index
int64 0
100k
| blob_id
stringlengths 40
40
| code
stringlengths 7
7.27M
| steps
sequencelengths 1
1.25k
| error
bool 2
classes |
---|---|---|---|---|
99,700 | 5bfb8cbfed8aa9854b64ce9eb400a88fc664c503 | """
Copyright 2018 Goldman Sachs.
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 gs_quant.instrument import Instrument, IRSwap
import datetime as dt
def test_from_dict():
swap = IRSwap('Receive', '3m', 'USD', fixedRate=0, notionalAmount=1)
properties = swap.as_dict()
new_swap = Instrument.from_dict(properties)
assert swap == new_swap
# setting a datetime.date should work in a dictionary
swap = IRSwap('Receive', dt.date(2030, 4, 11), 'USD', fixedRate='atm+5', notionalAmount=1)
properties = swap.as_dict()
new_swap = Instrument.from_dict(properties)
assert swap == new_swap
| [
"\"\"\"\nCopyright 2018 Goldman Sachs.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the License for the\nspecific language governing permissions and limitations\nunder the License.\n\"\"\"\n\nfrom gs_quant.instrument import Instrument, IRSwap\nimport datetime as dt\n\n\ndef test_from_dict():\n swap = IRSwap('Receive', '3m', 'USD', fixedRate=0, notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n\n # setting a datetime.date should work in a dictionary\n swap = IRSwap('Receive', dt.date(2030, 4, 11), 'USD', fixedRate='atm+5', notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n",
"<docstring token>\nfrom gs_quant.instrument import Instrument, IRSwap\nimport datetime as dt\n\n\ndef test_from_dict():\n swap = IRSwap('Receive', '3m', 'USD', fixedRate=0, notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n swap = IRSwap('Receive', dt.date(2030, 4, 11), 'USD', fixedRate='atm+5',\n notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n",
"<docstring token>\n<import token>\n\n\ndef test_from_dict():\n swap = IRSwap('Receive', '3m', 'USD', fixedRate=0, notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n swap = IRSwap('Receive', dt.date(2030, 4, 11), 'USD', fixedRate='atm+5',\n notionalAmount=1)\n properties = swap.as_dict()\n new_swap = Instrument.from_dict(properties)\n assert swap == new_swap\n",
"<docstring token>\n<import token>\n<function token>\n"
] | false |
99,701 | 12bfabb025f71c2fdef336f422e2709cc672395e | import pygame
class Controller:
def __init__(self, number):
self.buttonMap = { 0:"x", 1:"a", 2:"b", 3:"y", 4:"l", 5:"r", 8:"select", 9:"start"}
pygame.init()
## find controllers
pygame.joystick.init()
self.joystick = pygame.joystick.Joystick(number)
self.joystick.init()
self.clock = pygame.time.Clock()
self.done = False
def getInput(self):
# EVENT PROCESSING STEP
pygame.event.get()
## axis control ##
for i in range( 2 ):
axis = self.joystick.get_axis(i)
if axis >= 0.9 or axis == -1.0:
if axis > 0 and i == 0:
return "right"
if axis < 0 and i == 0:
return "left"
if axis > 0 and i == 1:
return "down"
if axis < 0 and i == 1:
return "up"
## button control ##
for i in range(10):
button = self.joystick.get_button(i)
if button == 1:
return self.buttonMap[i]
return None
| [
"import pygame\n\n\n\nclass Controller:\n def __init__(self, number):\n self.buttonMap = { 0:\"x\", 1:\"a\", 2:\"b\", 3:\"y\", 4:\"l\", 5:\"r\", 8:\"select\", 9:\"start\"} \n pygame.init()\n ## find controllers\n pygame.joystick.init()\n self.joystick = pygame.joystick.Joystick(number)\n self.joystick.init()\n self.clock = pygame.time.Clock()\n self.done = False\n\n def getInput(self):\n # EVENT PROCESSING STEP\n pygame.event.get()\n ## axis control ##\n for i in range( 2 ):\n axis = self.joystick.get_axis(i)\n if axis >= 0.9 or axis == -1.0:\n if axis > 0 and i == 0:\n return \"right\"\n if axis < 0 and i == 0:\n return \"left\"\n if axis > 0 and i == 1:\n return \"down\"\n if axis < 0 and i == 1:\n return \"up\"\n \n ## button control ##\n for i in range(10):\n button = self.joystick.get_button(i)\n if button == 1:\n return self.buttonMap[i]\n return None\n",
"import pygame\n\n\nclass Controller:\n\n def __init__(self, number):\n self.buttonMap = {(0): 'x', (1): 'a', (2): 'b', (3): 'y', (4): 'l',\n (5): 'r', (8): 'select', (9): 'start'}\n pygame.init()\n pygame.joystick.init()\n self.joystick = pygame.joystick.Joystick(number)\n self.joystick.init()\n self.clock = pygame.time.Clock()\n self.done = False\n\n def getInput(self):\n pygame.event.get()\n for i in range(2):\n axis = self.joystick.get_axis(i)\n if axis >= 0.9 or axis == -1.0:\n if axis > 0 and i == 0:\n return 'right'\n if axis < 0 and i == 0:\n return 'left'\n if axis > 0 and i == 1:\n return 'down'\n if axis < 0 and i == 1:\n return 'up'\n for i in range(10):\n button = self.joystick.get_button(i)\n if button == 1:\n return self.buttonMap[i]\n return None\n",
"<import token>\n\n\nclass Controller:\n\n def __init__(self, number):\n self.buttonMap = {(0): 'x', (1): 'a', (2): 'b', (3): 'y', (4): 'l',\n (5): 'r', (8): 'select', (9): 'start'}\n pygame.init()\n pygame.joystick.init()\n self.joystick = pygame.joystick.Joystick(number)\n self.joystick.init()\n self.clock = pygame.time.Clock()\n self.done = False\n\n def getInput(self):\n pygame.event.get()\n for i in range(2):\n axis = self.joystick.get_axis(i)\n if axis >= 0.9 or axis == -1.0:\n if axis > 0 and i == 0:\n return 'right'\n if axis < 0 and i == 0:\n return 'left'\n if axis > 0 and i == 1:\n return 'down'\n if axis < 0 and i == 1:\n return 'up'\n for i in range(10):\n button = self.joystick.get_button(i)\n if button == 1:\n return self.buttonMap[i]\n return None\n",
"<import token>\n\n\nclass Controller:\n\n def __init__(self, number):\n self.buttonMap = {(0): 'x', (1): 'a', (2): 'b', (3): 'y', (4): 'l',\n (5): 'r', (8): 'select', (9): 'start'}\n pygame.init()\n pygame.joystick.init()\n self.joystick = pygame.joystick.Joystick(number)\n self.joystick.init()\n self.clock = pygame.time.Clock()\n self.done = False\n <function token>\n",
"<import token>\n\n\nclass Controller:\n <function token>\n <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,702 | 53d0d5922edd3cdc1f747da74463b4859c91f443 | f = open('dataset_24465_4.txt')
l = []
for line in f:
l.append(line.rstrip())
f.close()
l.reverse()
content = '\n'.join(l)
n = open('file2.txt', 'w')
n.write(content)
n.close()
# 2 method
# with open('file1.txt', 'r') as f, open('file2.txt', 'w') as n:
# a = reversed(f.read())
# for x in a:
# print(x) | [
"f = open('dataset_24465_4.txt')\nl = []\n\nfor line in f:\n\tl.append(line.rstrip())\n\nf.close()\nl.reverse()\ncontent = '\\n'.join(l)\n\nn = open('file2.txt', 'w')\nn.write(content)\nn.close()\n\n\n# 2 method\n# with open('file1.txt', 'r') as f, open('file2.txt', 'w') as n:\n# \ta = reversed(f.read())\n# \tfor x in a:\n# \t\tprint(x)",
"f = open('dataset_24465_4.txt')\nl = []\nfor line in f:\n l.append(line.rstrip())\nf.close()\nl.reverse()\ncontent = '\\n'.join(l)\nn = open('file2.txt', 'w')\nn.write(content)\nn.close()\n",
"<assignment token>\nfor line in f:\n l.append(line.rstrip())\nf.close()\nl.reverse()\n<assignment token>\nn.write(content)\nn.close()\n",
"<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,703 | a165a284f3e029351182a16423ec25227a4f57e9 | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',name="login"),
url(r'^logout/$', 'core.views.logout', name="logout"),
url(r'^register/$', 'core.views.register',name="register"),
url(r'^$', 'core.views.home', name="home"),
url(r'^dashboard/$', 'core.views.dashboard', name="dashboard"),
) | [
"from django.conf.urls import patterns, url\n\nurlpatterns = patterns('',\n\turl(r'^login/$', 'django.contrib.auth.views.login',name=\"login\"),\n url(r'^logout/$', 'core.views.logout', name=\"logout\"),\n url(r'^register/$', 'core.views.register',name=\"register\"),\n url(r'^$', 'core.views.home', name=\"home\"),\n url(r'^dashboard/$', 'core.views.dashboard', name=\"dashboard\"),\n)",
"from django.conf.urls import patterns, url\nurlpatterns = patterns('', url('^login/$',\n 'django.contrib.auth.views.login', name='login'), url('^logout/$',\n 'core.views.logout', name='logout'), url('^register/$',\n 'core.views.register', name='register'), url('^$', 'core.views.home',\n name='home'), url('^dashboard/$', 'core.views.dashboard', name='dashboard')\n )\n",
"<import token>\nurlpatterns = patterns('', url('^login/$',\n 'django.contrib.auth.views.login', name='login'), url('^logout/$',\n 'core.views.logout', name='logout'), url('^register/$',\n 'core.views.register', name='register'), url('^$', 'core.views.home',\n name='home'), url('^dashboard/$', 'core.views.dashboard', name='dashboard')\n )\n",
"<import token>\n<assignment token>\n"
] | false |
99,704 | 4af0b163e3ab85b1afd987827871470ba6bcdde2 | # -*- coding: utf-8 -*-
# Lista en python
lista = ["Francia","México", "Dinamarca", "Rusia"]
# Ciclo for que recorre una lista con la variable ele
# Seguido de esto, se imprime el contenido de cada indice con
# el número de caracteres del String
print("Contenido de lista con String's")
for ele in lista:
print(ele, len(ele))
#Uso de rango sencillo en un ciclo for
print("ciclo for en un rango especifico")
for a in range(-4, 5):
print(a)
#Uso de rango un poco más apropiado
# Creamos una lista
palabras = ["cero", "Uno", "Dos", "tres", "Cuatro", "Cinco", "Seis"]
# Usamos un ciclo for que recorre la lista con la variable num
# Imprime el indice de la variable num multiplicado por 10 y el contenido de este
print("Ciclo for en una lista diferente")
for num in range(len(palabras)):
print(num * 10, palabras[num])
print("-----------")
| [
"# -*- coding: utf-8 -*-\n\n\n# Lista en python \n\nlista = [\"Francia\",\"México\", \"Dinamarca\", \"Rusia\"]\n\n# Ciclo for que recorre una lista con la variable ele\n# Seguido de esto, se imprime el contenido de cada indice con \n# el número de caracteres del String\n\nprint(\"Contenido de lista con String's\")\n\nfor ele in lista:\n print(ele, len(ele))\n \n \n#Uso de rango sencillo en un ciclo for\n\nprint(\"ciclo for en un rango especifico\")\nfor a in range(-4, 5):\n print(a)\n \n\n\n#Uso de rango un poco más apropiado\n# Creamos una lista\n\npalabras = [\"cero\", \"Uno\", \"Dos\", \"tres\", \"Cuatro\", \"Cinco\", \"Seis\"]\n\n# Usamos un ciclo for que recorre la lista con la variable num \n# Imprime el indice de la variable num multiplicado por 10 y el contenido de este\n\nprint(\"Ciclo for en una lista diferente\")\nfor num in range(len(palabras)):\n print(num * 10, palabras[num])\n print(\"-----------\")\n",
"lista = ['Francia', 'México', 'Dinamarca', 'Rusia']\nprint(\"Contenido de lista con String's\")\nfor ele in lista:\n print(ele, len(ele))\nprint('ciclo for en un rango especifico')\nfor a in range(-4, 5):\n print(a)\npalabras = ['cero', 'Uno', 'Dos', 'tres', 'Cuatro', 'Cinco', 'Seis']\nprint('Ciclo for en una lista diferente')\nfor num in range(len(palabras)):\n print(num * 10, palabras[num])\n print('-----------')\n",
"<assignment token>\nprint(\"Contenido de lista con String's\")\nfor ele in lista:\n print(ele, len(ele))\nprint('ciclo for en un rango especifico')\nfor a in range(-4, 5):\n print(a)\n<assignment token>\nprint('Ciclo for en una lista diferente')\nfor num in range(len(palabras)):\n print(num * 10, palabras[num])\n print('-----------')\n",
"<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,705 | f8dbf2752029b183c26660237c777d8fca686b87 | from tkinter import *
from tkinter import messagebox
from tkinter import font
import pyqrcode
import os
win = Tk()
win.title("QR Code Generator")
# Code Generation
def generate():
if len(subject.get()) != 0:
global myQR
myQR = pyqrcode.create(subject.get())
qrImage = myQR.xbm(scale=6)
global photo
photo = BitmapImage(data=qrImage)
else:
messagebox.showerror("Error", "Please enter the subject")
try:
showCode()
except:
pass
# Code Showing
def showCode():
global photo
notificationLabel.config(image=photo)
sublabel.config(text="Showing QR Code for: " + subject.get())
if __name__ == '__main__':
subLab = Label(win, text="Enter Subject", font=("Helvetica", 12))
subLab.grid(row=0, column=0, sticky=N + S + E + W)
subject = StringVar()
subjectEntry = Entry(win, textvariable=subject, font=("Helvetica", 12))
subjectEntry.grid(row=0, column=1, sticky=N + S + E + W)
createBtn = Button(win, text="Create QR Code", font=("Helvetica", 12), width=15, command=generate)
createBtn.grid(row=0, column=3, sticky=N + S + E + W)
notificationLabel = Label(win)
notificationLabel.grid(row=2, column=1, sticky=N + S + E + W)\
sublabel = Label(win, text="")
sublabel.grid(row=3, column=1, sticky=N + S + E + W)
# Making Responsive Layout
totalRows = 3
totalCols = 5
for row in range(totalRows + 1):
win.grid_rowconfigure(row, weight=1)
for col in range(totalCols + 1):
win.grid_columnconfigure(col, weight=1)
win.mainloop()
| [
"from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import font\nimport pyqrcode\nimport os\n\nwin = Tk()\nwin.title(\"QR Code Generator\")\n\n# Code Generation\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n \n else:\n messagebox.showerror(\"Error\", \"Please enter the subject\")\n \n try:\n showCode()\n \n except:\n pass\n\n# Code Showing\ndef showCode():\n global photo\n notificationLabel.config(image=photo)\n sublabel.config(text=\"Showing QR Code for: \" + subject.get())\n\nif __name__ == '__main__':\n subLab = Label(win, text=\"Enter Subject\", font=(\"Helvetica\", 12))\n subLab.grid(row=0, column=0, sticky=N + S + E + W)\n\n subject = StringVar()\n subjectEntry = Entry(win, textvariable=subject, font=(\"Helvetica\", 12))\n subjectEntry.grid(row=0, column=1, sticky=N + S + E + W)\n\n createBtn = Button(win, text=\"Create QR Code\", font=(\"Helvetica\", 12), width=15, command=generate)\n createBtn.grid(row=0, column=3, sticky=N + S + E + W)\n\n notificationLabel = Label(win)\n notificationLabel.grid(row=2, column=1, sticky=N + S + E + W)\\\n \n sublabel = Label(win, text=\"\")\n sublabel.grid(row=3, column=1, sticky=N + S + E + W)\n\n # Making Responsive Layout\n totalRows = 3\n totalCols = 5\n\n for row in range(totalRows + 1):\n win.grid_rowconfigure(row, weight=1)\n\n for col in range(totalCols + 1):\n win.grid_columnconfigure(col, weight=1)\n\n win.mainloop()\n",
"from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import font\nimport pyqrcode\nimport os\nwin = Tk()\nwin.title('QR Code Generator')\n\n\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n else:\n messagebox.showerror('Error', 'Please enter the subject')\n try:\n showCode()\n except:\n pass\n\n\ndef showCode():\n global photo\n notificationLabel.config(image=photo)\n sublabel.config(text='Showing QR Code for: ' + subject.get())\n\n\nif __name__ == '__main__':\n subLab = Label(win, text='Enter Subject', font=('Helvetica', 12))\n subLab.grid(row=0, column=0, sticky=N + S + E + W)\n subject = StringVar()\n subjectEntry = Entry(win, textvariable=subject, font=('Helvetica', 12))\n subjectEntry.grid(row=0, column=1, sticky=N + S + E + W)\n createBtn = Button(win, text='Create QR Code', font=('Helvetica', 12),\n width=15, command=generate)\n createBtn.grid(row=0, column=3, sticky=N + S + E + W)\n notificationLabel = Label(win)\n notificationLabel.grid(row=2, column=1, sticky=N + S + E + W)\n sublabel = Label(win, text='')\n sublabel.grid(row=3, column=1, sticky=N + S + E + W)\n totalRows = 3\n totalCols = 5\n for row in range(totalRows + 1):\n win.grid_rowconfigure(row, weight=1)\n for col in range(totalCols + 1):\n win.grid_columnconfigure(col, weight=1)\n win.mainloop()\n",
"<import token>\nwin = Tk()\nwin.title('QR Code Generator')\n\n\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n else:\n messagebox.showerror('Error', 'Please enter the subject')\n try:\n showCode()\n except:\n pass\n\n\ndef showCode():\n global photo\n notificationLabel.config(image=photo)\n sublabel.config(text='Showing QR Code for: ' + subject.get())\n\n\nif __name__ == '__main__':\n subLab = Label(win, text='Enter Subject', font=('Helvetica', 12))\n subLab.grid(row=0, column=0, sticky=N + S + E + W)\n subject = StringVar()\n subjectEntry = Entry(win, textvariable=subject, font=('Helvetica', 12))\n subjectEntry.grid(row=0, column=1, sticky=N + S + E + W)\n createBtn = Button(win, text='Create QR Code', font=('Helvetica', 12),\n width=15, command=generate)\n createBtn.grid(row=0, column=3, sticky=N + S + E + W)\n notificationLabel = Label(win)\n notificationLabel.grid(row=2, column=1, sticky=N + S + E + W)\n sublabel = Label(win, text='')\n sublabel.grid(row=3, column=1, sticky=N + S + E + W)\n totalRows = 3\n totalCols = 5\n for row in range(totalRows + 1):\n win.grid_rowconfigure(row, weight=1)\n for col in range(totalCols + 1):\n win.grid_columnconfigure(col, weight=1)\n win.mainloop()\n",
"<import token>\n<assignment token>\nwin.title('QR Code Generator')\n\n\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n else:\n messagebox.showerror('Error', 'Please enter the subject')\n try:\n showCode()\n except:\n pass\n\n\ndef showCode():\n global photo\n notificationLabel.config(image=photo)\n sublabel.config(text='Showing QR Code for: ' + subject.get())\n\n\nif __name__ == '__main__':\n subLab = Label(win, text='Enter Subject', font=('Helvetica', 12))\n subLab.grid(row=0, column=0, sticky=N + S + E + W)\n subject = StringVar()\n subjectEntry = Entry(win, textvariable=subject, font=('Helvetica', 12))\n subjectEntry.grid(row=0, column=1, sticky=N + S + E + W)\n createBtn = Button(win, text='Create QR Code', font=('Helvetica', 12),\n width=15, command=generate)\n createBtn.grid(row=0, column=3, sticky=N + S + E + W)\n notificationLabel = Label(win)\n notificationLabel.grid(row=2, column=1, sticky=N + S + E + W)\n sublabel = Label(win, text='')\n sublabel.grid(row=3, column=1, sticky=N + S + E + W)\n totalRows = 3\n totalCols = 5\n for row in range(totalRows + 1):\n win.grid_rowconfigure(row, weight=1)\n for col in range(totalCols + 1):\n win.grid_columnconfigure(col, weight=1)\n win.mainloop()\n",
"<import token>\n<assignment token>\n<code token>\n\n\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n else:\n messagebox.showerror('Error', 'Please enter the subject')\n try:\n showCode()\n except:\n pass\n\n\ndef showCode():\n global photo\n notificationLabel.config(image=photo)\n sublabel.config(text='Showing QR Code for: ' + subject.get())\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n\n\ndef generate():\n if len(subject.get()) != 0:\n global myQR\n myQR = pyqrcode.create(subject.get())\n qrImage = myQR.xbm(scale=6)\n global photo\n photo = BitmapImage(data=qrImage)\n else:\n messagebox.showerror('Error', 'Please enter the subject')\n try:\n showCode()\n except:\n pass\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,706 | 6ab1c42f414f9609c8c563df9068ea0a09300f1a | # Find the contiguous subarray within an array (containing at least one
# number, with at least one number greater than 0) which has the largest sum.
#
# For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
# the contiguous subarray [4,-1,2,1] has the largest sum = 6.
class Solution(object):
def max_subarray_pos(self, arr):
left = 0
right = 0
i = 0
the_max = 0
the_sum = 0
for j in range(len(arr)):
the_sum += arr[j]
if the_sum < 0:
the_sum = 0
i = j + 1
elif the_sum > the_max:
the_max = the_sum
left = i
right = j
return arr[left: right + 1]
def max_subarray(self, arr):
the_max = 0
the_sum = 0
for j in range(len(arr)):
the_sum += arr[j]
if the_sum < 0:
the_sum = 0
elif the_sum > the_max:
the_max = the_sum
return the_max
if __name__ == '__main__':
the_arr = [2, 1, 4]
obj = Solution()
print(obj.max_subarray_pos(the_arr))
| [
"# Find the contiguous subarray within an array (containing at least one\n# number, with at least one number greater than 0) which has the largest sum.\n#\n# For example, given the array [-2,1,-3,4,-1,2,1,-5,4],\n# the contiguous subarray [4,-1,2,1] has the largest sum = 6.\n\nclass Solution(object):\n def max_subarray_pos(self, arr):\n left = 0\n right = 0\n i = 0\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n i = j + 1\n elif the_sum > the_max:\n the_max = the_sum\n left = i\n right = j\n return arr[left: right + 1]\n\n def max_subarray(self, arr):\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n elif the_sum > the_max:\n the_max = the_sum\n return the_max\n\n\nif __name__ == '__main__':\n the_arr = [2, 1, 4]\n obj = Solution()\n print(obj.max_subarray_pos(the_arr))\n",
"class Solution(object):\n\n def max_subarray_pos(self, arr):\n left = 0\n right = 0\n i = 0\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n i = j + 1\n elif the_sum > the_max:\n the_max = the_sum\n left = i\n right = j\n return arr[left:right + 1]\n\n def max_subarray(self, arr):\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n elif the_sum > the_max:\n the_max = the_sum\n return the_max\n\n\nif __name__ == '__main__':\n the_arr = [2, 1, 4]\n obj = Solution()\n print(obj.max_subarray_pos(the_arr))\n",
"class Solution(object):\n\n def max_subarray_pos(self, arr):\n left = 0\n right = 0\n i = 0\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n i = j + 1\n elif the_sum > the_max:\n the_max = the_sum\n left = i\n right = j\n return arr[left:right + 1]\n\n def max_subarray(self, arr):\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n elif the_sum > the_max:\n the_max = the_sum\n return the_max\n\n\n<code token>\n",
"class Solution(object):\n\n def max_subarray_pos(self, arr):\n left = 0\n right = 0\n i = 0\n the_max = 0\n the_sum = 0\n for j in range(len(arr)):\n the_sum += arr[j]\n if the_sum < 0:\n the_sum = 0\n i = j + 1\n elif the_sum > the_max:\n the_max = the_sum\n left = i\n right = j\n return arr[left:right + 1]\n <function token>\n\n\n<code token>\n",
"class Solution(object):\n <function token>\n <function token>\n\n\n<code token>\n",
"<class token>\n<code token>\n"
] | false |
99,707 | 783d5fde36212720f67a5dfcc90d1b0f6b05d177 | """
This test module ensures default and custom engines load correctly from
configuration.
"""
import yaml
from insights_messaging.appbuilder import AppBuilder
from insights_messaging.engine import Engine
class CustomEngine(Engine):
pass
class MockFS:
pass
class MockFormat:
pass
CONFIG1 = yaml.load(
"""
plugins:
default_component_enabled: true
packages: []
configs: []
service:
engine:
name: insights_messaging.tests.test_pluggable_engine.CustomEngine
kwargs:
format: insights_messaging.tests.test_pluggable_engine.MockFormat
extract_timeout: 20
extract_tmp_dir: ${TMP_DIR:/tmp}
target_components: []
consumer:
name: insights_messaging.consumers.Consumer
publisher:
name: insights_messaging.publishers.Publisher
downloader:
name: insights_messaging.tests.test_pluggable_engine.MockFS
""",
Loader=yaml.SafeLoader,
)
CONFIG2 = yaml.load(
"""
plugins:
default_component_enabled: true
packages: []
configs: []
service:
extract_timeout: 20
extract_tmp_dir: ${TMP_DIR:/tmp}
format: insights_messaging.tests.test_pluggable_engine.MockFormat
target_components: []
consumer:
name: insights_messaging.consumers.Consumer
publisher:
name: insights_messaging.publishers.Publisher
downloader:
name: insights_messaging.tests.test_pluggable_engine.MockFS
""",
Loader=yaml.SafeLoader,
)
def test_configs_engine():
""" Should use the specified CustomEngine """
app = AppBuilder(CONFIG1).build_app()
assert isinstance(app.engine, CustomEngine)
assert app.engine.Formatter is MockFormat
assert app.engine.extract_timeout == 20
assert app.engine.extract_tmp_dir == "/tmp"
def test_config1_engine():
""" Should use the default insights_messaging.engine.Engine """
app = AppBuilder(CONFIG2).build_app()
assert isinstance(app.engine, Engine) and not isinstance(app.engine, CustomEngine)
assert app.engine.Formatter is MockFormat
assert app.engine.extract_timeout == 20
assert app.engine.extract_tmp_dir == "/tmp"
| [
"\"\"\"\nThis test module ensures default and custom engines load correctly from\nconfiguration.\n\"\"\"\nimport yaml\nfrom insights_messaging.appbuilder import AppBuilder\nfrom insights_messaging.engine import Engine\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\nCONFIG1 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n engine:\n name: insights_messaging.tests.test_pluggable_engine.CustomEngine\n kwargs:\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\",\n Loader=yaml.SafeLoader,\n)\n\n\nCONFIG2 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\",\n Loader=yaml.SafeLoader,\n)\n\n\ndef test_configs_engine():\n \"\"\" Should use the specified CustomEngine \"\"\"\n app = AppBuilder(CONFIG1).build_app()\n assert isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == \"/tmp\"\n\n\ndef test_config1_engine():\n \"\"\" Should use the default insights_messaging.engine.Engine \"\"\"\n app = AppBuilder(CONFIG2).build_app()\n assert isinstance(app.engine, Engine) and not isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == \"/tmp\"\n",
"<docstring token>\nimport yaml\nfrom insights_messaging.appbuilder import AppBuilder\nfrom insights_messaging.engine import Engine\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\nCONFIG1 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n engine:\n name: insights_messaging.tests.test_pluggable_engine.CustomEngine\n kwargs:\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\"\n , Loader=yaml.SafeLoader)\nCONFIG2 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\"\n , Loader=yaml.SafeLoader)\n\n\ndef test_configs_engine():\n \"\"\" Should use the specified CustomEngine \"\"\"\n app = AppBuilder(CONFIG1).build_app()\n assert isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n\n\ndef test_config1_engine():\n \"\"\" Should use the default insights_messaging.engine.Engine \"\"\"\n app = AppBuilder(CONFIG2).build_app()\n assert isinstance(app.engine, Engine) and not isinstance(app.engine,\n CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n",
"<docstring token>\n<import token>\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\nCONFIG1 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n engine:\n name: insights_messaging.tests.test_pluggable_engine.CustomEngine\n kwargs:\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\"\n , Loader=yaml.SafeLoader)\nCONFIG2 = yaml.load(\n \"\"\"\nplugins:\n default_component_enabled: true\n packages: []\n configs: []\nservice:\n extract_timeout: 20\n extract_tmp_dir: ${TMP_DIR:/tmp}\n format: insights_messaging.tests.test_pluggable_engine.MockFormat\n target_components: []\n consumer:\n name: insights_messaging.consumers.Consumer\n publisher:\n name: insights_messaging.publishers.Publisher\n downloader:\n name: insights_messaging.tests.test_pluggable_engine.MockFS\n\"\"\"\n , Loader=yaml.SafeLoader)\n\n\ndef test_configs_engine():\n \"\"\" Should use the specified CustomEngine \"\"\"\n app = AppBuilder(CONFIG1).build_app()\n assert isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n\n\ndef test_config1_engine():\n \"\"\" Should use the default insights_messaging.engine.Engine \"\"\"\n app = AppBuilder(CONFIG2).build_app()\n assert isinstance(app.engine, Engine) and not isinstance(app.engine,\n CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n",
"<docstring token>\n<import token>\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\n<assignment token>\n\n\ndef test_configs_engine():\n \"\"\" Should use the specified CustomEngine \"\"\"\n app = AppBuilder(CONFIG1).build_app()\n assert isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n\n\ndef test_config1_engine():\n \"\"\" Should use the default insights_messaging.engine.Engine \"\"\"\n app = AppBuilder(CONFIG2).build_app()\n assert isinstance(app.engine, Engine) and not isinstance(app.engine,\n CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n",
"<docstring token>\n<import token>\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\n<assignment token>\n\n\ndef test_configs_engine():\n \"\"\" Should use the specified CustomEngine \"\"\"\n app = AppBuilder(CONFIG1).build_app()\n assert isinstance(app.engine, CustomEngine)\n assert app.engine.Formatter is MockFormat\n assert app.engine.extract_timeout == 20\n assert app.engine.extract_tmp_dir == '/tmp'\n\n\n<function token>\n",
"<docstring token>\n<import token>\n\n\nclass CustomEngine(Engine):\n pass\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\n<assignment token>\n<function token>\n<function token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass MockFS:\n pass\n\n\nclass MockFormat:\n pass\n\n\n<assignment token>\n<function token>\n<function token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass MockFormat:\n pass\n\n\n<assignment token>\n<function token>\n<function token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<function token>\n<function token>\n"
] | false |
99,708 | ef5d828f1c009f8309a060bbe6cc6ae3ee221243 | from . import db
class Airport(db.Model):
# "iata_code","lat","long"
__tablename__ = 'airports'
id = db.Column(db.Integer, primary_key=True)
iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True)
lat = db.Column(db.Float, unique=False, nullable=False, index=True)
long = db.Column(db.Float, unique=False, nullable=False, index=True)
def __repr__(self):
return '<Airport %r>' % self.iata_code
@staticmethod
def insert_test_airports():
# "MAD",40.47193,-3.56264
a_01 = Airport(
iata_code='MAD',
lat=40.47193, # N
long=-3.56264) # W
# "TLV",32.0114,34.8867
a_02 = Airport(
iata_code='TLV',
lat=32.0114, # N
long=34.8867) # E
# "IAH",29.9844,-95.3414
a_03 = Airport(
iata_code='IAH',
lat=29.9844, # N
long=-95.3414) # W
db.session.add_all([a_01, a_02, a_03])
db.session.commit()
class Destination(db.Model):
# "city","country","iata_code","lat","long"
__tablename__ = 'destinations'
id = db.Column(db.Integer, primary_key=True)
iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True)
city = db.Column(db.String(100), unique=True, nullable=False, index=False)
country = db.Column(db.String(100), unique=False, nullable=False, index=True)
lat = db.Column(db.Float, unique=False, nullable=False, index=True)
long = db.Column(db.Float, unique=False, nullable=False, index=True)
def __repr__(self):
return '<Destination %r>' % (self.iata_code + ' - ' + self.city)
@staticmethod
def insert_test_destinations():
# "Paris","France","CDG",49.0128,2.55
d_01 = Destination(
iata_code='CDG',
city='Paris',
country='France',
lat=49.0128, # N
long=2.55) # E
# "London","United Kingdom","LHR",51.4706,-0.46194
d_02 = Destination(
iata_code='LHR',
city='London',
country='United Kingdom',
lat=51.4706, # N
long=-0.46194) # W
# "Rome","Italy","FCO",41.80028,12.23889
d_03 = Destination(
iata_code='FCO',
city='Rome',
country='Italy',
lat=41.80028, # N
long=12.23889) # E
# "New York","United States","JFK",40.6398,-73.7789
d_04 = Destination(
iata_code='JFK',
city='New York',
country='United States',
lat=40.6398, # N
long=-73.7789) # W
# "Madrid","Spain","MAD",40.47193,-3.56264
d_05 = Destination(
iata_code='MAD',
city='Madrid',
country='Spain',
lat=40.47193, # N
long=-3.56264) # W
# "Tel Aviv","Israel","TLV",32.0114,34.8867
d_06 = Destination(
iata_code='TLV',
city='Tel Aviv',
country='Israel',
lat=32.0114, # N
long=34.8867) # E
# "Houston","United States","IAH",29.9844,-95.3414
d_07 = Destination(
iata_code='IAH',
city='Houston',
country='United States',
lat=29.9844, # N
long=-95.3414) # W
db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])
db.session.commit()
class Weather(db.Model):
# "iata_code","month","min_temperature_celsius","max_temperature_celsius","daily_precipitation_mm"
__tablename__ = 'weather_conditions'
id = db.Column(db.Integer, primary_key=True)
iata_code = db.Column(db.String(3), unique=False, nullable=False, index=False)
month = db.Column(db.String(10), unique=False, nullable=False, index=False)
min_temperature_celsius = db.Column(db.Float, unique=False, nullable=False, index=True)
max_temperature_celsius = db.Column(db.Float, unique=False, nullable=False, index=True)
daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=False, index=False)
def __repr__(self):
return '<Weather %r>' % (self.iata_code + ' ' + self.month)
@staticmethod
def insert_test_weather_conditions():
pass
# "MAD","January","2.0","12.9","1.6"
w_01 = Weather(
iata_code='MAD',
month='January',
min_temperature_celsius=2.0,
max_temperature_celsius=12.9,
daily_precipitation_mm=1.6)
# "TLV","January","12.8","22.0","3.3"
w_02 = Weather(
iata_code='TLV',
month='January',
min_temperature_celsius=12.8,
max_temperature_celsius=22.0,
daily_precipitation_mm=3.3)
# "IAH","January","8.2","19.6","2.4"
w_03 = Weather(
iata_code='IAH',
month='January',
min_temperature_celsius=8.2,
max_temperature_celsius=19.6,
daily_precipitation_mm=2.4)
db.session.add_all([w_01, w_02, w_03])
db.session.commit()
| [
"from . import db\n\n\nclass Airport(db.Model):\n # \"iata_code\",\"lat\",\"long\"\n __tablename__ = 'airports'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Airport %r>' % self.iata_code\n\n @staticmethod\n def insert_test_airports():\n # \"MAD\",40.47193,-3.56264\n a_01 = Airport(\n iata_code='MAD',\n lat=40.47193, # N \n long=-3.56264) # W\n # \"TLV\",32.0114,34.8867\n a_02 = Airport(\n iata_code='TLV',\n lat=32.0114, # N \n long=34.8867) # E\n # \"IAH\",29.9844,-95.3414\n a_03 = Airport(\n iata_code='IAH',\n lat=29.9844, # N\n long=-95.3414) # W\n db.session.add_all([a_01, a_02, a_03])\n db.session.commit()\n\n\nclass Destination(db.Model):\n # \"city\",\"country\",\"iata_code\",\"lat\",\"long\"\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True)\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index=True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n # \"Paris\",\"France\",\"CDG\",49.0128,2.55\n d_01 = Destination(\n iata_code='CDG',\n city='Paris',\n country='France',\n lat=49.0128, # N\n long=2.55) # E\n # \"London\",\"United Kingdom\",\"LHR\",51.4706,-0.46194\n d_02 = Destination(\n iata_code='LHR',\n city='London',\n country='United Kingdom',\n lat=51.4706, # N\n long=-0.46194) # W\n # \"Rome\",\"Italy\",\"FCO\",41.80028,12.23889\n d_03 = Destination(\n iata_code='FCO',\n city='Rome',\n country='Italy',\n lat=41.80028, # N\n long=12.23889) # E\n # \"New York\",\"United States\",\"JFK\",40.6398,-73.7789\n d_04 = Destination(\n iata_code='JFK',\n city='New York',\n country='United States',\n lat=40.6398, # N\n long=-73.7789) # W\n # \"Madrid\",\"Spain\",\"MAD\",40.47193,-3.56264\n d_05 = Destination(\n iata_code='MAD',\n city='Madrid',\n country='Spain',\n lat=40.47193, # N \n long=-3.56264) # W\n # \"Tel Aviv\",\"Israel\",\"TLV\",32.0114,34.8867\n d_06 = Destination(\n iata_code='TLV',\n city='Tel Aviv',\n country='Israel',\n lat=32.0114, # N \n long=34.8867) # E\n # \"Houston\",\"United States\",\"IAH\",29.9844,-95.3414\n d_07 = Destination(\n iata_code='IAH',\n city='Houston',\n country='United States',\n lat=29.9844, # N\n long=-95.3414) # W\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n # \"iata_code\",\"month\",\"min_temperature_celsius\",\"max_temperature_celsius\",\"daily_precipitation_mm\"\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index=False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=False, index=False)\n \n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n # \"MAD\",\"January\",\"2.0\",\"12.9\",\"1.6\"\n w_01 = Weather(\n iata_code='MAD',\n month='January',\n min_temperature_celsius=2.0,\n max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n # \"TLV\",\"January\",\"12.8\",\"22.0\",\"3.3\"\n w_02 = Weather(\n iata_code='TLV',\n month='January',\n min_temperature_celsius=12.8,\n max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n # \"IAH\",\"January\",\"8.2\",\"19.6\",\"2.4\"\n w_03 = Weather(\n iata_code='IAH',\n month='January',\n min_temperature_celsius=8.2,\n max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"from . import db\n\n\nclass Airport(db.Model):\n __tablename__ = 'airports'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Airport %r>' % self.iata_code\n\n @staticmethod\n def insert_test_airports():\n a_01 = Airport(iata_code='MAD', lat=40.47193, long=-3.56264)\n a_02 = Airport(iata_code='TLV', lat=32.0114, long=34.8867)\n a_03 = Airport(iata_code='IAH', lat=29.9844, long=-95.3414)\n db.session.add_all([a_01, a_02, a_03])\n db.session.commit()\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n\n\nclass Airport(db.Model):\n __tablename__ = 'airports'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Airport %r>' % self.iata_code\n\n @staticmethod\n def insert_test_airports():\n a_01 = Airport(iata_code='MAD', lat=40.47193, long=-3.56264)\n a_02 = Airport(iata_code='TLV', lat=32.0114, long=34.8867)\n a_03 = Airport(iata_code='IAH', lat=29.9844, long=-95.3414)\n db.session.add_all([a_01, a_02, a_03])\n db.session.commit()\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n\n\nclass Airport(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __repr__(self):\n return '<Airport %r>' % self.iata_code\n\n @staticmethod\n def insert_test_airports():\n a_01 = Airport(iata_code='MAD', lat=40.47193, long=-3.56264)\n a_02 = Airport(iata_code='TLV', lat=32.0114, long=34.8867)\n a_03 = Airport(iata_code='IAH', lat=29.9844, long=-95.3414)\n db.session.add_all([a_01, a_02, a_03])\n db.session.commit()\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n\n\nclass Airport(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __repr__(self):\n return '<Airport %r>' % self.iata_code\n <function token>\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n\n\nclass Airport(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n\n\nclass Destination(db.Model):\n __tablename__ = 'destinations'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=True, nullable=False, index=True\n )\n city = db.Column(db.String(100), unique=True, nullable=False, index=False)\n country = db.Column(db.String(100), unique=False, nullable=False, index\n =True)\n lat = db.Column(db.Float, unique=False, nullable=False, index=True)\n long = db.Column(db.Float, unique=False, nullable=False, index=True)\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n\n\nclass Destination(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __repr__(self):\n return '<Destination %r>' % (self.iata_code + ' - ' + self.city)\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n\n\nclass Destination(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n @staticmethod\n def insert_test_destinations():\n d_01 = Destination(iata_code='CDG', city='Paris', country='France',\n lat=49.0128, long=2.55)\n d_02 = Destination(iata_code='LHR', city='London', country=\n 'United Kingdom', lat=51.4706, long=-0.46194)\n d_03 = Destination(iata_code='FCO', city='Rome', country='Italy',\n lat=41.80028, long=12.23889)\n d_04 = Destination(iata_code='JFK', city='New York', country=\n 'United States', lat=40.6398, long=-73.7789)\n d_05 = Destination(iata_code='MAD', city='Madrid', country='Spain',\n lat=40.47193, long=-3.56264)\n d_06 = Destination(iata_code='TLV', city='Tel Aviv', country=\n 'Israel', lat=32.0114, long=34.8867)\n d_07 = Destination(iata_code='IAH', city='Houston', country=\n 'United States', lat=29.9844, long=-95.3414)\n db.session.add_all([d_01, d_02, d_03, d_04, d_05, d_06, d_07])\n db.session.commit()\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n\n\nclass Destination(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Weather(db.Model):\n __tablename__ = 'weather_conditions'\n id = db.Column(db.Integer, primary_key=True)\n iata_code = db.Column(db.String(3), unique=False, nullable=False, index\n =False)\n month = db.Column(db.String(10), unique=False, nullable=False, index=False)\n min_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n max_temperature_celsius = db.Column(db.Float, unique=False, nullable=\n False, index=True)\n daily_precipitation_mm = db.Column(db.Float, unique=False, nullable=\n False, index=False)\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Weather(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n\n @staticmethod\n def insert_test_weather_conditions():\n pass\n w_01 = Weather(iata_code='MAD', month='January',\n min_temperature_celsius=2.0, max_temperature_celsius=12.9,\n daily_precipitation_mm=1.6)\n w_02 = Weather(iata_code='TLV', month='January',\n min_temperature_celsius=12.8, max_temperature_celsius=22.0,\n daily_precipitation_mm=3.3)\n w_03 = Weather(iata_code='IAH', month='January',\n min_temperature_celsius=8.2, max_temperature_celsius=19.6,\n daily_precipitation_mm=2.4)\n db.session.add_all([w_01, w_02, w_03])\n db.session.commit()\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Weather(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __repr__(self):\n return '<Weather %r>' % (self.iata_code + ' ' + self.month)\n <function token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Weather(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,709 | f1c56de18ede21573cffa728dc9884f232d38f37 | from app import app, db
from app.models import User
from config import Config
from flask_api import status
import unittest
class UserModelCase(unittest.TestCase):
def setUp(self):
self.good_user = User(username='', password='')
db.session.add(self.good_user)
db.session.commit()
pass
def tearDown(self):
User.query.delete()
db.session.commit()
pass
# Login Tests
if __name__ == '__main__':
unittest.main(verbosity=2)
| [
"from app import app, db\nfrom app.models import User\nfrom config import Config\nfrom flask_api import status\nimport unittest\n\n\nclass UserModelCase(unittest.TestCase):\n\n def setUp(self):\n self.good_user = User(username='', password='')\n db.session.add(self.good_user)\n db.session.commit()\n pass\n\n def tearDown(self):\n User.query.delete()\n db.session.commit()\n pass\n\n # Login Tests\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n",
"from app import app, db\nfrom app.models import User\nfrom config import Config\nfrom flask_api import status\nimport unittest\n\n\nclass UserModelCase(unittest.TestCase):\n\n def setUp(self):\n self.good_user = User(username='', password='')\n db.session.add(self.good_user)\n db.session.commit()\n pass\n\n def tearDown(self):\n User.query.delete()\n db.session.commit()\n pass\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n",
"<import token>\n\n\nclass UserModelCase(unittest.TestCase):\n\n def setUp(self):\n self.good_user = User(username='', password='')\n db.session.add(self.good_user)\n db.session.commit()\n pass\n\n def tearDown(self):\n User.query.delete()\n db.session.commit()\n pass\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n",
"<import token>\n\n\nclass UserModelCase(unittest.TestCase):\n\n def setUp(self):\n self.good_user = User(username='', password='')\n db.session.add(self.good_user)\n db.session.commit()\n pass\n\n def tearDown(self):\n User.query.delete()\n db.session.commit()\n pass\n\n\n<code token>\n",
"<import token>\n\n\nclass UserModelCase(unittest.TestCase):\n\n def setUp(self):\n self.good_user = User(username='', password='')\n db.session.add(self.good_user)\n db.session.commit()\n pass\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass UserModelCase(unittest.TestCase):\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<class token>\n<code token>\n"
] | false |
99,710 | 7184c6e45e8c8653d0777335a9f3f92b06af80ff | """MobileCallPromotion Problem"""
def promotion(time, sum_price):
"""Return price of Promotion from given timecall(second)"""
time = second_to_minute(time)
for (pro, price) in [(24*60, 150), (12*60, 100), (8*60, 80), (3*60, 40), (60, 15), (20, 10)]:
sum_price = sum_price + (time//pro)*price
time = time % pro
oneminute = time - 3
return sum_price + oneminute if oneminute > 0 else sum_price
def second_to_minute(time):
"""Convert second to minute"""
if time % 60 != 0:
time = time + 60
return time // 60
print(promotion(int(input()), 0))
| [
"\"\"\"MobileCallPromotion Problem\"\"\"\ndef promotion(time, sum_price):\n \"\"\"Return price of Promotion from given timecall(second)\"\"\"\n time = second_to_minute(time)\n for (pro, price) in [(24*60, 150), (12*60, 100), (8*60, 80), (3*60, 40), (60, 15), (20, 10)]:\n sum_price = sum_price + (time//pro)*price\n time = time % pro\n oneminute = time - 3\n return sum_price + oneminute if oneminute > 0 else sum_price\n\ndef second_to_minute(time):\n \"\"\"Convert second to minute\"\"\"\n if time % 60 != 0:\n time = time + 60\n return time // 60\n\nprint(promotion(int(input()), 0))\n",
"<docstring token>\n\n\ndef promotion(time, sum_price):\n \"\"\"Return price of Promotion from given timecall(second)\"\"\"\n time = second_to_minute(time)\n for pro, price in [(24 * 60, 150), (12 * 60, 100), (8 * 60, 80), (3 * \n 60, 40), (60, 15), (20, 10)]:\n sum_price = sum_price + time // pro * price\n time = time % pro\n oneminute = time - 3\n return sum_price + oneminute if oneminute > 0 else sum_price\n\n\ndef second_to_minute(time):\n \"\"\"Convert second to minute\"\"\"\n if time % 60 != 0:\n time = time + 60\n return time // 60\n\n\nprint(promotion(int(input()), 0))\n",
"<docstring token>\n\n\ndef promotion(time, sum_price):\n \"\"\"Return price of Promotion from given timecall(second)\"\"\"\n time = second_to_minute(time)\n for pro, price in [(24 * 60, 150), (12 * 60, 100), (8 * 60, 80), (3 * \n 60, 40), (60, 15), (20, 10)]:\n sum_price = sum_price + time // pro * price\n time = time % pro\n oneminute = time - 3\n return sum_price + oneminute if oneminute > 0 else sum_price\n\n\ndef second_to_minute(time):\n \"\"\"Convert second to minute\"\"\"\n if time % 60 != 0:\n time = time + 60\n return time // 60\n\n\n<code token>\n",
"<docstring token>\n\n\ndef promotion(time, sum_price):\n \"\"\"Return price of Promotion from given timecall(second)\"\"\"\n time = second_to_minute(time)\n for pro, price in [(24 * 60, 150), (12 * 60, 100), (8 * 60, 80), (3 * \n 60, 40), (60, 15), (20, 10)]:\n sum_price = sum_price + time // pro * price\n time = time % pro\n oneminute = time - 3\n return sum_price + oneminute if oneminute > 0 else sum_price\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,711 | a0432b8b1b1fee6fdb61aa08eb2d99eb4d785d1a | import sys
def dfs(vertex, inverse_adj, visited):
if visited[vertex] == 2:
return True
if visited[vertex] == 1:
return False
visited[vertex] = 2
for precursor in inverse_adj[vertex]:
if dfs(precursor, inverse_adj, visited):
return True
visited[vertex] = 1
return False
for line in sys.stdin:
G = eval(line)
res = 0
visited = [0 for _ in range(len(G))]
inverse_adj = [set() for _ in range(len(G))]
for i in range(len(G)):
for j in range(len(G)):
if G[i][j]:
inverse_adj[j].add(i)
else:
continue
for i in range(len(G)):
if dfs(i, inverse_adj, visited):
res = 1
break
print(res)
| [
"import sys\n\n\ndef dfs(vertex, inverse_adj, visited):\n if visited[vertex] == 2:\n return True\n if visited[vertex] == 1:\n return False\n\n visited[vertex] = 2\n for precursor in inverse_adj[vertex]:\n if dfs(precursor, inverse_adj, visited):\n return True\n\n visited[vertex] = 1\n return False\n\n\nfor line in sys.stdin:\n G = eval(line)\n res = 0\n visited = [0 for _ in range(len(G))]\n inverse_adj = [set() for _ in range(len(G))]\n for i in range(len(G)):\n for j in range(len(G)):\n if G[i][j]:\n inverse_adj[j].add(i)\n else:\n continue\n for i in range(len(G)):\n if dfs(i, inverse_adj, visited):\n res = 1\n break\n print(res)\n\n\n\n",
"import sys\n\n\ndef dfs(vertex, inverse_adj, visited):\n if visited[vertex] == 2:\n return True\n if visited[vertex] == 1:\n return False\n visited[vertex] = 2\n for precursor in inverse_adj[vertex]:\n if dfs(precursor, inverse_adj, visited):\n return True\n visited[vertex] = 1\n return False\n\n\nfor line in sys.stdin:\n G = eval(line)\n res = 0\n visited = [(0) for _ in range(len(G))]\n inverse_adj = [set() for _ in range(len(G))]\n for i in range(len(G)):\n for j in range(len(G)):\n if G[i][j]:\n inverse_adj[j].add(i)\n else:\n continue\n for i in range(len(G)):\n if dfs(i, inverse_adj, visited):\n res = 1\n break\n print(res)\n",
"<import token>\n\n\ndef dfs(vertex, inverse_adj, visited):\n if visited[vertex] == 2:\n return True\n if visited[vertex] == 1:\n return False\n visited[vertex] = 2\n for precursor in inverse_adj[vertex]:\n if dfs(precursor, inverse_adj, visited):\n return True\n visited[vertex] = 1\n return False\n\n\nfor line in sys.stdin:\n G = eval(line)\n res = 0\n visited = [(0) for _ in range(len(G))]\n inverse_adj = [set() for _ in range(len(G))]\n for i in range(len(G)):\n for j in range(len(G)):\n if G[i][j]:\n inverse_adj[j].add(i)\n else:\n continue\n for i in range(len(G)):\n if dfs(i, inverse_adj, visited):\n res = 1\n break\n print(res)\n",
"<import token>\n\n\ndef dfs(vertex, inverse_adj, visited):\n if visited[vertex] == 2:\n return True\n if visited[vertex] == 1:\n return False\n visited[vertex] = 2\n for precursor in inverse_adj[vertex]:\n if dfs(precursor, inverse_adj, visited):\n return True\n visited[vertex] = 1\n return False\n\n\n<code token>\n",
"<import token>\n<function token>\n<code token>\n"
] | false |
99,712 | c38d4ecdd88e744bd5874ce11879cd2c9c524369 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-10 09:00
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
dependencies = [
('catalog', '0004_item'),
]
operations = [
migrations.CreateModel(
name='ItemPhoto',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('photo', sorl.thumbnail.fields.ImageField(upload_to='catalog', verbose_name='image')),
('ordering', models.IntegerField(default=100, verbose_name='ordering')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='catalog.Item', verbose_name='catalog item')),
],
options={
'ordering': ['ordering'],
'verbose_name': 'photo',
'verbose_name_plural': 'photos',
},
),
]
| [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.9.1 on 2016-01-10 09:00\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport sorl.thumbnail.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalog', '0004_item'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ItemPhoto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('photo', sorl.thumbnail.fields.ImageField(upload_to='catalog', verbose_name='image')),\n ('ordering', models.IntegerField(default=100, verbose_name='ordering')),\n ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='catalog.Item', verbose_name='catalog item')),\n ],\n options={\n 'ordering': ['ordering'],\n 'verbose_name': 'photo',\n 'verbose_name_plural': 'photos',\n },\n ),\n ]\n",
"from __future__ import unicode_literals\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport sorl.thumbnail.fields\n\n\nclass Migration(migrations.Migration):\n dependencies = [('catalog', '0004_item')]\n operations = [migrations.CreateModel(name='ItemPhoto', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('photo', sorl.thumbnail.fields.\n ImageField(upload_to='catalog', verbose_name='image')), ('ordering',\n models.IntegerField(default=100, verbose_name='ordering')), ('item',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'catalog.Item', verbose_name='catalog item'))], options={'ordering':\n ['ordering'], 'verbose_name': 'photo', 'verbose_name_plural':\n 'photos'})]\n",
"<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('catalog', '0004_item')]\n operations = [migrations.CreateModel(name='ItemPhoto', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('photo', sorl.thumbnail.fields.\n ImageField(upload_to='catalog', verbose_name='image')), ('ordering',\n models.IntegerField(default=100, verbose_name='ordering')), ('item',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'catalog.Item', verbose_name='catalog item'))], options={'ordering':\n ['ordering'], 'verbose_name': 'photo', 'verbose_name_plural':\n 'photos'})]\n",
"<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n",
"<import token>\n<class token>\n"
] | false |
99,713 | e75c945a93f5ef5a20554e9b034de41eff5afa98 | from django.test import TestCase, RequestFactory
from django.db.models.query import QuerySet
from solos.views import index, SoloDetailView
from solos.models import Solo
from albums.models import Album, Track
"""
Note that RequestFactory vs self.client.get('/', {'instrument': 'drums'})
depends on the amount of isolation you want your unittest to be run on
with requestfactory giving more isolation
"""
class SolosBaseTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
@classmethod
def setUpClass(cls):
# note difference with python2 which would be super(IndexViewTestCase,cls).setUpClass()
super().setUpClass()
cls.no_funny_hats = Album.objects.create(
name='No Funny Hats',
slug = 'no-funny-hats'
)
cls.bugle_call_rag = Track.objects.create(
name='Bugle Call Rag',
slug = 'bugle-call-rag',
)
cls.drum_solo = Solo.objects.create(
instrument='drums',
artist='Rich',
track=cls.bugle_call_rag,
slug='rich'
)
cls.giant_steps = Album.objects.create(
name='Giant Steps',
slug='giant-steps'
)
cls.mr_pc = Track.objects.create(
name='Mr. PC',
slug = 'mr-pc',
album=cls.giant_steps
)
cls.bass_solo = Solo.objects.create(
instrument='saxophone',
artist='Coltrane',
track=cls.my_pc,
slug = 'coltrane'
)
class IndexViewTestCase(SolosBaseTestCase):
"""
Subclass from SolosBaseTestCase for DRY
"""
def test_index_view_basic(self):
"""
Test that the view returns a 200 response and uses
correct template
"""
request = self.factory.get("/")
with self.assertTemplateUsed('solos/index.html'):
response = index(request)
self.assertEqual(response.status_code, 200)
def test_index_view_returns_solos(self):
"""
Test that the index view will attempt to return solos if
query parameters exist
"""
# use self.client instead of RequestFactory
# so that we can access response.context dictionary
#* using client depends on existence of the URL unlike requestfactory
response = self.client.get('/', {'instrument': 'drums'})
solos = response.context['solos']
self.assertIs(type(solos), QuerySet)
self.assertEqual(len(solos), 1)
self.assertEqual(solos[0].artist,'Rich')
self.assertIs(
type(response.context['solos']),
QuerySet
)
class SoloViewTestCase(SolosBaseTestCase):
def setUp(self):
self.factory = RequestFactory()
def test_basic(self):
"""
Test that the solo view returns a 200 response, uses
the correct template and has the correct context
"""
#* using request factory is independent of existence of the path and calls the view as a function.
#* it may well be get('nonesense/') unless this argument is needed in the view function
#* it calls the view as a regular function and tests its effects
request = self.factory.get('/solos/1/')
# since view is class based
response =SoloDetailView.as_view()(
request,
pk=self.drum_solo.pk
)
self.assertEqual(response.status_code, 200) # check that the drum is in database
self.assertEqual(response.context_data['solo'].artist, 'Rich') # check that this drummers' name is correct
# check that the template used for this detail is correct
with self.assertTemplateUsed('solos/solo_detail.html'):
# use render since we use the request factory
response.render()
| [
"from django.test import TestCase, RequestFactory\nfrom django.db.models.query import QuerySet\nfrom solos.views import index, SoloDetailView\nfrom solos.models import Solo\nfrom albums.models import Album, Track\n\n\"\"\"\nNote that RequestFactory vs self.client.get('/', {'instrument': 'drums'}) \ndepends on the amount of isolation you want your unittest to be run on\nwith requestfactory giving more isolation\n\"\"\"\n\nclass SolosBaseTestCase(TestCase):\n \n def setUp(self):\n self.factory = RequestFactory()\n\n @classmethod\n def setUpClass(cls):\n # note difference with python2 which would be super(IndexViewTestCase,cls).setUpClass()\n super().setUpClass() \n cls.no_funny_hats = Album.objects.create(\n name='No Funny Hats',\n slug = 'no-funny-hats'\n )\n\n cls.bugle_call_rag = Track.objects.create(\n name='Bugle Call Rag',\n slug = 'bugle-call-rag',\n )\n \n cls.drum_solo = Solo.objects.create(\n instrument='drums',\n artist='Rich',\n track=cls.bugle_call_rag,\n slug='rich'\n )\n \n cls.giant_steps = Album.objects.create(\n name='Giant Steps',\n slug='giant-steps'\n )\n\n cls.mr_pc = Track.objects.create(\n name='Mr. PC',\n slug = 'mr-pc',\n album=cls.giant_steps\n )\n\n cls.bass_solo = Solo.objects.create(\n instrument='saxophone',\n artist='Coltrane',\n track=cls.my_pc,\n slug = 'coltrane'\n )\n \n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get(\"/\")\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n # use self.client instead of RequestFactory \n # so that we can access response.context dictionary\n #* using client depends on existence of the URL unlike requestfactory\n response = self.client.get('/', {'instrument': 'drums'}) \n\n solos = response.context['solos']\n \n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist,'Rich')\n\n self.assertIs(\n type(response.context['solos']),\n QuerySet\n )\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n \n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n #* using request factory is independent of existence of the path and calls the view as a function.\n #* it may well be get('nonesense/') unless this argument is needed in the view function\n #* it calls the view as a regular function and tests its effects\n request = self.factory.get('/solos/1/')\n # since view is class based\n response =SoloDetailView.as_view()(\n request,\n pk=self.drum_solo.pk\n )\n\n self.assertEqual(response.status_code, 200) # check that the drum is in database\n self.assertEqual(response.context_data['solo'].artist, 'Rich') # check that this drummers' name is correct\n # check that the template used for this detail is correct\n with self.assertTemplateUsed('solos/solo_detail.html'):\n # use render since we use the request factory\n response.render()\n",
"from django.test import TestCase, RequestFactory\nfrom django.db.models.query import QuerySet\nfrom solos.views import index, SoloDetailView\nfrom solos.models import Solo\nfrom albums.models import Album, Track\n<docstring token>\n\n\nclass SolosBaseTestCase(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.no_funny_hats = Album.objects.create(name='No Funny Hats', slug\n ='no-funny-hats')\n cls.bugle_call_rag = Track.objects.create(name='Bugle Call Rag',\n slug='bugle-call-rag')\n cls.drum_solo = Solo.objects.create(instrument='drums', artist=\n 'Rich', track=cls.bugle_call_rag, slug='rich')\n cls.giant_steps = Album.objects.create(name='Giant Steps', slug=\n 'giant-steps')\n cls.mr_pc = Track.objects.create(name='Mr. PC', slug='mr-pc', album\n =cls.giant_steps)\n cls.bass_solo = Solo.objects.create(instrument='saxophone', artist=\n 'Coltrane', track=cls.my_pc, slug='coltrane')\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n\n\nclass SolosBaseTestCase(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.no_funny_hats = Album.objects.create(name='No Funny Hats', slug\n ='no-funny-hats')\n cls.bugle_call_rag = Track.objects.create(name='Bugle Call Rag',\n slug='bugle-call-rag')\n cls.drum_solo = Solo.objects.create(instrument='drums', artist=\n 'Rich', track=cls.bugle_call_rag, slug='rich')\n cls.giant_steps = Album.objects.create(name='Giant Steps', slug=\n 'giant-steps')\n cls.mr_pc = Track.objects.create(name='Mr. PC', slug='mr-pc', album\n =cls.giant_steps)\n cls.bass_solo = Solo.objects.create(instrument='saxophone', artist=\n 'Coltrane', track=cls.my_pc, slug='coltrane')\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n\n\nclass SolosBaseTestCase(TestCase):\n <function token>\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.no_funny_hats = Album.objects.create(name='No Funny Hats', slug\n ='no-funny-hats')\n cls.bugle_call_rag = Track.objects.create(name='Bugle Call Rag',\n slug='bugle-call-rag')\n cls.drum_solo = Solo.objects.create(instrument='drums', artist=\n 'Rich', track=cls.bugle_call_rag, slug='rich')\n cls.giant_steps = Album.objects.create(name='Giant Steps', slug=\n 'giant-steps')\n cls.mr_pc = Track.objects.create(name='Mr. PC', slug='mr-pc', album\n =cls.giant_steps)\n cls.bass_solo = Solo.objects.create(instrument='saxophone', artist=\n 'Coltrane', track=cls.my_pc, slug='coltrane')\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n\n\nclass SolosBaseTestCase(TestCase):\n <function token>\n <function token>\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n \"\"\" \n Subclass from SolosBaseTestCase for DRY\n \"\"\"\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n <docstring token>\n\n def test_index_view_basic(self):\n \"\"\"\n Test that the view returns a 200 response and uses\n correct template\n \"\"\"\n request = self.factory.get('/')\n with self.assertTemplateUsed('solos/index.html'):\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n <docstring token>\n <function token>\n\n def test_index_view_returns_solos(self):\n \"\"\"\n Test that the index view will attempt to return solos if \n query parameters exist\n \"\"\"\n response = self.client.get('/', {'instrument': 'drums'})\n solos = response.context['solos']\n self.assertIs(type(solos), QuerySet)\n self.assertEqual(len(solos), 1)\n self.assertEqual(solos[0].artist, 'Rich')\n self.assertIs(type(response.context['solos']), QuerySet)\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n\n\nclass IndexViewTestCase(SolosBaseTestCase):\n <docstring token>\n <function token>\n <function token>\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n<class token>\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_basic(self):\n \"\"\"\n Test that the solo view returns a 200 response, uses\n the correct template and has the correct context\n \"\"\"\n request = self.factory.get('/solos/1/')\n response = SoloDetailView.as_view()(request, pk=self.drum_solo.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.context_data['solo'].artist, 'Rich')\n with self.assertTemplateUsed('solos/solo_detail.html'):\n response.render()\n",
"<import token>\n<docstring token>\n<class token>\n<class token>\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n <function token>\n",
"<import token>\n<docstring token>\n<class token>\n<class token>\n\n\nclass SoloViewTestCase(SolosBaseTestCase):\n <function token>\n <function token>\n",
"<import token>\n<docstring token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,714 | 0e00e28f65e9fe05342d94fbc95b516c7e2a2fcd | from django.contrib import admin
from .models import Hood,Calls
class HoodAdmin(admin.ModelAdmin):
admin.site.register(Hood)
admin.site.register(Calls)
| [
"from django.contrib import admin\nfrom .models import Hood,Calls\n\nclass HoodAdmin(admin.ModelAdmin):\n admin.site.register(Hood)\n admin.site.register(Calls)\n",
"from django.contrib import admin\nfrom .models import Hood, Calls\n\n\nclass HoodAdmin(admin.ModelAdmin):\n admin.site.register(Hood)\n admin.site.register(Calls)\n",
"<import token>\n\n\nclass HoodAdmin(admin.ModelAdmin):\n admin.site.register(Hood)\n admin.site.register(Calls)\n",
"<import token>\n<class token>\n"
] | false |
99,715 | c627bbeb927c333573f9203ffbee3ea26fae0c8d | #!/usr/bin/env python3
from paint import paint
import sys
from time import sleep
import numpy as np
"""
# Sample format to answer pattern questions
# assuming the pattern would be frag0:
..*
**.
.**
#############################################
# Reread the instructions for assignment 1: make sure
# that you have the version with due date SUNDAY.
# Every student submits their own assignment.
* Delete the names and ccids below, and put
# the names and ccids of all members of your group, including you.
# name ccid
cole stevenson crsteven
Duncan Krammer krammer
Shridhar Patel spatel1
Colman Koivisto koivisto
Khrystina Vrublevska vrublevs
#############################################
# Your answer to question 1-a:
a glider needs a grid that's unbounded for the whole simulation
.*.
..*
***
this is because the glider doens't die out and constantly moves
across the grid
#############################################
# Your answer to question 1-b:
a gosper glider gun is a pattern whose number of cells alive at any one
time is unbounded
.......................**.........**..
......................*.*.........**..
**.......**...........**..............
**......*.*...........................
........**......**....................
................*.*...................
................*.....................
...................................**.
...................................*.*
...................................*..
......................................
......................................
........................***...........
........................*.............
.........................*............
that is because the gun shoots out gliders and those gliders keep upping
the live cell count indefinitely
#############################################
# Your answer to question 2:
For starters, life-np uses the numpy array instaad of the row array, which
makes the indexing easier. The num-nbrs function from life.py isnt' needed
in life-np because it's functionality is merged with next state.
Concerning the "infinity" of the grid in life.py: the grid isn't actually
infinite. The file has a pad function that adds new rows and columns anytime
the pattern reaches the edge.
Having a guarded board simplifies num_nbrsbecause the function doesn't have
to check for the edges of the board on each iteration. There is no need to
pass the board dimentions as arguments to it.
#############################################
# Follow the assignment 1 instructions and
# make the changes requested in question 3.
# Then come back and fill in the answer to
# question 3-c:
..........*...
...........*..
.........***..
..............
..............
iterations 260
#############################################
"""
"""
based on life-np.py from course repo
"""
PTS = '.*#'
DEAD, ALIVE, WALL = 0, 1, 2
DCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]
def point(r, c, cols): return c + r*cols
"""
board functions
* represent board as 2-dimensional array
"""
def get_board():
B = []
print(sys.argv[1])
with open(sys.argv[1]) as f:
for line in f:
B.append(line.rstrip().replace(' ', ''))
rows, cols = len(B), len(B[0])
for j in range(1, rows):
assert(len(B[j]) == cols)
return B, rows, cols
def convert_board(B, r, c): # from string to numpy array
A = np.zeros((r, c), dtype=np.int8)
for j in range(r):
for k in range(c):
if B[j][k] == ACH:
A[j, k] = ALIVE
return A
def expand_grid(A, r, c, t): # add t empty rows and columns on each side
N = np.zeros((r+2*t, c+2*t), dtype=np.int8)
for j in range(r):
for k in range(c):
if A[j][k] == ALIVE:
N[j+t, k+t] = ALIVE
return N, r+2*t, c+2*t
def print_array(A, r, c):
print('')
for j in range(r):
out = ''
for k in range(c):
out += ACH if A[j, k] == ALIVE else DCH
print(out)
def show_array(A, r, c):
for j in range(r):
line = ''
for k in range(c):
line += str(A[j, k])
print(line)
print('')
"""
Conway's next-state formula
"""
def next_state(A, r, c):
N = np.zeros((r, c), dtype=np.int8)
changed = False
for j in range(r):
for k in range(c):
num = 0
if j > 0 and k > 0 and A[j-1, k-1] == ALIVE:
num += 1
if j > 0 and A[j-1, k] == ALIVE:
num += 1
if j > 0 and k < c-1 and A[j-1, k+1] == ALIVE:
num += 1
if k > 0 and A[j, k-1] == ALIVE:
num += 1
if k < c-1 and A[j, k+1] == ALIVE:
num += 1
if j < r-1 and k > 0 and A[j+1, k-1] == ALIVE:
num += 1
if j < r-1 and A[j+1, k] == ALIVE:
num += 1
if j < r-1 and k < c-1 and A[j+1, k+1] == ALIVE:
num += 1
if A[j, k] == ALIVE:
if num > 1 and num < 4:
N[j, k] = ALIVE
else:
N[j, k] = DEAD
changed = True
else:
if num == 3:
N[j, k] = ALIVE
changed = True
else:
N[j, k] = DEAD
return N, changed
#############################################
"""
Provide your code for the function
next_state2 that (for the usual bounded
rectangular grid) calls the function num_nbrs2,
and delete the raise error statement:
"""
def next_state2(A, r, c):
N = np.zeros((r, c), dtype=np.int8)
changed = False
for j in range(r):
for k in range(c):
num = num_nbrs2(A, r, j, c, k)
if A[j, k] == ALIVE:
if num > 1 and num < 4:
N[j, k] = ALIVE
else:
N[j, k] = DEAD
changed = True
else:
if num == 3:
N[j, k] = ALIVE
changed = True
else:
N[j, k] = DEAD
return N, changed
#############################################
#############################################
"""
Provide your code for the function
num_nbrs2 here and delete the raise error
statement:
"""
def num_nbrs2(A, r, j, c, k):
num = 0
if j > 0 and k > 0 and A[j-1, k-1] == ALIVE:
num += 1
if j > 0 and A[j-1, k] == ALIVE:
num += 1
if j > 0 and k < c-1 and A[j-1, k+1] == ALIVE:
num += 1
if k > 0 and A[j, k-1] == ALIVE:
num += 1
if k < c-1 and A[j, k+1] == ALIVE:
num += 1
if j < r-1 and k > 0 and A[j+1, k-1] == ALIVE:
num += 1
if j < r-1 and A[j+1, k] == ALIVE:
num += 1
if j < r-1 and k < c-1 and A[j+1, k+1] == ALIVE:
num += 1
return num
#############################################
#############################################
"""
Provide your code for the function
next_state_torus here and delete the raise
error statement:
"""
def next_state_torus(A, r, c):
N = np.zeros((r, c), dtype=np.int8)
changed = False
for j in range(r):
for k in range(c):
num = num_nbrs_torus(A, r, j, c, k)
if A[j, k] == ALIVE:
if num > 1 and num < 4:
N[j, k] = ALIVE
else:
N[j, k] = DEAD
changed = True
else:
if num == 3:
N[j, k] = ALIVE
changed = True
else:
N[j, k] = DEAD
return N, changed
#############################################
#############################################
"""
Provide your code for the function
num_nbrs_torus here and delete the raise
error statement:
"""
def num_nbrs_torus(A, r, j, c, k):
""" Counts number of neighbours for a torus.
Args:
A: the numpy board
r: number of rows in the board
j: current row of the cell in the iteration
c: number of columns in the board
k: current column of the cell in the iteration
Returns:
num: the number of neighbours
"""
num = 0
r = r - 1 # to account for off by one errors
c = c - 1
if j == 0:
if k == 0:
# top left corner edge case
if A[r, c] == ALIVE:
num += 1
if A[j, c] == ALIVE:
num += 1
if A[j+1, c] == ALIVE:
num += 1
if A[r, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j+1, k+1] == ALIVE:
num += 1
if k > 0 and k < c:
# top row minus corners edge cases
if A[r, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j+1, k-1] == ALIVE:
num += 1
if A[r, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j+1, k+1] == ALIVE:
num += 1
if k == c:
# top right corner edge case
if A[r, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j+1, k-1] == ALIVE:
num += 1
if A[r, 0] == ALIVE:
num += 1
if A[j, 0] == ALIVE:
num += 1
if A[j+1, 0] == ALIVE:
num += 1
if A[j+1,k] == ALIVE:
num += 1
if A[r, k] == ALIVE:
num += 1
if j > 0 and j < r:
if k == 0:
# left side minus corners edge cases
if A[j-1, c] == ALIVE:
num += 1
if A[j, c] == ALIVE:
num += 1
if A[j+1, c] == ALIVE:
num += 1
if A[j-1, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j+1, k+1] == ALIVE:
num += 1
if k > 0 and k < c:
# center
if A[j-1, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j+1, k-1] == ALIVE:
num += 1
if A[j-1, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j+1, k+1] == ALIVE:
num += 1
if k == c:
# right side minus corners edge cases
if A[j-1, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j+1, k-1] == ALIVE:
num += 1
if A[j-1, 0] == ALIVE:
num += 1
if A[j, 0] == ALIVE:
num += 1
if A[j+1, 0] == ALIVE:
num += 1
if A[j+1,k] == ALIVE:
num += 1
if A[j-1, k] == ALIVE:
num += 1
if j == r:
if k == 0:
# bottom left corner edge cases
if A[j-1, c] == ALIVE:
num += 1
if A[j, c] == ALIVE:
num += 1
if A[0, c] == ALIVE:
num += 1
if A[0, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j-1, k+1] == ALIVE:
num += 1
if k > 0 and k < c:
# bottom row minus corners edge cases
if A[0, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j-1, k-1] == ALIVE:
num += 1
if A[0, k+1] == ALIVE:
num += 1
if A[j, k+1] == ALIVE:
num += 1
if A[j-1, k+1] == ALIVE:
num += 1
if k == c:
# bottom right corner edge cases
if A[0, k-1] == ALIVE:
num += 1
if A[j, k-1] == ALIVE:
num += 1
if A[j-1, k-1] == ALIVE:
num += 1
if A[0, 0] == ALIVE:
num += 1
if A[j, 0] == ALIVE:
num += 1
if A[j-1, 0] == ALIVE:
num += 1
if A[j-1,k] == ALIVE:
num += 1
if A[0, k] == ALIVE:
num += 1
return num
#############################################
"""
input, output
"""
pause = 0.0
#############################################
"""
Modify interact as necessary to run the code:
"""
#############################################
def interact(max_itn):
itn = 0
B, r, c = get_board()
print(B)
X = convert_board(B, r, c)
A, r, c = expand_grid(X, r, c, 0)
print_array(A, r, c)
while itn <= max_itn:
sleep(pause)
newA, delta = next_state2(A, r, c)
if not delta:
break
itn += 1
A = newA
print_array(A, r, c)
print('\niterations', itn)
def main():
interact(259)
if __name__ == '__main__':
main()
| [
"#!/usr/bin/env python3\nfrom paint import paint\nimport sys\nfrom time import sleep\nimport numpy as np\n\"\"\"\n# Sample format to answer pattern questions \n# assuming the pattern would be frag0:\n..*\n**.\n.**\n#############################################\n# Reread the instructions for assignment 1: make sure\n# that you have the version with due date SUNDAY.\n# Every student submits their own assignment.\n* Delete the names and ccids below, and put\n# the names and ccids of all members of your group, including you. \n# name ccid\ncole stevenson crsteven\nDuncan Krammer krammer\nShridhar Patel spatel1\nColman Koivisto koivisto\nKhrystina Vrublevska vrublevs\n\n#############################################\n# Your answer to question 1-a:\n\na glider needs a grid that's unbounded for the whole simulation\n\n.*.\n..*\n***\n\nthis is because the glider doens't die out and constantly moves\nacross the grid\n\n#############################################\n# Your answer to question 1-b:\n\na gosper glider gun is a pattern whose number of cells alive at any one \ntime is unbounded\n\n.......................**.........**..\n......................*.*.........**..\n**.......**...........**..............\n**......*.*...........................\n........**......**....................\n................*.*...................\n................*.....................\n...................................**.\n...................................*.*\n...................................*..\n......................................\n......................................\n........................***...........\n........................*.............\n.........................*............\n\nthat is because the gun shoots out gliders and those gliders keep upping\nthe live cell count indefinitely\n\n#############################################\n# Your answer to question 2:\n\nFor starters, life-np uses the numpy array instaad of the row array, which \nmakes the indexing easier. The num-nbrs function from life.py isnt' needed\nin life-np because it's functionality is merged with next state. \n\nConcerning the \"infinity\" of the grid in life.py: the grid isn't actually \ninfinite. The file has a pad function that adds new rows and columns anytime\nthe pattern reaches the edge.\n\nHaving a guarded board simplifies num_nbrsbecause the function doesn't have \nto check for the edges of the board on each iteration. There is no need to\npass the board dimentions as arguments to it.\n\n#############################################\n# Follow the assignment 1 instructions and\n# make the changes requested in question 3.\n# Then come back and fill in the answer to\n# question 3-c:\n\n..........*...\n...........*..\n.........***..\n..............\n..............\n\niterations 260\n\n#############################################\n\"\"\"\n\"\"\"\nbased on life-np.py from course repo\n\"\"\"\n\n\nPTS = '.*#'\nDEAD, ALIVE, WALL = 0, 1, 2\nDCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]\n\n\ndef point(r, c, cols): return c + r*cols\n\n\"\"\"\nboard functions\n * represent board as 2-dimensional array\n\"\"\"\n\n\ndef get_board():\n\tB = []\n\tprint(sys.argv[1])\n\twith open(sys.argv[1]) as f:\n\t\tfor line in f:\n\t\t\tB.append(line.rstrip().replace(' ', ''))\n\t\trows, cols = len(B), len(B[0])\n\t\tfor j in range(1, rows):\n\t\t\tassert(len(B[j]) == cols)\n\t\treturn B, rows, cols\n\n\ndef convert_board(B, r, c): # from string to numpy array\n\tA = np.zeros((r, c), dtype=np.int8)\n\tfor j in range(r):\n\t\tfor k in range(c):\n\t\t\tif B[j][k] == ACH:\n\t\t\t\tA[j, k] = ALIVE\n\treturn A\n\n\ndef expand_grid(A, r, c, t): # add t empty rows and columns on each side\n\tN = np.zeros((r+2*t, c+2*t), dtype=np.int8)\n\tfor j in range(r):\n\t\tfor k in range(c):\n\t\t\tif A[j][k] == ALIVE:\n\t\t\t\tN[j+t, k+t] = ALIVE\n\treturn N, r+2*t, c+2*t\n\n\ndef print_array(A, r, c):\n\tprint('')\n\tfor j in range(r):\n\t\tout = ''\n\t\tfor k in range(c):\n\t\t\tout += ACH if A[j, k] == ALIVE else DCH\n\t\tprint(out)\n\n\ndef show_array(A, r, c):\n\tfor j in range(r):\n\t\tline = ''\n\t\tfor k in range(c):\n\t\t\tline += str(A[j, k])\n\t\tprint(line)\n\tprint('')\n\n\n\"\"\" \nConway's next-state formula\n\"\"\"\n\n\ndef next_state(A, r, c):\n\tN = np.zeros((r, c), dtype=np.int8)\n\tchanged = False\n\tfor j in range(r):\n\t\tfor k in range(c):\n\t\t\tnum = 0\n\t\t\tif j > 0 and k > 0 and A[j-1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif j > 0 and A[j-1, k] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif j > 0 and k < c-1 and A[j-1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif k > 0 and A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif k < c-1 and A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif j < r-1 and k > 0 and A[j+1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif j < r-1 and A[j+1, k] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif j < r-1 and k < c-1 and A[j+1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k] == ALIVE:\n\t\t\t\tif num > 1 and num < 4:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\t\t\t\t\tchanged = True\n\t\t\telse:\n\t\t\t\tif num == 3:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\t\tchanged = True\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\treturn N, changed\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnext_state2 that (for the usual bounded\nrectangular grid) calls the function num_nbrs2,\nand delete the raise error statement:\n\"\"\"\n\n\ndef next_state2(A, r, c):\n\tN = np.zeros((r, c), dtype=np.int8)\n\tchanged = False\n\tfor j in range(r):\n\t\tfor k in range(c):\n\t\t\tnum = num_nbrs2(A, r, j, c, k)\n\t\t\tif A[j, k] == ALIVE:\n\t\t\t\tif num > 1 and num < 4:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\t\t\t\t\tchanged = True\n\t\t\telse:\n\t\t\t\tif num == 3:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\t\tchanged = True\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\treturn N, changed\n#############################################\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnum_nbrs2 here and delete the raise error\nstatement:\n\"\"\"\n\n\ndef num_nbrs2(A, r, j, c, k):\n\tnum = 0\n\tif j > 0 and k > 0 and A[j-1, k-1] == ALIVE:\n\t\tnum += 1\n\tif j > 0 and A[j-1, k] == ALIVE:\n\t\tnum += 1\n\tif j > 0 and k < c-1 and A[j-1, k+1] == ALIVE:\n\t\tnum += 1\n\tif k > 0 and A[j, k-1] == ALIVE:\n\t\tnum += 1\n\tif k < c-1 and A[j, k+1] == ALIVE:\n\t\tnum += 1\n\tif j < r-1 and k > 0 and A[j+1, k-1] == ALIVE:\n\t\tnum += 1\n\tif j < r-1 and A[j+1, k] == ALIVE:\n\t\tnum += 1\n\tif j < r-1 and k < c-1 and A[j+1, k+1] == ALIVE:\n\t\tnum += 1\n\treturn num\n\t\n#############################################\n\n\n#############################################\n\"\"\" \nProvide your code for the function \nnext_state_torus here and delete the raise \nerror statement:\n\"\"\"\n\n\ndef next_state_torus(A, r, c):\n\tN = np.zeros((r, c), dtype=np.int8)\n\tchanged = False\n\tfor j in range(r):\n\t\tfor k in range(c):\n\t\t\tnum = num_nbrs_torus(A, r, j, c, k)\n\t\t\tif A[j, k] == ALIVE:\n\t\t\t\tif num > 1 and num < 4:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\t\t\t\t\tchanged = True\n\t\t\telse:\n\t\t\t\tif num == 3:\n\t\t\t\t\tN[j, k] = ALIVE\n\t\t\t\t\tchanged = True\n\t\t\t\telse:\n\t\t\t\t\tN[j, k] = DEAD\n\treturn N, changed\n#############################################\n\n#############################################\n\"\"\" \nProvide your code for the function \nnum_nbrs_torus here and delete the raise \nerror statement:\n\"\"\"\ndef num_nbrs_torus(A, r, j, c, k): \n\t\"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n\tnum = 0\n\tr = r - 1 # to account for off by one errors\n\tc = c - 1\n\tif j == 0:\n\t\tif k == 0:\n\t\t\t# top left corner edge case\n\t\t\tif A[r, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, c] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[r, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\tif k > 0 and k < c:\n\t\t\t# top row minus corners edge cases\n\t\t\tif A[r, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[r, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif k == c:\n\t\t\t# top right corner edge case\n\t\t\tif A[r, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[r, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif A[j+1,k] == ALIVE:\n\t\t\tnum += 1\n\t\tif A[r, k] == ALIVE:\n\t\t\tnum += 1\n\n\tif j > 0 and j < r:\n\t\tif k == 0:\n\t\t\t# left side minus corners edge cases\n\t\t\tif A[j-1, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, c] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[j-1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\tif k > 0 and k < c:\n\t\t\t# center\n\t\t\tif A[j-1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[j-1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif k == c:\n\t\t\t# right side minus corners edge cases\n\t\t\tif A[j-1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[j-1, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j+1, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif A[j+1,k] == ALIVE:\n\t\t\tnum += 1\n\t\tif A[j-1, k] == ALIVE:\n\t\t\tnum += 1\n\n\n\tif j == r:\n\t\tif k == 0:\n\t\t\t# bottom left corner edge cases\n\t\t\tif A[j-1, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, c] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[0, c] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[0, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j-1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\tif k > 0 and k < c:\n\t\t\t# bottom row minus corners edge cases\n\t\t\tif A[0, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j-1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[0, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j-1, k+1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif k == c:\n\t\t\t# bottom right corner edge cases\n\t\t\tif A[0, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j-1, k-1] == ALIVE:\n\t\t\t\tnum += 1\n\n\t\t\tif A[0, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\tif A[j-1, 0] == ALIVE:\n\t\t\t\tnum += 1\n\t\t\n\t\tif A[j-1,k] == ALIVE:\n\t\t\tnum += 1\n\t\tif A[0, k] == ALIVE:\n\t\t\tnum += 1\n\t\n\treturn num\n#############################################\n\n\n\"\"\"\ninput, output\n\"\"\"\n\npause = 0.0\n\n#############################################\n\"\"\" \nModify interact as necessary to run the code:\n\"\"\"\n#############################################\n\n\ndef interact(max_itn):\n\titn = 0\n\tB, r, c = get_board()\n\tprint(B)\n\tX = convert_board(B, r, c)\n\tA, r, c = expand_grid(X, r, c, 0)\n\tprint_array(A, r, c)\n\twhile itn <= max_itn:\n\t\tsleep(pause)\n\t\tnewA, delta = next_state2(A, r, c)\n\t\tif not delta:\n\t\t\tbreak\n\t\titn += 1\n\t\tA = newA\n\t\tprint_array(A, r, c)\n\tprint('\\niterations', itn)\n\n\ndef main():\n\tinteract(259)\n\n\nif __name__ == '__main__':\n\tmain()\n",
"from paint import paint\nimport sys\nfrom time import sleep\nimport numpy as np\n<docstring token>\nPTS = '.*#'\nDEAD, ALIVE, WALL = 0, 1, 2\nDCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n\n\ndef get_board():\n B = []\n print(sys.argv[1])\n with open(sys.argv[1]) as f:\n for line in f:\n B.append(line.rstrip().replace(' ', ''))\n rows, cols = len(B), len(B[0])\n for j in range(1, rows):\n assert len(B[j]) == cols\n return B, rows, cols\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\npause = 0.0\n<docstring token>\n\n\ndef interact(max_itn):\n itn = 0\n B, r, c = get_board()\n print(B)\n X = convert_board(B, r, c)\n A, r, c = expand_grid(X, r, c, 0)\n print_array(A, r, c)\n while itn <= max_itn:\n sleep(pause)\n newA, delta = next_state2(A, r, c)\n if not delta:\n break\n itn += 1\n A = newA\n print_array(A, r, c)\n print('\\niterations', itn)\n\n\ndef main():\n interact(259)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<docstring token>\nPTS = '.*#'\nDEAD, ALIVE, WALL = 0, 1, 2\nDCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n\n\ndef get_board():\n B = []\n print(sys.argv[1])\n with open(sys.argv[1]) as f:\n for line in f:\n B.append(line.rstrip().replace(' ', ''))\n rows, cols = len(B), len(B[0])\n for j in range(1, rows):\n assert len(B[j]) == cols\n return B, rows, cols\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\npause = 0.0\n<docstring token>\n\n\ndef interact(max_itn):\n itn = 0\n B, r, c = get_board()\n print(B)\n X = convert_board(B, r, c)\n A, r, c = expand_grid(X, r, c, 0)\n print_array(A, r, c)\n while itn <= max_itn:\n sleep(pause)\n newA, delta = next_state2(A, r, c)\n if not delta:\n break\n itn += 1\n A = newA\n print_array(A, r, c)\n print('\\niterations', itn)\n\n\ndef main():\n interact(259)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n\n\ndef get_board():\n B = []\n print(sys.argv[1])\n with open(sys.argv[1]) as f:\n for line in f:\n B.append(line.rstrip().replace(' ', ''))\n rows, cols = len(B), len(B[0])\n for j in range(1, rows):\n assert len(B[j]) == cols\n return B, rows, cols\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n\n\ndef interact(max_itn):\n itn = 0\n B, r, c = get_board()\n print(B)\n X = convert_board(B, r, c)\n A, r, c = expand_grid(X, r, c, 0)\n print_array(A, r, c)\n while itn <= max_itn:\n sleep(pause)\n newA, delta = next_state2(A, r, c)\n if not delta:\n break\n itn += 1\n A = newA\n print_array(A, r, c)\n print('\\niterations', itn)\n\n\ndef main():\n interact(259)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n\n\ndef get_board():\n B = []\n print(sys.argv[1])\n with open(sys.argv[1]) as f:\n for line in f:\n B.append(line.rstrip().replace(' ', ''))\n rows, cols = len(B), len(B[0])\n for j in range(1, rows):\n assert len(B[j]) == cols\n return B, rows, cols\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n\n\ndef interact(max_itn):\n itn = 0\n B, r, c = get_board()\n print(B)\n X = convert_board(B, r, c)\n A, r, c = expand_grid(X, r, c, 0)\n print_array(A, r, c)\n while itn <= max_itn:\n sleep(pause)\n newA, delta = next_state2(A, r, c)\n if not delta:\n break\n itn += 1\n A = newA\n print_array(A, r, c)\n print('\\niterations', itn)\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n\n\ndef interact(max_itn):\n itn = 0\n B, r, c = get_board()\n print(B)\n X = convert_board(B, r, c)\n A, r, c = expand_grid(X, r, c, 0)\n print_array(A, r, c)\n while itn <= max_itn:\n sleep(pause)\n newA, delta = next_state2(A, r, c)\n if not delta:\n break\n itn += 1\n A = newA\n print_array(A, r, c)\n print('\\niterations', itn)\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\ndef print_array(A, r, c):\n print('')\n for j in range(r):\n out = ''\n for k in range(c):\n out += ACH if A[j, k] == ALIVE else DCH\n print(out)\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\ndef expand_grid(A, r, c, t):\n N = np.zeros((r + 2 * t, c + 2 * t), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if A[j][k] == ALIVE:\n N[j + t, k + t] = ALIVE\n return N, r + 2 * t, c + 2 * t\n\n\n<function token>\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\n<function token>\n<function token>\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n\n\ndef next_state(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef point(r, c, cols):\n return c + r * cols\n\n\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\n<function token>\n<function token>\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\n<function token>\n<function token>\n\n\ndef show_array(A, r, c):\n for j in range(r):\n line = ''\n for k in range(c):\n line += str(A[j, k])\n print(line)\n print('')\n\n\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n\n\ndef convert_board(B, r, c):\n A = np.zeros((r, c), dtype=np.int8)\n for j in range(r):\n for k in range(c):\n if B[j][k] == ACH:\n A[j, k] = ALIVE\n return A\n\n\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef next_state2(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs2(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n\n\ndef main():\n interact(259)\n\n\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef num_nbrs2(A, r, j, c, k):\n num = 0\n if j > 0 and k > 0 and A[j - 1, k - 1] == ALIVE:\n num += 1\n if j > 0 and A[j - 1, k] == ALIVE:\n num += 1\n if j > 0 and k < c - 1 and A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and A[j, k - 1] == ALIVE:\n num += 1\n if k < c - 1 and A[j, k + 1] == ALIVE:\n num += 1\n if j < r - 1 and k > 0 and A[j + 1, k - 1] == ALIVE:\n num += 1\n if j < r - 1 and A[j + 1, k] == ALIVE:\n num += 1\n if j < r - 1 and k < c - 1 and A[j + 1, k + 1] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef next_state_torus(A, r, c):\n N = np.zeros((r, c), dtype=np.int8)\n changed = False\n for j in range(r):\n for k in range(c):\n num = num_nbrs_torus(A, r, j, c, k)\n if A[j, k] == ALIVE:\n if num > 1 and num < 4:\n N[j, k] = ALIVE\n else:\n N[j, k] = DEAD\n changed = True\n elif num == 3:\n N[j, k] = ALIVE\n changed = True\n else:\n N[j, k] = DEAD\n return N, changed\n\n\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n\n\ndef num_nbrs_torus(A, r, j, c, k):\n \"\"\" Counts number of neighbours for a torus.\n\n\tArgs:\n\t\tA: the numpy board\n\t\tr: number of rows in the board\n\t\tj: current row of the cell in the iteration\n\t\tc: number of columns in the board\n\t\tk: current column of the cell in the iteration\n\t\n\tReturns:\n\t\tnum: the number of neighbours\n\t\"\"\"\n num = 0\n r = r - 1\n c = c - 1\n if j == 0:\n if k == 0:\n if A[r, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[r, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[r, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[r, k] == ALIVE:\n num += 1\n if j > 0 and j < r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[j + 1, c] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j + 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j + 1, k - 1] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j + 1, 0] == ALIVE:\n num += 1\n if A[j + 1, k] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if j == r:\n if k == 0:\n if A[j - 1, c] == ALIVE:\n num += 1\n if A[j, c] == ALIVE:\n num += 1\n if A[0, c] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k > 0 and k < c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, k + 1] == ALIVE:\n num += 1\n if A[j, k + 1] == ALIVE:\n num += 1\n if A[j - 1, k + 1] == ALIVE:\n num += 1\n if k == c:\n if A[0, k - 1] == ALIVE:\n num += 1\n if A[j, k - 1] == ALIVE:\n num += 1\n if A[j - 1, k - 1] == ALIVE:\n num += 1\n if A[0, 0] == ALIVE:\n num += 1\n if A[j, 0] == ALIVE:\n num += 1\n if A[j - 1, 0] == ALIVE:\n num += 1\n if A[j - 1, k] == ALIVE:\n num += 1\n if A[0, k] == ALIVE:\n num += 1\n return num\n\n\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<function token>\n<docstring token>\n<assignment token>\n<docstring token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,716 | 53b14c046f6250b38f373c8b7247cf27b9badede | # -*- coding: utf-8 -*-
"""
scripteo personal
Created on Tue Jan 23 11:44:15 2018
@author: yo
"""
#ESTRUCTURAS TEMPORALES
#Semana
semana = ["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"]
#año
año = ["Enero", "Febrero","Marzo", "Mayo", "Abril", "Junio","Julio", "Agosto","Septiembre","Octubre", "Noviembre", "Diciembre"]
print (año[11])
#actividades
actividades = ["Casa del Axolote", "Amor/familia", "Investigación/desarrollo/educación", "Gaming", "Investing"]
#Estructuras económicas
#cashflows
cashflows = ["Renta", "Ventas", "Salario Jess", "Salario CaX", "Bono anual"]
cashflows_en_desarrollo = ["Restaurante", "Ventas", "Bono anual", "Inversiones"]
#cashflows que se ponen a funcionar claramente en este año
cashflows_en_desarrollo_corto_plazo = ["Restaurante", "Ventas", "Bono anual"]
cahsflows_en_desarrollo_corto_plazo_indies = ["Restaurante", "Ventas"]
#Ingreso mensual 2018
renta = 5000
salario_cax = 2500
ventas_bajas = 4000
ventas_medias = 8000
ventas_altas = 15000
salario_jess = 9000
restaurante =
ingreso_mensual_2018 = renta + salario_cax + salario_jess + ventas_bajas
print(ingreso_mensual_2018)
#gasto mensual 2018
pago_carro = 7000
pago_escuela = 1000
semana = 1000
gasolina = 1200
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nscripteo personal \nCreated on Tue Jan 23 11:44:15 2018\n\n@author: yo\n\"\"\"\n\n#ESTRUCTURAS TEMPORALES\n\n#Semana\nsemana = [\"Lunes\", \"Martes\", \"Miercoles\", \"Jueves\", \"Viernes\", \"Sabado\", \"Domingo\"]\n\n#año\naño = [\"Enero\", \"Febrero\",\"Marzo\", \"Mayo\", \"Abril\", \"Junio\",\"Julio\", \"Agosto\",\"Septiembre\",\"Octubre\", \"Noviembre\", \"Diciembre\"]\nprint (año[11])\n\n\n#actividades\nactividades = [\"Casa del Axolote\", \"Amor/familia\", \"Investigación/desarrollo/educación\", \"Gaming\", \"Investing\"]\n\n\n#Estructuras económicas\n\n#cashflows \ncashflows = [\"Renta\", \"Ventas\", \"Salario Jess\", \"Salario CaX\", \"Bono anual\"]\ncashflows_en_desarrollo = [\"Restaurante\", \"Ventas\", \"Bono anual\", \"Inversiones\"]\n\n#cashflows que se ponen a funcionar claramente en este año\ncashflows_en_desarrollo_corto_plazo = [\"Restaurante\", \"Ventas\", \"Bono anual\"]\ncahsflows_en_desarrollo_corto_plazo_indies = [\"Restaurante\", \"Ventas\"] \n\n#Ingreso mensual 2018\n\nrenta = 5000\nsalario_cax = 2500\nventas_bajas = 4000\nventas_medias = 8000\nventas_altas = 15000\nsalario_jess = 9000\n\nrestaurante = \n\ningreso_mensual_2018 = renta + salario_cax + salario_jess + ventas_bajas \nprint(ingreso_mensual_2018)\n\n#gasto mensual 2018\n\npago_carro = 7000\npago_escuela = 1000\nsemana = 1000\ngasolina = 1200\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | true |
99,717 | 8af4feae23120b1b24b21dd287e0983011d0bc20 | import pandas as pd
def count_elements(path):
""" gets the file, converts into a dictionary,
counts the number of different elements
and returns the dataframe"""
count = 0
with open(path, 'r') as f:
groups = f.read().split('\n\n')
for idx in range(len(groups)):
word = groups[idx].split('\n')
no_of_ele = len(word)
for i in range(no_of_ele-1):
word[0] = word[0]+word[i+1]
count += len(''.join(set(word[0])))
return count
path = 'data/day6.txt'
nr = count_elements(path)
nr
| [
"import pandas as pd\n\n\ndef count_elements(path):\n \"\"\" gets the file, converts into a dictionary, \n counts the number of different elements \n and returns the dataframe\"\"\"\n count = 0\n with open(path, 'r') as f:\n groups = f.read().split('\\n\\n')\n for idx in range(len(groups)):\n word = groups[idx].split('\\n')\n no_of_ele = len(word)\n for i in range(no_of_ele-1):\n word[0] = word[0]+word[i+1]\n count += len(''.join(set(word[0])))\n return count\n\n\npath = 'data/day6.txt'\n\nnr = count_elements(path)\nnr\n",
"import pandas as pd\n\n\ndef count_elements(path):\n \"\"\" gets the file, converts into a dictionary, \n counts the number of different elements \n and returns the dataframe\"\"\"\n count = 0\n with open(path, 'r') as f:\n groups = f.read().split('\\n\\n')\n for idx in range(len(groups)):\n word = groups[idx].split('\\n')\n no_of_ele = len(word)\n for i in range(no_of_ele - 1):\n word[0] = word[0] + word[i + 1]\n count += len(''.join(set(word[0])))\n return count\n\n\npath = 'data/day6.txt'\nnr = count_elements(path)\nnr\n",
"<import token>\n\n\ndef count_elements(path):\n \"\"\" gets the file, converts into a dictionary, \n counts the number of different elements \n and returns the dataframe\"\"\"\n count = 0\n with open(path, 'r') as f:\n groups = f.read().split('\\n\\n')\n for idx in range(len(groups)):\n word = groups[idx].split('\\n')\n no_of_ele = len(word)\n for i in range(no_of_ele - 1):\n word[0] = word[0] + word[i + 1]\n count += len(''.join(set(word[0])))\n return count\n\n\npath = 'data/day6.txt'\nnr = count_elements(path)\nnr\n",
"<import token>\n\n\ndef count_elements(path):\n \"\"\" gets the file, converts into a dictionary, \n counts the number of different elements \n and returns the dataframe\"\"\"\n count = 0\n with open(path, 'r') as f:\n groups = f.read().split('\\n\\n')\n for idx in range(len(groups)):\n word = groups[idx].split('\\n')\n no_of_ele = len(word)\n for i in range(no_of_ele - 1):\n word[0] = word[0] + word[i + 1]\n count += len(''.join(set(word[0])))\n return count\n\n\n<assignment token>\nnr\n",
"<import token>\n\n\ndef count_elements(path):\n \"\"\" gets the file, converts into a dictionary, \n counts the number of different elements \n and returns the dataframe\"\"\"\n count = 0\n with open(path, 'r') as f:\n groups = f.read().split('\\n\\n')\n for idx in range(len(groups)):\n word = groups[idx].split('\\n')\n no_of_ele = len(word)\n for i in range(no_of_ele - 1):\n word[0] = word[0] + word[i + 1]\n count += len(''.join(set(word[0])))\n return count\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<function token>\n<assignment token>\n<code token>\n"
] | false |
99,718 | 8915dc155375e018561f99b581956f1b29d0cb98 | '''faça um programa que leia um angulo qualquer e mostre na tela o valor do seno,
cosseno e tangente desse angulo'''
import math
an = float(input('Digite o ângulo que você deseja:'))
seno = math.sin(math.radians(an))
cos = math.cos(math.radians(an))
tan = math.tan(math.radians(an))
print('o seno é de {:.2f}'.format(seno))
print('O cosseno é de {:.2f}'.format(cos))
print('A tangente é de {:.2f}'.format(tan)) | [
"'''faça um programa que leia um angulo qualquer e mostre na tela o valor do seno,\ncosseno e tangente desse angulo'''\nimport math\nan = float(input('Digite o ângulo que você deseja:'))\nseno = math.sin(math.radians(an))\ncos = math.cos(math.radians(an))\ntan = math.tan(math.radians(an))\nprint('o seno é de {:.2f}'.format(seno))\nprint('O cosseno é de {:.2f}'.format(cos))\nprint('A tangente é de {:.2f}'.format(tan))",
"<docstring token>\nimport math\nan = float(input('Digite o ângulo que você deseja:'))\nseno = math.sin(math.radians(an))\ncos = math.cos(math.radians(an))\ntan = math.tan(math.radians(an))\nprint('o seno é de {:.2f}'.format(seno))\nprint('O cosseno é de {:.2f}'.format(cos))\nprint('A tangente é de {:.2f}'.format(tan))\n",
"<docstring token>\n<import token>\nan = float(input('Digite o ângulo que você deseja:'))\nseno = math.sin(math.radians(an))\ncos = math.cos(math.radians(an))\ntan = math.tan(math.radians(an))\nprint('o seno é de {:.2f}'.format(seno))\nprint('O cosseno é de {:.2f}'.format(cos))\nprint('A tangente é de {:.2f}'.format(tan))\n",
"<docstring token>\n<import token>\n<assignment token>\nprint('o seno é de {:.2f}'.format(seno))\nprint('O cosseno é de {:.2f}'.format(cos))\nprint('A tangente é de {:.2f}'.format(tan))\n",
"<docstring token>\n<import token>\n<assignment token>\n<code token>\n"
] | false |
99,719 | 1f2cbdb1fcdeb94726aa51569160d6618e7873b9 | import grpc
import computer_pb2
import computer_pb2_grpc
def generate_nums(n):
for i in range(n):
yield computer_pb2.Number(value = i)
def run():
with grpc.insecure_channel('localhost:50051') as channel:
stub = computer_pb2_grpc.ComputerStub(channel)
print("-------------- squareRoot --------------")
print(stub.SquareRoot(computer_pb2.Number(value=4)).value)
print("-------------- Primes --------------")
a = stub.Primes(computer_pb2.Number(value=40))
for aa in a:
print(aa.value)
print("-------------- STD --------------")
print(stub.STD(generate_nums(10)).value)
print("-------------- maxElem --------------")
for a in stub.MaxElem(generate_nums(10)):
print(a.value)
print("-------------- maxElem --------------")
aaaa = list(map(lambda x: computer_pb2.Number(value=x), [4,2,1,5,3,10,2,120,22,-1,32,900,2,2,2]))
for a in stub.MaxElem(iter(aaaa)):
print(a.value)
if __name__ == '__main__':
run() | [
"import grpc\nimport computer_pb2\nimport computer_pb2_grpc\n\n\ndef generate_nums(n):\n for i in range(n):\n yield computer_pb2.Number(value = i)\n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = computer_pb2_grpc.ComputerStub(channel)\n\n print(\"-------------- squareRoot --------------\")\n print(stub.SquareRoot(computer_pb2.Number(value=4)).value)\n\n print(\"-------------- Primes --------------\")\n a = stub.Primes(computer_pb2.Number(value=40))\n for aa in a:\n print(aa.value)\n \n print(\"-------------- STD --------------\")\n print(stub.STD(generate_nums(10)).value)\n\n print(\"-------------- maxElem --------------\")\n for a in stub.MaxElem(generate_nums(10)):\n print(a.value)\n\n print(\"-------------- maxElem --------------\")\n aaaa = list(map(lambda x: computer_pb2.Number(value=x), [4,2,1,5,3,10,2,120,22,-1,32,900,2,2,2]))\n for a in stub.MaxElem(iter(aaaa)):\n print(a.value)\n\n\nif __name__ == '__main__':\n run()",
"import grpc\nimport computer_pb2\nimport computer_pb2_grpc\n\n\ndef generate_nums(n):\n for i in range(n):\n yield computer_pb2.Number(value=i)\n\n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = computer_pb2_grpc.ComputerStub(channel)\n print('-------------- squareRoot --------------')\n print(stub.SquareRoot(computer_pb2.Number(value=4)).value)\n print('-------------- Primes --------------')\n a = stub.Primes(computer_pb2.Number(value=40))\n for aa in a:\n print(aa.value)\n print('-------------- STD --------------')\n print(stub.STD(generate_nums(10)).value)\n print('-------------- maxElem --------------')\n for a in stub.MaxElem(generate_nums(10)):\n print(a.value)\n print('-------------- maxElem --------------')\n aaaa = list(map(lambda x: computer_pb2.Number(value=x), [4, 2, 1, 5,\n 3, 10, 2, 120, 22, -1, 32, 900, 2, 2, 2]))\n for a in stub.MaxElem(iter(aaaa)):\n print(a.value)\n\n\nif __name__ == '__main__':\n run()\n",
"<import token>\n\n\ndef generate_nums(n):\n for i in range(n):\n yield computer_pb2.Number(value=i)\n\n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = computer_pb2_grpc.ComputerStub(channel)\n print('-------------- squareRoot --------------')\n print(stub.SquareRoot(computer_pb2.Number(value=4)).value)\n print('-------------- Primes --------------')\n a = stub.Primes(computer_pb2.Number(value=40))\n for aa in a:\n print(aa.value)\n print('-------------- STD --------------')\n print(stub.STD(generate_nums(10)).value)\n print('-------------- maxElem --------------')\n for a in stub.MaxElem(generate_nums(10)):\n print(a.value)\n print('-------------- maxElem --------------')\n aaaa = list(map(lambda x: computer_pb2.Number(value=x), [4, 2, 1, 5,\n 3, 10, 2, 120, 22, -1, 32, 900, 2, 2, 2]))\n for a in stub.MaxElem(iter(aaaa)):\n print(a.value)\n\n\nif __name__ == '__main__':\n run()\n",
"<import token>\n\n\ndef generate_nums(n):\n for i in range(n):\n yield computer_pb2.Number(value=i)\n\n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = computer_pb2_grpc.ComputerStub(channel)\n print('-------------- squareRoot --------------')\n print(stub.SquareRoot(computer_pb2.Number(value=4)).value)\n print('-------------- Primes --------------')\n a = stub.Primes(computer_pb2.Number(value=40))\n for aa in a:\n print(aa.value)\n print('-------------- STD --------------')\n print(stub.STD(generate_nums(10)).value)\n print('-------------- maxElem --------------')\n for a in stub.MaxElem(generate_nums(10)):\n print(a.value)\n print('-------------- maxElem --------------')\n aaaa = list(map(lambda x: computer_pb2.Number(value=x), [4, 2, 1, 5,\n 3, 10, 2, 120, 22, -1, 32, 900, 2, 2, 2]))\n for a in stub.MaxElem(iter(aaaa)):\n print(a.value)\n\n\n<code token>\n",
"<import token>\n\n\ndef generate_nums(n):\n for i in range(n):\n yield computer_pb2.Number(value=i)\n\n\n<function token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,720 | 42c261dfb1c425fcc9d6e8e58b21536396ecb5df | from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
import pickle, os, sys
SCOPES = ["https://www.googleapis.com/auth/drive"]
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'portal.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
drive = build('drive', 'v3', credentials=creds)
def ls(parent, searchTerms=""):
files = []
resp = drive.files().list(q=f"'{parent}' in parents" + searchTerms, pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True).execute()
files += resp["files"]
while "nextPageToken" in resp:
resp = drive.files().list(q=f"'{parent}' in parents" + searchTerms, pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True, pageToken=resp["nextPageToken"]).execute()
files += resp["files"]
return files
def lsd(parent):
return ls(parent, searchTerms=" and mimeType contains 'application/vnd.google-apps.folder'")
def lsf(parent):
return ls(parent, searchTerms=" and not mimeType contains 'application/vnd.google-apps.folder'")
def getf(fileid):
return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()
def strip_perms(fileid):
resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True).execute()
for i in resp["permissions"]:
if i.get("role") != "owner":
drive.permissions().delete(fileId=fileid, permissionId=i["id"]).execute()
def recurse_folder(folderid):
strip_perms(folderid)
files = ls(folderid)
for i in files:
if i["mimeType"] == "application/vnd.google-apps.folder":
recurse_folder(i["id"])
else:
strip_perms(i["id"])
recurse_folder(sys.argv[1]) | [
"from google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.discovery import build\nimport pickle, os, sys\n\nSCOPES = [\"https://www.googleapis.com/auth/drive\"]\n\ncreds = None\nif os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\nif not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'portal.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\ndrive = build('drive', 'v3', credentials=creds)\n\ndef ls(parent, searchTerms=\"\"):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms, pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True).execute()\n files += resp[\"files\"]\n while \"nextPageToken\" in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms, pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True, pageToken=resp[\"nextPageToken\"]).execute()\n files += resp[\"files\"]\n return files\n\ndef lsd(parent):\n \n return ls(parent, searchTerms=\" and mimeType contains 'application/vnd.google-apps.folder'\")\n\ndef lsf(parent):\n \n return ls(parent, searchTerms=\" and not mimeType contains 'application/vnd.google-apps.folder'\")\n\ndef getf(fileid):\n \n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\ndef strip_perms(fileid):\n \n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True).execute()\n for i in resp[\"permissions\"]:\n if i.get(\"role\") != \"owner\":\n drive.permissions().delete(fileId=fileid, permissionId=i[\"id\"]).execute()\n\ndef recurse_folder(folderid):\n \n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i[\"mimeType\"] == \"application/vnd.google-apps.folder\":\n recurse_folder(i[\"id\"])\n else:\n strip_perms(i[\"id\"])\n \nrecurse_folder(sys.argv[1])",
"from google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.discovery import build\nimport pickle, os, sys\nSCOPES = ['https://www.googleapis.com/auth/drive']\ncreds = None\nif os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\nif not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('portal.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\ndrive = build('drive', 'v3', credentials=creds)\n\n\ndef ls(parent, searchTerms=''):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True\n ).execute()\n files += resp['files']\n while 'nextPageToken' in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True,\n includeItemsFromAllDrives=True, pageToken=resp['nextPageToken']\n ).execute()\n files += resp['files']\n return files\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef lsf(parent):\n return ls(parent, searchTerms=\n \" and not mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\nrecurse_folder(sys.argv[1])\n",
"<import token>\nSCOPES = ['https://www.googleapis.com/auth/drive']\ncreds = None\nif os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\nif not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('portal.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\ndrive = build('drive', 'v3', credentials=creds)\n\n\ndef ls(parent, searchTerms=''):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True\n ).execute()\n files += resp['files']\n while 'nextPageToken' in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True,\n includeItemsFromAllDrives=True, pageToken=resp['nextPageToken']\n ).execute()\n files += resp['files']\n return files\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef lsf(parent):\n return ls(parent, searchTerms=\n \" and not mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\nrecurse_folder(sys.argv[1])\n",
"<import token>\n<assignment token>\nif os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\nif not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('portal.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n<assignment token>\n\n\ndef ls(parent, searchTerms=''):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True\n ).execute()\n files += resp['files']\n while 'nextPageToken' in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True,\n includeItemsFromAllDrives=True, pageToken=resp['nextPageToken']\n ).execute()\n files += resp['files']\n return files\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef lsf(parent):\n return ls(parent, searchTerms=\n \" and not mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\nrecurse_folder(sys.argv[1])\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n\n\ndef ls(parent, searchTerms=''):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True\n ).execute()\n files += resp['files']\n while 'nextPageToken' in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True,\n includeItemsFromAllDrives=True, pageToken=resp['nextPageToken']\n ).execute()\n files += resp['files']\n return files\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef lsf(parent):\n return ls(parent, searchTerms=\n \" and not mimeType contains 'application/vnd.google-apps.folder'\")\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n\n\ndef ls(parent, searchTerms=''):\n files = []\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True, includeItemsFromAllDrives=True\n ).execute()\n files += resp['files']\n while 'nextPageToken' in resp:\n resp = drive.files().list(q=f\"'{parent}' in parents\" + searchTerms,\n pageSize=1000, supportsAllDrives=True,\n includeItemsFromAllDrives=True, pageToken=resp['nextPageToken']\n ).execute()\n files += resp['files']\n return files\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\n<function token>\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<function token>\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\n<function token>\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\ndef recurse_folder(folderid):\n strip_perms(folderid)\n files = ls(folderid)\n for i in files:\n if i['mimeType'] == 'application/vnd.google-apps.folder':\n recurse_folder(i['id'])\n else:\n strip_perms(i['id'])\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<function token>\n\n\ndef lsd(parent):\n return ls(parent, searchTerms=\n \" and mimeType contains 'application/vnd.google-apps.folder'\")\n\n\n<function token>\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\ndef strip_perms(fileid):\n resp = drive.permissions().list(fileId=fileid, supportsAllDrives=True\n ).execute()\n for i in resp['permissions']:\n if i.get('role') != 'owner':\n drive.permissions().delete(fileId=fileid, permissionId=i['id']\n ).execute()\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef getf(fileid):\n return drive.files().get(fileId=fileid, supportsAllDrives=True).execute()\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,721 | 36c4df4db8447702769774d004d0b0ad15ad93f8 | import os
import unittest
import numpy as np
import src.dqn.main
def done_chasing(state: tuple) -> bool:
chaser_state = state[0]
chasee_state = state[1]
return chaser_state == chasee_state
def mock_renderer(state: tuple):
return
class TestDQNMain(unittest.TestCase):
def setUp(self):
self.model_path = "test_dqn_model_output.st"
# Environment parameters
env_size = 1
state_space_1D = range(-env_size, env_size + 1)
state_space_bounds = ((-env_size, env_size),)*2
action_space = np.arange(4)
obstacles = []
self.start_state = ((-1, -1), (1, 1))
self.env = src.env.Env(state_space_bounds,
action_space,
src.reward.TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds, obstacles),
src.transition.transition_2d_grid,
done_chasing,
self.start_state,
obstacles)
def tearDown(self):
if os.path.exists(self.model_path):
os.remove(self.model_path)
def test_train(self):
# just run to see if it doesn't crash for now
src.dqn.main.dqn_trainer(self.env, self.start_state, self.model_path, batch_size=1, max_training_steps=10)
self.assertTrue(os.path.isfile(self.model_path))
def test_runner(self):
self.test_train() # generate model file to work with
# just run to see if it doesn't crash for now
src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer, self.model_path, max_running_steps=10)
if __name__ == '__main__':
unittest.main()
| [
"import os\nimport unittest\nimport numpy as np\n\nimport src.dqn.main\n\ndef done_chasing(state: tuple) -> bool:\n chaser_state = state[0]\n chasee_state = state[1]\n return chaser_state == chasee_state\n\ndef mock_renderer(state: tuple):\n return\n\nclass TestDQNMain(unittest.TestCase):\n def setUp(self):\n self.model_path = \"test_dqn_model_output.st\"\n # Environment parameters\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),)*2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = ((-1, -1), (1, 1))\n\n self.env = src.env.Env(state_space_bounds,\n action_space,\n src.reward.TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds, obstacles),\n src.transition.transition_2d_grid,\n done_chasing,\n self.start_state,\n obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n # just run to see if it doesn't crash for now\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train() # generate model file to work with\n # just run to see if it doesn't crash for now\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer, self.model_path, max_running_steps=10)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"import os\nimport unittest\nimport numpy as np\nimport src.dqn.main\n\n\ndef done_chasing(state: tuple) ->bool:\n chaser_state = state[0]\n chasee_state = state[1]\n return chaser_state == chasee_state\n\n\ndef mock_renderer(state: tuple):\n return\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<import token>\n\n\ndef done_chasing(state: tuple) ->bool:\n chaser_state = state[0]\n chasee_state = state[1]\n return chaser_state == chasee_state\n\n\ndef mock_renderer(state: tuple):\n return\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<import token>\n\n\ndef done_chasing(state: tuple) ->bool:\n chaser_state = state[0]\n chasee_state = state[1]\n return chaser_state == chasee_state\n\n\ndef mock_renderer(state: tuple):\n return\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\ndef mock_renderer(state: tuple):\n return\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n\n def tearDown(self):\n if os.path.exists(self.model_path):\n os.remove(self.model_path)\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\nclass TestDQNMain(unittest.TestCase):\n\n def setUp(self):\n self.model_path = 'test_dqn_model_output.st'\n env_size = 1\n state_space_1D = range(-env_size, env_size + 1)\n state_space_bounds = ((-env_size, env_size),) * 2\n action_space = np.arange(4)\n obstacles = []\n self.start_state = (-1, -1), (1, 1)\n self.env = src.env.Env(state_space_bounds, action_space, src.reward\n .TwoAgentChasingRewardNdGridWithObstacles(state_space_bounds,\n obstacles), src.transition.transition_2d_grid, done_chasing,\n self.start_state, obstacles)\n <function token>\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\nclass TestDQNMain(unittest.TestCase):\n <function token>\n <function token>\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n\n def test_runner(self):\n self.test_train()\n src.dqn.main.dqn_runner(self.env, self.start_state, mock_renderer,\n self.model_path, max_running_steps=10)\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\nclass TestDQNMain(unittest.TestCase):\n <function token>\n <function token>\n\n def test_train(self):\n src.dqn.main.dqn_trainer(self.env, self.start_state, self.\n model_path, batch_size=1, max_training_steps=10)\n self.assertTrue(os.path.isfile(self.model_path))\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\nclass TestDQNMain(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<class token>\n<code token>\n"
] | false |
99,722 | a6953ed00429fc382ff3ab21201e319674f7b889 | # import csv
# # 读取csv文件
# data = csv.reader(open('./a.csv','r'))
# for i in data:
# print(i)
from xml.dom import minidom
data = minidom.parse('./a.xml')
print(data)
# 获取到当前所有的对象
root = data.documentElement
print(root)
# 获取文档元素
print(root.nodeName)
# 获取xml里面元素
print(root.getElementsByTagName('project'))
print(root.getElementsByTagName('name'))
| [
"# import csv\n# # 读取csv文件\n# data = csv.reader(open('./a.csv','r'))\n# for i in data:\n# print(i)\n\nfrom xml.dom import minidom\n\ndata = minidom.parse('./a.xml')\nprint(data)\n# 获取到当前所有的对象\nroot = data.documentElement\nprint(root)\n# 获取文档元素\nprint(root.nodeName)\n# 获取xml里面元素\nprint(root.getElementsByTagName('project'))\nprint(root.getElementsByTagName('name'))\n\n",
"from xml.dom import minidom\ndata = minidom.parse('./a.xml')\nprint(data)\nroot = data.documentElement\nprint(root)\nprint(root.nodeName)\nprint(root.getElementsByTagName('project'))\nprint(root.getElementsByTagName('name'))\n",
"<import token>\ndata = minidom.parse('./a.xml')\nprint(data)\nroot = data.documentElement\nprint(root)\nprint(root.nodeName)\nprint(root.getElementsByTagName('project'))\nprint(root.getElementsByTagName('name'))\n",
"<import token>\n<assignment token>\nprint(data)\n<assignment token>\nprint(root)\nprint(root.nodeName)\nprint(root.getElementsByTagName('project'))\nprint(root.getElementsByTagName('name'))\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,723 | 8a53370234cf128ee1cfd7bf6ca8cdfd015ae6d5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 00:49:45 2020
@author: sh
"""
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 23 00:49:45 2020\n\n@author: sh\n\"\"\"\n\n\n",
"<docstring token>\n"
] | false |
99,724 | 618f8c8867bb6c9dab039251ee9330bb5afdb575 | #!/usr/bin/python
# patternSet.py
import json
import random
import math
# used in calculating Sigma based on center locations
def euclidianDistance(p, q):
sumOfSquares = 0.0
if isinstance(p, list):
if isinstance(p[0], list):
for i in range(len(p)):
for j in range(len(p[i])):
sumOfSquares = sumOfSquares + ((p[i][j]-q[i][j])*(p[i][j]-q[i][j]))
else:
for i in range(len(p)):
sumOfSquares = sumOfSquares + ((p[i]-q[i])*(p[i]-q[i]))
else:
sumOfSquares = sumOfSquares + ((p-q)*(p-q))
return math.sqrt(sumOfSquares)
# Centers are built for each of the targets in two steps
# First an average is built for each target from each pattern of that target type
# Next we run k-means on the new centers against all patterns
# Sigmas are calculated for each element
def buildCentersAndSigmas(patterns):
centersTargets = {}
for pattern in patterns:
if pattern['t'] not in centersTargets:
centersTargets[pattern['t']] = []
centersTargets[pattern['t']].append(pattern)
centers = {}
sigmas = {}
print("Found " + str(len(centersTargets)) + " targets.")
print("Constructing Centers and Sigmas...")
# build center as mean of all trained k patterns, and sigma as standard deviation
for k in centersTargets.keys():
kPats = centersTargets[k]
centers[k] = buildMeanPattern(kPats)
# OPTIONAL k-MEANS CENTER SOFTENING --WINNER--
dist = 100
distDelta = 100
oldDist = 0
while dist > 1 and abs(distDelta) > 0.01:
tempCenters = adjustCenters(patterns, centers)
dist = 0
for k in centersTargets.keys():
dist = dist + euclidianDistance(centers[k], tempCenters[k])
centers = tempCenters
distDelta = dist - oldDist
oldDist = dist
#print("dist:" + str(round(dist, 4)) + ", delta:" + str(round(distDelta, 4)))
# #Build Sigmas for each space
for k in centersTargets.keys():
sigmas[k] = buildSigmaPattern(centers[k], kPats)
return {'centers':centers, 'sigmas':sigmas}
# given several patterns we create an average pattern of the same dimension
# This method works for 2D arrays, 1D arrays, and scalers
def buildMeanPattern(patterns):
h = 0
w = len(patterns[0]['p'])
if isinstance(patterns[0]['p'][0], list):
h = len(patterns[0]['p'])
w = len(patterns[0]['p'][0])
mPat = emptyPattern(w, h)
for pat in patterns:
if h > 1:
for i in range(h):
for j in range(w):
mPat[i][j] = mPat[i][j] + pat['p'][i][j]
else:
for j in range(w):
mPat[j] = mPat[j] + pat['p'][j]
if h > 1:
for i in range(h):
for j in range(w):
mPat[i][j] = mPat[i][j] / len(patterns)
else:
for j in range(w):
mPat[j] = mPat[j] / len(patterns)
return mPat
# This pattern shows us where the fuzziness is in our average
def buildSigmaPattern(meanPat, patterns):
h = 0
w = len(patterns[0]['p'])
if isinstance(patterns[0]['p'][0], list):
h = len(patterns[0]['p'])
w = len(patterns[0]['p'][0])
sPat = emptyPattern(w, h)
# Sum over all square of distance from means
if h > 1:
for i in range(h):
for j in range(w):
for pat in patterns:
sPat[i][j] = sPat[i][j] + (pat['p'][i][j] - meanPat[i][j])*(pat['p'][i][j] - meanPat[i][j])
sPat[i][j] = math.sqrt(1.0/len(patterns)*sPat[i][j])
else:
for j in range(w):
for pat in patterns:
sPat[j] = sPat[j] + (pat['p'][j] - meanPat[j])*(pat['p'][j] - meanPat[j])
sPat[j] = math.sqrt(1.0/len(patterns)*sPat[j])
return sPat
# Used in k-means, here we take an average of the member patterns to construct a new center
def adjustCenters(patterns, centers):
groups = {}
for k in centers.keys():
groups[k] = []
for pattern in patterns:
bestDist = 99999
bestKey = ''
for key in centers.keys():
center = centers[key]
dist = euclidianDistance(pattern['p'], center)
if dist < bestDist:
bestDist = dist
bestKey = key
groups[bestKey].append(pattern)
newCenters = {}
for k in centers.keys():
if len(groups[k]) > 0:
newCenters[k] = buildMeanPattern(groups[k])
else:
newCenters[k] = centers[k]
return newCenters
# Creates and empty pattern of the given dimensionality
def emptyPattern(w, h):
pat = []
if h > 1:
for i in range(h):
pat.append([])
for j in range(w):
pat[i].append(0.0)
else:
for j in range(w):
pat.append(0.0)
return pat
# print an individual pattern with or without target value
def printPatterns(pattern):
if isinstance(pattern, dict):
for key in pattern.keys():
if key == 't':
print("Target: " + str(key))
elif key == 'p':
printPatterns(pattern['p'])
elif isinstance(pattern[0], list):
for pat in pattern:
printPatterns(pat)
else:
print(', '.join(str(round(x, 3)) for x in pattern))
# A Pattern set contains sets of 3 types of patterns
# and can be used to retrieve only those patterns of a certain type
class PatternSet:
# Reads patterns in from a file, and puts them in their coorisponding set
def __init__(self, fileName, percentTraining):
with open(fileName) as jsonData:
data = json.load(jsonData)
# Assign Patterns and Randomize order
self.patterns = data['patterns']
self.count = data['count']
self.inputMagX = len(self.patterns[0]['p'])
self.inputMagY = 1
if isinstance(self.patterns[0]['p'][0], list):
self.inputMagX = len(self.patterns[0]['p'][0])
self.inputMagY = len(self.patterns[0]['p'])
random.shuffle(self.patterns)
print(str(len(self.patterns)) + " Patterns Available (" + str(self.inputMagY) + "x" + str(self.inputMagX) + ")")
# Construct Centers but base them only off the cases to be trained with
centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data['count']*percentTraining)])
self.centers = centersAndSigmas['centers']
self.sigmas = centersAndSigmas['sigmas']
# Architecture has 1 output node for each digit / letter
# Assemble our target and confusion matrix
keys = list(self.centers.keys())
keys.sort()
print("Centers: [" + ', '.join(str(k).split('.')[0] for k in keys) + "]")
self.confusionMatrix = {}
self.targetMatrix = {}
index = 0
# Initialize Confusion Matrix and Target Matrix
for key in keys:
self.confusionMatrix[key] = [0.0] * len(keys)
self.targetMatrix[key] = [0] * len(keys)
self.targetMatrix[key][index] = 1
index = index + 1
self.outputMag = len(keys)
def printConfusionMatrix(self):
keys = list(self.confusionMatrix.keys())
keys.sort()
print("\nConfusion Matrix")
for key in keys:
printPatterns(self.confusionMatrix[key])
print("\nKey, Precision, Recall")
#for key in keys:
#print(str(key) + ", " + str(round(self.calcPrecision(key), 3)) + ", " + str(round(self.calcRecall(key), 3)))
self.calcPrecisionAndRecall()
def calcPrecision(self, k):
tp = self.confusionMatrix[k][k]
fpSum = sum(self.confusionMatrix[k])
if fpSum == 0.0:
return fpSum
return tp/fpSum
def calcRecall(self, k):
tp = self.confusionMatrix[k][k]
keys = list(self.confusionMatrix.keys())
keys.sort()
i = 0
tnSum = 0.0
for key in keys:
tnSum = tnSum + self.confusionMatrix[key][k]
if tnSum == 0.0:
return tnSum
return tp/tnSum
def calcPrecisionAndRecall(self):
keys = list(self.confusionMatrix.keys())
matrixSum = 0.0
keys.sort()
i = 0
precision = []
recall = []
diagonal = []
for key in keys:
row = self.confusionMatrix[key]
rowSum = 0
for j, val in enumerate(row):
if i==j:
diagonal.append(val)
rowSum += val
if len(recall) == j:
recall.append(val)
else:
recall[j] = recall[j] + val
matrixSum = matrixSum + rowSum
precision.append(rowSum)
i += 1
for i, elem in enumerate(diagonal):
if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:
print(str(keys[i]) + ", " + str(round(elem / precision[i], 4)) + ", " + str(round(elem/recall[i], 4)))
print("Overall Correct: " + str(round(sum(diagonal)/matrixSum, 4)))
def targetVector(self, key):
return self.targetMatrix[key]
def updateConfusionMatrix(self, key, outputs):
maxIndex = 0
maxValue = 0
for i in range(len(outputs)):
if maxValue < outputs[i]:
maxIndex = i
maxValue = outputs[i]
self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][maxIndex] + 1
def inputMagnitude(self):
return self.inputMagX * self.inputMagY
def outputMagnitude(self):
return self.outputMag | [
"#!/usr/bin/python\n# patternSet.py\n\nimport json\nimport random\nimport math\n\n# used in calculating Sigma based on center locations\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + ((p[i][j]-q[i][j])*(p[i][j]-q[i][j]))\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + ((p[i]-q[i])*(p[i]-q[i]))\n else:\n sumOfSquares = sumOfSquares + ((p-q)*(p-q))\n return math.sqrt(sumOfSquares)\n\n# Centers are built for each of the targets in two steps\n# First an average is built for each target from each pattern of that target type\n# Next we run k-means on the new centers against all patterns\n# Sigmas are calculated for each element\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print(\"Found \" + str(len(centersTargets)) + \" targets.\")\n print(\"Constructing Centers and Sigmas...\")\n # build center as mean of all trained k patterns, and sigma as standard deviation\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n\n # OPTIONAL k-MEANS CENTER SOFTENING --WINNER--\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n #print(\"dist:\" + str(round(dist, 4)) + \", delta:\" + str(round(distDelta, 4)))\n\n # #Build Sigmas for each space\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n\n return {'centers':centers, 'sigmas':sigmas}\n\n# given several patterns we create an average pattern of the same dimension\n# This method works for 2D arrays, 1D arrays, and scalers\ndef buildMeanPattern(patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n mPat = emptyPattern(w, h)\n for pat in patterns:\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] + pat['p'][i][j]\n else:\n for j in range(w):\n mPat[j] = mPat[j] + pat['p'][j]\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] / len(patterns)\n else:\n for j in range(w):\n mPat[j] = mPat[j] / len(patterns)\n return mPat\n\n# This pattern shows us where the fuzziness is in our average\ndef buildSigmaPattern(meanPat, patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n sPat = emptyPattern(w, h)\n # Sum over all square of distance from means\n if h > 1:\n for i in range(h):\n for j in range(w):\n for pat in patterns:\n sPat[i][j] = sPat[i][j] + (pat['p'][i][j] - meanPat[i][j])*(pat['p'][i][j] - meanPat[i][j])\n sPat[i][j] = math.sqrt(1.0/len(patterns)*sPat[i][j])\n else:\n for j in range(w):\n for pat in patterns:\n sPat[j] = sPat[j] + (pat['p'][j] - meanPat[j])*(pat['p'][j] - meanPat[j])\n sPat[j] = math.sqrt(1.0/len(patterns)*sPat[j])\n return sPat\n\n# Used in k-means, here we take an average of the member patterns to construct a new center\ndef adjustCenters(patterns, centers):\n groups = {}\n for k in centers.keys():\n groups[k] = []\n for pattern in patterns:\n bestDist = 99999\n bestKey = ''\n for key in centers.keys():\n center = centers[key]\n dist = euclidianDistance(pattern['p'], center)\n if dist < bestDist:\n bestDist = dist\n bestKey = key\n groups[bestKey].append(pattern)\n newCenters = {}\n for k in centers.keys():\n if len(groups[k]) > 0:\n newCenters[k] = buildMeanPattern(groups[k])\n else:\n newCenters[k] = centers[k]\n return newCenters\n\n# Creates and empty pattern of the given dimensionality\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat \n\n# print an individual pattern with or without target value\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print(\"Target: \" + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n# A Pattern set contains sets of 3 types of patterns\n# and can be used to retrieve only those patterns of a certain type\nclass PatternSet:\n # Reads patterns in from a file, and puts them in their coorisponding set\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n \n # Assign Patterns and Randomize order\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + \" Patterns Available (\" + str(self.inputMagY) + \"x\" + str(self.inputMagX) + \")\")\n\n # Construct Centers but base them only off the cases to be trained with\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data['count']*percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n\n # Architecture has 1 output node for each digit / letter\n # Assemble our target and confusion matrix\n keys = list(self.centers.keys())\n keys.sort()\n print(\"Centers: [\" + ', '.join(str(k).split('.')[0] for k in keys) + \"]\")\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n\n # Initialize Confusion Matrix and Target Matrix\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print(\"\\nConfusion Matrix\")\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print(\"\\nKey, Precision, Recall\")\n #for key in keys:\n #print(str(key) + \", \" + str(round(self.calcPrecision(key), 3)) + \", \" + str(round(self.calcRecall(key), 3)))\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp/fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp/tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i==j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + \", \" + str(round(elem / precision[i], 4)) + \", \" + str(round(elem/recall[i], 4)))\n print(\"Overall Correct: \" + str(round(sum(diagonal)/matrixSum, 4)))\n \n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag",
"import json\nimport random\nimport math\n\n\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + (p[i][j] - q[i][j]) * (p[\n i][j] - q[i][j])\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + (p[i] - q[i]) * (p[i] - q[i])\n else:\n sumOfSquares = sumOfSquares + (p - q) * (p - q)\n return math.sqrt(sumOfSquares)\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\ndef buildMeanPattern(patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n mPat = emptyPattern(w, h)\n for pat in patterns:\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] + pat['p'][i][j]\n else:\n for j in range(w):\n mPat[j] = mPat[j] + pat['p'][j]\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] / len(patterns)\n else:\n for j in range(w):\n mPat[j] = mPat[j] / len(patterns)\n return mPat\n\n\ndef buildSigmaPattern(meanPat, patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n sPat = emptyPattern(w, h)\n if h > 1:\n for i in range(h):\n for j in range(w):\n for pat in patterns:\n sPat[i][j] = sPat[i][j] + (pat['p'][i][j] - meanPat[i][j]\n ) * (pat['p'][i][j] - meanPat[i][j])\n sPat[i][j] = math.sqrt(1.0 / len(patterns) * sPat[i][j])\n else:\n for j in range(w):\n for pat in patterns:\n sPat[j] = sPat[j] + (pat['p'][j] - meanPat[j]) * (pat['p'][\n j] - meanPat[j])\n sPat[j] = math.sqrt(1.0 / len(patterns) * sPat[j])\n return sPat\n\n\ndef adjustCenters(patterns, centers):\n groups = {}\n for k in centers.keys():\n groups[k] = []\n for pattern in patterns:\n bestDist = 99999\n bestKey = ''\n for key in centers.keys():\n center = centers[key]\n dist = euclidianDistance(pattern['p'], center)\n if dist < bestDist:\n bestDist = dist\n bestKey = key\n groups[bestKey].append(pattern)\n newCenters = {}\n for k in centers.keys():\n if len(groups[k]) > 0:\n newCenters[k] = buildMeanPattern(groups[k])\n else:\n newCenters[k] = centers[k]\n return newCenters\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n\n\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + (p[i][j] - q[i][j]) * (p[\n i][j] - q[i][j])\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + (p[i] - q[i]) * (p[i] - q[i])\n else:\n sumOfSquares = sumOfSquares + (p - q) * (p - q)\n return math.sqrt(sumOfSquares)\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\ndef buildMeanPattern(patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n mPat = emptyPattern(w, h)\n for pat in patterns:\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] + pat['p'][i][j]\n else:\n for j in range(w):\n mPat[j] = mPat[j] + pat['p'][j]\n if h > 1:\n for i in range(h):\n for j in range(w):\n mPat[i][j] = mPat[i][j] / len(patterns)\n else:\n for j in range(w):\n mPat[j] = mPat[j] / len(patterns)\n return mPat\n\n\ndef buildSigmaPattern(meanPat, patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n sPat = emptyPattern(w, h)\n if h > 1:\n for i in range(h):\n for j in range(w):\n for pat in patterns:\n sPat[i][j] = sPat[i][j] + (pat['p'][i][j] - meanPat[i][j]\n ) * (pat['p'][i][j] - meanPat[i][j])\n sPat[i][j] = math.sqrt(1.0 / len(patterns) * sPat[i][j])\n else:\n for j in range(w):\n for pat in patterns:\n sPat[j] = sPat[j] + (pat['p'][j] - meanPat[j]) * (pat['p'][\n j] - meanPat[j])\n sPat[j] = math.sqrt(1.0 / len(patterns) * sPat[j])\n return sPat\n\n\ndef adjustCenters(patterns, centers):\n groups = {}\n for k in centers.keys():\n groups[k] = []\n for pattern in patterns:\n bestDist = 99999\n bestKey = ''\n for key in centers.keys():\n center = centers[key]\n dist = euclidianDistance(pattern['p'], center)\n if dist < bestDist:\n bestDist = dist\n bestKey = key\n groups[bestKey].append(pattern)\n newCenters = {}\n for k in centers.keys():\n if len(groups[k]) > 0:\n newCenters[k] = buildMeanPattern(groups[k])\n else:\n newCenters[k] = centers[k]\n return newCenters\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n\n\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + (p[i][j] - q[i][j]) * (p[\n i][j] - q[i][j])\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + (p[i] - q[i]) * (p[i] - q[i])\n else:\n sumOfSquares = sumOfSquares + (p - q) * (p - q)\n return math.sqrt(sumOfSquares)\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n\n\ndef buildSigmaPattern(meanPat, patterns):\n h = 0\n w = len(patterns[0]['p'])\n if isinstance(patterns[0]['p'][0], list):\n h = len(patterns[0]['p'])\n w = len(patterns[0]['p'][0])\n sPat = emptyPattern(w, h)\n if h > 1:\n for i in range(h):\n for j in range(w):\n for pat in patterns:\n sPat[i][j] = sPat[i][j] + (pat['p'][i][j] - meanPat[i][j]\n ) * (pat['p'][i][j] - meanPat[i][j])\n sPat[i][j] = math.sqrt(1.0 / len(patterns) * sPat[i][j])\n else:\n for j in range(w):\n for pat in patterns:\n sPat[j] = sPat[j] + (pat['p'][j] - meanPat[j]) * (pat['p'][\n j] - meanPat[j])\n sPat[j] = math.sqrt(1.0 / len(patterns) * sPat[j])\n return sPat\n\n\ndef adjustCenters(patterns, centers):\n groups = {}\n for k in centers.keys():\n groups[k] = []\n for pattern in patterns:\n bestDist = 99999\n bestKey = ''\n for key in centers.keys():\n center = centers[key]\n dist = euclidianDistance(pattern['p'], center)\n if dist < bestDist:\n bestDist = dist\n bestKey = key\n groups[bestKey].append(pattern)\n newCenters = {}\n for k in centers.keys():\n if len(groups[k]) > 0:\n newCenters[k] = buildMeanPattern(groups[k])\n else:\n newCenters[k] = centers[k]\n return newCenters\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n\n\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + (p[i][j] - q[i][j]) * (p[\n i][j] - q[i][j])\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + (p[i] - q[i]) * (p[i] - q[i])\n else:\n sumOfSquares = sumOfSquares + (p - q) * (p - q)\n return math.sqrt(sumOfSquares)\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n<function token>\n\n\ndef adjustCenters(patterns, centers):\n groups = {}\n for k in centers.keys():\n groups[k] = []\n for pattern in patterns:\n bestDist = 99999\n bestKey = ''\n for key in centers.keys():\n center = centers[key]\n dist = euclidianDistance(pattern['p'], center)\n if dist < bestDist:\n bestDist = dist\n bestKey = key\n groups[bestKey].append(pattern)\n newCenters = {}\n for k in centers.keys():\n if len(groups[k]) > 0:\n newCenters[k] = buildMeanPattern(groups[k])\n else:\n newCenters[k] = centers[k]\n return newCenters\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n\n\ndef euclidianDistance(p, q):\n sumOfSquares = 0.0\n if isinstance(p, list):\n if isinstance(p[0], list):\n for i in range(len(p)):\n for j in range(len(p[i])):\n sumOfSquares = sumOfSquares + (p[i][j] - q[i][j]) * (p[\n i][j] - q[i][j])\n else:\n for i in range(len(p)):\n sumOfSquares = sumOfSquares + (p[i] - q[i]) * (p[i] - q[i])\n else:\n sumOfSquares = sumOfSquares + (p - q) * (p - q)\n return math.sqrt(sumOfSquares)\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\ndef printPatterns(pattern):\n if isinstance(pattern, dict):\n for key in pattern.keys():\n if key == 't':\n print('Target: ' + str(key))\n elif key == 'p':\n printPatterns(pattern['p'])\n elif isinstance(pattern[0], list):\n for pat in pattern:\n printPatterns(pat)\n else:\n print(', '.join(str(round(x, 3)) for x in pattern))\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef emptyPattern(w, h):\n pat = []\n if h > 1:\n for i in range(h):\n pat.append([])\n for j in range(w):\n pat[i].append(0.0)\n else:\n for j in range(w):\n pat.append(0.0)\n return pat\n\n\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n\n\ndef buildCentersAndSigmas(patterns):\n centersTargets = {}\n for pattern in patterns:\n if pattern['t'] not in centersTargets:\n centersTargets[pattern['t']] = []\n centersTargets[pattern['t']].append(pattern)\n centers = {}\n sigmas = {}\n print('Found ' + str(len(centersTargets)) + ' targets.')\n print('Constructing Centers and Sigmas...')\n for k in centersTargets.keys():\n kPats = centersTargets[k]\n centers[k] = buildMeanPattern(kPats)\n dist = 100\n distDelta = 100\n oldDist = 0\n while dist > 1 and abs(distDelta) > 0.01:\n tempCenters = adjustCenters(patterns, centers)\n dist = 0\n for k in centersTargets.keys():\n dist = dist + euclidianDistance(centers[k], tempCenters[k])\n centers = tempCenters\n distDelta = dist - oldDist\n oldDist = dist\n for k in centersTargets.keys():\n sigmas[k] = buildSigmaPattern(centers[k], kPats)\n return {'centers': centers, 'sigmas': sigmas}\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n\n def targetVector(self, key):\n return self.targetMatrix[key]\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n\n def inputMagnitude(self):\n return self.inputMagX * self.inputMagY\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n <function token>\n\n def outputMagnitude(self):\n return self.outputMag\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n\n def updateConfusionMatrix(self, key, outputs):\n maxIndex = 0\n maxValue = 0\n for i in range(len(outputs)):\n if maxValue < outputs[i]:\n maxIndex = i\n maxValue = outputs[i]\n self.confusionMatrix[key][maxIndex] = self.confusionMatrix[key][\n maxIndex] + 1\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n\n def calcRecall(self, k):\n tp = self.confusionMatrix[k][k]\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n i = 0\n tnSum = 0.0\n for key in keys:\n tnSum = tnSum + self.confusionMatrix[key][k]\n if tnSum == 0.0:\n return tnSum\n return tp / tnSum\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n\n def calcPrecision(self, k):\n tp = self.confusionMatrix[k][k]\n fpSum = sum(self.confusionMatrix[k])\n if fpSum == 0.0:\n return fpSum\n return tp / fpSum\n <function token>\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n\n def __init__(self, fileName, percentTraining):\n with open(fileName) as jsonData:\n data = json.load(jsonData)\n self.patterns = data['patterns']\n self.count = data['count']\n self.inputMagX = len(self.patterns[0]['p'])\n self.inputMagY = 1\n if isinstance(self.patterns[0]['p'][0], list):\n self.inputMagX = len(self.patterns[0]['p'][0])\n self.inputMagY = len(self.patterns[0]['p'])\n random.shuffle(self.patterns)\n print(str(len(self.patterns)) + ' Patterns Available (' + str(self.\n inputMagY) + 'x' + str(self.inputMagX) + ')')\n centersAndSigmas = buildCentersAndSigmas(self.patterns[:int(data[\n 'count'] * percentTraining)])\n self.centers = centersAndSigmas['centers']\n self.sigmas = centersAndSigmas['sigmas']\n keys = list(self.centers.keys())\n keys.sort()\n print('Centers: [' + ', '.join(str(k).split('.')[0] for k in keys) +\n ']')\n self.confusionMatrix = {}\n self.targetMatrix = {}\n index = 0\n for key in keys:\n self.confusionMatrix[key] = [0.0] * len(keys)\n self.targetMatrix[key] = [0] * len(keys)\n self.targetMatrix[key][index] = 1\n index = index + 1\n self.outputMag = len(keys)\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n <function token>\n <function token>\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n <function token>\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n <function token>\n <function token>\n\n def calcPrecisionAndRecall(self):\n keys = list(self.confusionMatrix.keys())\n matrixSum = 0.0\n keys.sort()\n i = 0\n precision = []\n recall = []\n diagonal = []\n for key in keys:\n row = self.confusionMatrix[key]\n rowSum = 0\n for j, val in enumerate(row):\n if i == j:\n diagonal.append(val)\n rowSum += val\n if len(recall) == j:\n recall.append(val)\n else:\n recall[j] = recall[j] + val\n matrixSum = matrixSum + rowSum\n precision.append(rowSum)\n i += 1\n for i, elem in enumerate(diagonal):\n if abs(precision[i]) > 0.0 and abs(recall[i]) > 0.0:\n print(str(keys[i]) + ', ' + str(round(elem / precision[i], \n 4)) + ', ' + str(round(elem / recall[i], 4)))\n print('Overall Correct: ' + str(round(sum(diagonal) / matrixSum, 4)))\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n <function token>\n\n def printConfusionMatrix(self):\n keys = list(self.confusionMatrix.keys())\n keys.sort()\n print('\\nConfusion Matrix')\n for key in keys:\n printPatterns(self.confusionMatrix[key])\n print('\\nKey, Precision, Recall')\n self.calcPrecisionAndRecall()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\nclass PatternSet:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<class token>\n"
] | false |
99,725 | c1de1c18ec0c0797985467b373506975d1d855b5 | #!/usr/bin/env python3
from textwrap import dedent
from argparse import ArgumentParser
from formatter import Formatter
from filereader import get_communities_data
class BirdRoaFormatter(Formatter):
"""
Formatter for roa table in bird format
"""
def __init__(self, roa_table_name=False):
self.config = []
self.data = []
self.indent = ""
self.roa_table_name = roa_table_name
if not roa_table_name:
self.add_comment(dedent(
"""
This file is automatically generated.
You need to add the surrounding roa table statement yourself.
So Include it via:
roa table icvpn { include "roa.con?" }
"""
))
else:
self.indent = "\t"
self.config.append("roa table {tbl_name} {{".format(
tbl_name=roa_table_name
))
def add_data(self, asn, name, network, max_prefixlen):
self.data.append((network, max_prefixlen, asn, name))
def finalize(self):
maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))
maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))
for entry in self.data:
self.config.append(
"{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}".format(
indent=self.indent, subnet=entry[0], max_prefix_len=entry[1], asn=entry[2],
community=entry[3], len_net=maxlen_net, len_asn=maxlen_asn
))
if self.roa_table_name:
self.config.append("}")
return "\n".join(self.config)
class Bird2RoaFormatter(Formatter):
"""
Formatter for roa tables in bird2 format
https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static
"""
def __init__(self, roa_table_name=False):
self.config = []
self.data = []
self.indent = ""
self.roa_table_name = roa_table_name
if not roa_table_name:
self.add_comment(dedent(
"""
This file is automatically generated.
You need to add the surrounding roa table statement yourself.
So Include it via:
protocol static {
roa4 {table roa_icvpn4; };
include "roa4.con?";
}
"""
))
else:
self.indent = "\t"
self.config.append("roa table {tbl_name} {{".format(
tbl_name=roa_table_name
))
def add_data(self, asn, name, network, max_prefixlen):
self.data.append((network, max_prefixlen, asn, name))
def finalize(self):
maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))
maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))
for entry in self.data:
self.config.append(
"{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}".format(
indent=self.indent, subnet=entry[0], max_prefix_len=entry[1], asn=entry[2],
community=entry[3], len_net=maxlen_net, len_asn=maxlen_asn
))
if self.roa_table_name:
self.config.append("}")
return "\n".join(self.config)
def add_roa(formatter, asn, community, network, prefixlen, default_max_prefixlen):
formatter.add_data(asn, community, network, max(prefixlen, default_max_prefixlen))
def create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen, *args):
"""
Generates a configuration using all files in srcdir
(non-recursively) excluding communities from 'exclude'.
The files are read in lexicographic order to produce deterministic
results.
"""
formatter = fmtclass(*args)
if default_max_prefixlen is None:
if family == 'ipv6':
default_max_prefixlen = 64
elif family == 'ipv4':
default_max_prefixlen = 24
for community, data in get_communities_data(srcdir, exclude):
try:
networks = data['networks'][family]
asn = data['asn']
for network in sorted(networks):
prefixlen = int(network.split("/")[1])
add_roa(formatter, asn, community, network, prefixlen, default_max_prefixlen)
except (TypeError, KeyError):
pass
delegate = data.get('delegate', {})
for delegate_asn, delegate_networks in delegate.items():
for delegate_network in delegate_networks:
# not very beautiful, but everything more proper requires including a library
if family == 'ipv6' and '.' in delegate_network:
continue
if family == 'ipv4' and ':' in delegate_network:
continue
prefixlen = int(delegate_network.split("/")[1])
add_roa(formatter, delegate_asn, "{} (delegation)".format(community), delegate_network, prefixlen,
default_max_prefixlen)
print(formatter.finalize())
if __name__ == '__main__':
formatters = {
'bird': BirdRoaFormatter,
'bird2': Bird2RoaFormatter,
}
PARSER = ArgumentParser()
PARSER.add_argument('-f', '--format', dest='fmt',
help='Create config in format FMT. Possible values: {formatters}.'.format(
formatters=", ".join(formatters.keys())),
metavar='FMT',
choices=list(formatters.keys()),
default='bird')
PARSER.add_argument('-4', dest='family', action='store_const', const='ipv4',
help='Generate IPv4 config')
PARSER.add_argument('-6', dest='family', action='store_const', const='ipv6',
help='Generate IPv6 config')
PARSER.add_argument('-s', '--sourcedir', dest='src',
help="Use files in DIR as input files. Default: ../icvpn-meta/",
metavar="DIR", default="../icvpn-meta/")
PARSER.add_argument('-x', '--exclude', dest='exclude', action='append',
help='Exclude the comma-separated list of COMMUNITIES',
metavar='COMMUNITIES',
default=[])
PARSER.add_argument('-m', '--max', dest='default_max_prefixlen', default=None,
type=int, help='max prefix length to accept')
PARSER.add_argument('--bird-table-name', dest='bird_table_name',
help='Render ROA table with given name', default=False)
PARSER.set_defaults(family='ipv6')
ARGS = PARSER.parse_args()
create_config(ARGS.src, set(ARGS.exclude),
ARGS.family, formatters[ARGS.fmt],
ARGS.default_max_prefixlen, ARGS.bird_table_name)
| [
"#!/usr/bin/env python3\n\nfrom textwrap import dedent\nfrom argparse import ArgumentParser\nfrom formatter import Formatter\nfrom filereader import get_communities_data\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = \"\"\n self.roa_table_name = roa_table_name\n\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = \"\\t\"\n self.config.append(\"roa table {tbl_name} {{\".format(\n tbl_name=roa_table_name\n ))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n\n for entry in self.data:\n self.config.append(\n \"{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}\".format(\n indent=self.indent, subnet=entry[0], max_prefix_len=entry[1], asn=entry[2],\n community=entry[3], len_net=maxlen_net, len_asn=maxlen_asn\n ))\n\n if self.roa_table_name:\n self.config.append(\"}\")\n\n return \"\\n\".join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = \"\"\n self.roa_table_name = roa_table_name\n\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = \"\\t\"\n self.config.append(\"roa table {tbl_name} {{\".format(\n tbl_name=roa_table_name\n ))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n\n for entry in self.data:\n self.config.append(\n \"{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}\".format(\n indent=self.indent, subnet=entry[0], max_prefix_len=entry[1], asn=entry[2],\n community=entry[3], len_net=maxlen_net, len_asn=maxlen_asn\n ))\n\n if self.roa_table_name:\n self.config.append(\"}\")\n\n return \"\\n\".join(self.config)\n\n\ndef add_roa(formatter, asn, community, network, prefixlen, default_max_prefixlen):\n formatter.add_data(asn, community, network, max(prefixlen, default_max_prefixlen))\n\n\ndef create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen, *args):\n \"\"\"\n Generates a configuration using all files in srcdir\n (non-recursively) excluding communities from 'exclude'.\n\n The files are read in lexicographic order to produce deterministic\n results.\n \"\"\"\n formatter = fmtclass(*args)\n\n if default_max_prefixlen is None:\n if family == 'ipv6':\n default_max_prefixlen = 64\n elif family == 'ipv4':\n default_max_prefixlen = 24\n\n for community, data in get_communities_data(srcdir, exclude):\n try:\n networks = data['networks'][family]\n asn = data['asn']\n for network in sorted(networks):\n prefixlen = int(network.split(\"/\")[1])\n add_roa(formatter, asn, community, network, prefixlen, default_max_prefixlen)\n except (TypeError, KeyError):\n pass\n\n delegate = data.get('delegate', {})\n for delegate_asn, delegate_networks in delegate.items():\n for delegate_network in delegate_networks:\n # not very beautiful, but everything more proper requires including a library\n if family == 'ipv6' and '.' in delegate_network:\n continue\n if family == 'ipv4' and ':' in delegate_network:\n continue\n prefixlen = int(delegate_network.split(\"/\")[1])\n add_roa(formatter, delegate_asn, \"{} (delegation)\".format(community), delegate_network, prefixlen,\n default_max_prefixlen)\n\n print(formatter.finalize())\n\n\nif __name__ == '__main__':\n formatters = {\n 'bird': BirdRoaFormatter,\n 'bird2': Bird2RoaFormatter,\n }\n\n PARSER = ArgumentParser()\n PARSER.add_argument('-f', '--format', dest='fmt',\n help='Create config in format FMT. Possible values: {formatters}.'.format(\n formatters=\", \".join(formatters.keys())),\n metavar='FMT',\n choices=list(formatters.keys()),\n default='bird')\n PARSER.add_argument('-4', dest='family', action='store_const', const='ipv4',\n help='Generate IPv4 config')\n PARSER.add_argument('-6', dest='family', action='store_const', const='ipv6',\n help='Generate IPv6 config')\n PARSER.add_argument('-s', '--sourcedir', dest='src',\n help=\"Use files in DIR as input files. Default: ../icvpn-meta/\",\n metavar=\"DIR\", default=\"../icvpn-meta/\")\n PARSER.add_argument('-x', '--exclude', dest='exclude', action='append',\n help='Exclude the comma-separated list of COMMUNITIES',\n metavar='COMMUNITIES',\n default=[])\n PARSER.add_argument('-m', '--max', dest='default_max_prefixlen', default=None,\n type=int, help='max prefix length to accept')\n PARSER.add_argument('--bird-table-name', dest='bird_table_name',\n help='Render ROA table with given name', default=False)\n PARSER.set_defaults(family='ipv6')\n\n ARGS = PARSER.parse_args()\n\n create_config(ARGS.src, set(ARGS.exclude),\n ARGS.family, formatters[ARGS.fmt],\n ARGS.default_max_prefixlen, ARGS.bird_table_name)\n",
"from textwrap import dedent\nfrom argparse import ArgumentParser\nfrom formatter import Formatter\nfrom filereader import get_communities_data\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\ndef add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen):\n formatter.add_data(asn, community, network, max(prefixlen,\n default_max_prefixlen))\n\n\ndef create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen,\n *args):\n \"\"\"\n Generates a configuration using all files in srcdir\n (non-recursively) excluding communities from 'exclude'.\n\n The files are read in lexicographic order to produce deterministic\n results.\n \"\"\"\n formatter = fmtclass(*args)\n if default_max_prefixlen is None:\n if family == 'ipv6':\n default_max_prefixlen = 64\n elif family == 'ipv4':\n default_max_prefixlen = 24\n for community, data in get_communities_data(srcdir, exclude):\n try:\n networks = data['networks'][family]\n asn = data['asn']\n for network in sorted(networks):\n prefixlen = int(network.split('/')[1])\n add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen)\n except (TypeError, KeyError):\n pass\n delegate = data.get('delegate', {})\n for delegate_asn, delegate_networks in delegate.items():\n for delegate_network in delegate_networks:\n if family == 'ipv6' and '.' in delegate_network:\n continue\n if family == 'ipv4' and ':' in delegate_network:\n continue\n prefixlen = int(delegate_network.split('/')[1])\n add_roa(formatter, delegate_asn, '{} (delegation)'.format(\n community), delegate_network, prefixlen,\n default_max_prefixlen)\n print(formatter.finalize())\n\n\nif __name__ == '__main__':\n formatters = {'bird': BirdRoaFormatter, 'bird2': Bird2RoaFormatter}\n PARSER = ArgumentParser()\n PARSER.add_argument('-f', '--format', dest='fmt', help=\n 'Create config in format FMT. Possible values: {formatters}.'.\n format(formatters=', '.join(formatters.keys())), metavar='FMT',\n choices=list(formatters.keys()), default='bird')\n PARSER.add_argument('-4', dest='family', action='store_const', const=\n 'ipv4', help='Generate IPv4 config')\n PARSER.add_argument('-6', dest='family', action='store_const', const=\n 'ipv6', help='Generate IPv6 config')\n PARSER.add_argument('-s', '--sourcedir', dest='src', help=\n 'Use files in DIR as input files. Default: ../icvpn-meta/', metavar\n ='DIR', default='../icvpn-meta/')\n PARSER.add_argument('-x', '--exclude', dest='exclude', action='append',\n help='Exclude the comma-separated list of COMMUNITIES', metavar=\n 'COMMUNITIES', default=[])\n PARSER.add_argument('-m', '--max', dest='default_max_prefixlen',\n default=None, type=int, help='max prefix length to accept')\n PARSER.add_argument('--bird-table-name', dest='bird_table_name', help=\n 'Render ROA table with given name', default=False)\n PARSER.set_defaults(family='ipv6')\n ARGS = PARSER.parse_args()\n create_config(ARGS.src, set(ARGS.exclude), ARGS.family, formatters[ARGS\n .fmt], ARGS.default_max_prefixlen, ARGS.bird_table_name)\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\ndef add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen):\n formatter.add_data(asn, community, network, max(prefixlen,\n default_max_prefixlen))\n\n\ndef create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen,\n *args):\n \"\"\"\n Generates a configuration using all files in srcdir\n (non-recursively) excluding communities from 'exclude'.\n\n The files are read in lexicographic order to produce deterministic\n results.\n \"\"\"\n formatter = fmtclass(*args)\n if default_max_prefixlen is None:\n if family == 'ipv6':\n default_max_prefixlen = 64\n elif family == 'ipv4':\n default_max_prefixlen = 24\n for community, data in get_communities_data(srcdir, exclude):\n try:\n networks = data['networks'][family]\n asn = data['asn']\n for network in sorted(networks):\n prefixlen = int(network.split('/')[1])\n add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen)\n except (TypeError, KeyError):\n pass\n delegate = data.get('delegate', {})\n for delegate_asn, delegate_networks in delegate.items():\n for delegate_network in delegate_networks:\n if family == 'ipv6' and '.' in delegate_network:\n continue\n if family == 'ipv4' and ':' in delegate_network:\n continue\n prefixlen = int(delegate_network.split('/')[1])\n add_roa(formatter, delegate_asn, '{} (delegation)'.format(\n community), delegate_network, prefixlen,\n default_max_prefixlen)\n print(formatter.finalize())\n\n\nif __name__ == '__main__':\n formatters = {'bird': BirdRoaFormatter, 'bird2': Bird2RoaFormatter}\n PARSER = ArgumentParser()\n PARSER.add_argument('-f', '--format', dest='fmt', help=\n 'Create config in format FMT. Possible values: {formatters}.'.\n format(formatters=', '.join(formatters.keys())), metavar='FMT',\n choices=list(formatters.keys()), default='bird')\n PARSER.add_argument('-4', dest='family', action='store_const', const=\n 'ipv4', help='Generate IPv4 config')\n PARSER.add_argument('-6', dest='family', action='store_const', const=\n 'ipv6', help='Generate IPv6 config')\n PARSER.add_argument('-s', '--sourcedir', dest='src', help=\n 'Use files in DIR as input files. Default: ../icvpn-meta/', metavar\n ='DIR', default='../icvpn-meta/')\n PARSER.add_argument('-x', '--exclude', dest='exclude', action='append',\n help='Exclude the comma-separated list of COMMUNITIES', metavar=\n 'COMMUNITIES', default=[])\n PARSER.add_argument('-m', '--max', dest='default_max_prefixlen',\n default=None, type=int, help='max prefix length to accept')\n PARSER.add_argument('--bird-table-name', dest='bird_table_name', help=\n 'Render ROA table with given name', default=False)\n PARSER.set_defaults(family='ipv6')\n ARGS = PARSER.parse_args()\n create_config(ARGS.src, set(ARGS.exclude), ARGS.family, formatters[ARGS\n .fmt], ARGS.default_max_prefixlen, ARGS.bird_table_name)\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\ndef add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen):\n formatter.add_data(asn, community, network, max(prefixlen,\n default_max_prefixlen))\n\n\ndef create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen,\n *args):\n \"\"\"\n Generates a configuration using all files in srcdir\n (non-recursively) excluding communities from 'exclude'.\n\n The files are read in lexicographic order to produce deterministic\n results.\n \"\"\"\n formatter = fmtclass(*args)\n if default_max_prefixlen is None:\n if family == 'ipv6':\n default_max_prefixlen = 64\n elif family == 'ipv4':\n default_max_prefixlen = 24\n for community, data in get_communities_data(srcdir, exclude):\n try:\n networks = data['networks'][family]\n asn = data['asn']\n for network in sorted(networks):\n prefixlen = int(network.split('/')[1])\n add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen)\n except (TypeError, KeyError):\n pass\n delegate = data.get('delegate', {})\n for delegate_asn, delegate_networks in delegate.items():\n for delegate_network in delegate_networks:\n if family == 'ipv6' and '.' in delegate_network:\n continue\n if family == 'ipv4' and ':' in delegate_network:\n continue\n prefixlen = int(delegate_network.split('/')[1])\n add_roa(formatter, delegate_asn, '{} (delegation)'.format(\n community), delegate_network, prefixlen,\n default_max_prefixlen)\n print(formatter.finalize())\n\n\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n\n\ndef create_config(srcdir, exclude, family, fmtclass, default_max_prefixlen,\n *args):\n \"\"\"\n Generates a configuration using all files in srcdir\n (non-recursively) excluding communities from 'exclude'.\n\n The files are read in lexicographic order to produce deterministic\n results.\n \"\"\"\n formatter = fmtclass(*args)\n if default_max_prefixlen is None:\n if family == 'ipv6':\n default_max_prefixlen = 64\n elif family == 'ipv4':\n default_max_prefixlen = 24\n for community, data in get_communities_data(srcdir, exclude):\n try:\n networks = data['networks'][family]\n asn = data['asn']\n for network in sorted(networks):\n prefixlen = int(network.split('/')[1])\n add_roa(formatter, asn, community, network, prefixlen,\n default_max_prefixlen)\n except (TypeError, KeyError):\n pass\n delegate = data.get('delegate', {})\n for delegate_asn, delegate_networks in delegate.items():\n for delegate_network in delegate_networks:\n if family == 'ipv6' and '.' in delegate_network:\n continue\n if family == 'ipv4' and ':' in delegate_network:\n continue\n prefixlen = int(delegate_network.split('/')[1])\n add_roa(formatter, delegate_asn, '{} (delegation)'.format(\n community), delegate_network, prefixlen,\n default_max_prefixlen)\n print(formatter.finalize())\n\n\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n \"\"\"\n Formatter for roa table in bird format\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n <docstring token>\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n <docstring token>\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n <function token>\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}roa {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n <docstring token>\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n roa table icvpn { include \"roa.con?\" }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n <function token>\n <function token>\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n\n\nclass BirdRoaFormatter(Formatter):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Bird2RoaFormatter(Formatter):\n \"\"\"\n Formatter for roa tables in bird2 format\n https://bird.network.cz/?get_doc&v=20&f=bird-6.html#static\n \"\"\"\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Bird2RoaFormatter(Formatter):\n <docstring token>\n\n def __init__(self, roa_table_name=False):\n self.config = []\n self.data = []\n self.indent = ''\n self.roa_table_name = roa_table_name\n if not roa_table_name:\n self.add_comment(dedent(\n \"\"\"\n This file is automatically generated.\n You need to add the surrounding roa table statement yourself.\n So Include it via:\n protocol static {\n roa4 {table roa_icvpn4; };\n include \"roa4.con?\";\n }\n \"\"\"\n ))\n else:\n self.indent = '\\t'\n self.config.append('roa table {tbl_name} {{'.format(tbl_name=\n roa_table_name))\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Bird2RoaFormatter(Formatter):\n <docstring token>\n <function token>\n\n def add_data(self, asn, name, network, max_prefixlen):\n self.data.append((network, max_prefixlen, asn, name))\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Bird2RoaFormatter(Formatter):\n <docstring token>\n <function token>\n <function token>\n\n def finalize(self):\n maxlen_net = str(max(map(lambda x: len(x[0]), self.data)))\n maxlen_asn = str(max(map(lambda x: len(str(x[2])), self.data)))\n for entry in self.data:\n self.config.append(\n '{indent}route {subnet:<{len_net}} max {max_prefix_len:>3} as {asn:>{len_asn}}; # {community}'\n .format(indent=self.indent, subnet=entry[0], max_prefix_len\n =entry[1], asn=entry[2], community=entry[3], len_net=\n maxlen_net, len_asn=maxlen_asn))\n if self.roa_table_name:\n self.config.append('}')\n return '\\n'.join(self.config)\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Bird2RoaFormatter(Formatter):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,726 | d4dfd7a3eef9b42867ff6ea74bd1cd5bc7bda160 | import phonenumbers
import arrow
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, BooleanField
from wtforms.validators import DataRequired, Length, Email, ValidationError
from flaskdocs.models import Groups, Staff
class AddStaffForm(FlaskForm):
first_name = StringField('Имя',
validators=[DataRequired(), Length(min=2, max=35)])
second_name = StringField('Фамилия',
validators=[DataRequired(), Length(min=2, max=35)])
email = StringField('Email',
validators=[DataRequired(), Email()])
phone = StringField('Номер телефона',
validators=[DataRequired()])
group = SelectField('Группа ', validators=[DataRequired()], coerce=int)
use_email = BooleanField('Email')
use_phone = BooleanField('SMS')
submit = SubmitField('Сохранить')
def __init__(self, *args, **kwargs):
super(AddStaffForm, self).__init__(*args, **kwargs)
self.group.choices = [(group.id, group.name) for group in Groups.query.all()]
def validate_email(self, email):
user = Staff.query.filter_by(email=email.data).first()
if user:
raise ValidationError('Работник с такой почтой уже зарегистрирован')
def validate_phone(self, phone):
try:
input_number = phonenumbers.parse(phone.data)
if not (phonenumbers.is_valid_number(input_number)):
raise ValidationError('ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)')
user = Staff.query.filter_by(phone=phone.data).first()
if user:
raise ValidationError('Работник с таким номером уже зарегистрирован')
except Exception as error:
raise ValidationError(error)
class AddDocsForm(FlaskForm):
date = StringField("Действительно до (Формат: ДД.ММ.ГГГГ)", validators=[DataRequired()])
name = StringField("Имя документа", validators=[DataRequired()])
submit = SubmitField('Добавить')
def validate_date(self, date):
try:
date = arrow.get(date.data,'DD.MM.YYYY')
if date < arrow.utcnow():
raise ValidationError("Срок действия документа истёк, невозможно добавить недействительный документ")
except Exception as error:
raise ValidationError(error)
class EditStaffForm(FlaskForm):
first_name = StringField('Имя',
validators=[DataRequired(), Length(min=2, max=35)])
second_name = StringField('Фамилия',
validators=[DataRequired(), Length(min=2, max=35)])
email = StringField('Email',
validators=[DataRequired(), Email()])
phone = StringField('Номер телефона',
validators=[DataRequired()])
group = SelectField('Группа ', validators=[DataRequired()], coerce=int)
use_email = BooleanField('Email')
use_phone = BooleanField('SMS')
submit = SubmitField('Сохранить')
def __init__(self, *args, **kwargs):
super(EditStaffForm, self).__init__(*args, **kwargs)
self.group.choices = [(group.id, group.name) for group in Groups.query.all()]
def validate_phone(self, phone):
try:
input_number = phonenumbers.parse(phone.data)
if not (phonenumbers.is_valid_number(input_number)):
raise ValidationError('ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)')
except Exception as error:
raise ValidationError(error) | [
"import phonenumbers\nimport arrow\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField, BooleanField\nfrom wtforms.validators import DataRequired, Length, Email, ValidationError\nfrom flaskdocs.models import Groups, Staff\n\n\nclass AddStaffForm(FlaskForm):\n first_name = StringField('Имя',\n validators=[DataRequired(), Length(min=2, max=35)])\n second_name = StringField('Фамилия',\n validators=[DataRequired(), Length(min=2, max=35)])\n email = StringField('Email',\n validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона',\n validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(AddStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.query.all()]\n\n\n def validate_email(self, email):\n user = Staff.query.filter_by(email=email.data).first()\n if user:\n raise ValidationError('Работник с такой почтой уже зарегистрирован')\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not (phonenumbers.is_valid_number(input_number)):\n raise ValidationError('ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)')\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError('Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\nclass AddDocsForm(FlaskForm):\n date = StringField(\"Действительно до (Формат: ДД.ММ.ГГГГ)\", validators=[DataRequired()])\n name = StringField(\"Имя документа\", validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data,'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\"Срок действия документа истёк, невозможно добавить недействительный документ\")\n except Exception as error:\n raise ValidationError(error)\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя',\n validators=[DataRequired(), Length(min=2, max=35)])\n second_name = StringField('Фамилия',\n validators=[DataRequired(), Length(min=2, max=35)])\n email = StringField('Email',\n validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона',\n validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not (phonenumbers.is_valid_number(input_number)):\n raise ValidationError('ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)')\n except Exception as error:\n raise ValidationError(error)",
"import phonenumbers\nimport arrow\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField, BooleanField\nfrom wtforms.validators import DataRequired, Length, Email, ValidationError\nfrom flaskdocs.models import Groups, Staff\n\n\nclass AddStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(AddStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_email(self, email):\n user = Staff.query.filter_by(email=email.data).first()\n if user:\n raise ValidationError('Работник с такой почтой уже зарегистрирован'\n )\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError(\n 'Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n\n\nclass AddStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(AddStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_email(self, email):\n user = Staff.query.filter_by(email=email.data).first()\n if user:\n raise ValidationError('Работник с такой почтой уже зарегистрирован'\n )\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError(\n 'Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n\n\nclass AddStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(AddStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_email(self, email):\n user = Staff.query.filter_by(email=email.data).first()\n if user:\n raise ValidationError('Работник с такой почтой уже зарегистрирован'\n )\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError(\n 'Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n\n\nclass AddStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(AddStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n <function token>\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError(\n 'Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n\n\nclass AddStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n user = Staff.query.filter_by(phone=phone.data).first()\n if user:\n raise ValidationError(\n 'Работник с таким номером уже зарегистрирован')\n except Exception as error:\n raise ValidationError(error)\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n\n\nclass AddStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n\n\nclass AddDocsForm(FlaskForm):\n date = StringField('Действительно до (Формат: ДД.ММ.ГГГГ)', validators=\n [DataRequired()])\n name = StringField('Имя документа', validators=[DataRequired()])\n submit = SubmitField('Добавить')\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n\n\nclass AddDocsForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def validate_date(self, date):\n try:\n date = arrow.get(date.data, 'DD.MM.YYYY')\n if date < arrow.utcnow():\n raise ValidationError(\n 'Срок действия документа истёк, невозможно добавить недействительный документ'\n )\n except Exception as error:\n raise ValidationError(error)\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n\n\nclass AddDocsForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EditStaffForm(FlaskForm):\n first_name = StringField('Имя', validators=[DataRequired(), Length(min=\n 2, max=35)])\n second_name = StringField('Фамилия', validators=[DataRequired(), Length\n (min=2, max=35)])\n email = StringField('Email', validators=[DataRequired(), Email()])\n phone = StringField('Номер телефона', validators=[DataRequired()])\n group = SelectField('Группа ', validators=[DataRequired()], coerce=int)\n use_email = BooleanField('Email')\n use_phone = BooleanField('SMS')\n submit = SubmitField('Сохранить')\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EditStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n\n def validate_phone(self, phone):\n try:\n input_number = phonenumbers.parse(phone.data)\n if not phonenumbers.is_valid_number(input_number):\n raise ValidationError(\n 'ErrorAfterParsing: Неправильный формат номера, убедитесь что он имеет вид +71234567890 (Без пробелов между цифрами)'\n )\n except Exception as error:\n raise ValidationError(error)\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EditStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(EditStaffForm, self).__init__(*args, **kwargs)\n self.group.choices = [(group.id, group.name) for group in Groups.\n query.all()]\n <function token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EditStaffForm(FlaskForm):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,727 | d728e9a9e089427b61be220e48e550a0b21a28c7 | import random
import time
import tensorflow as tf
from utils import *
from models import GCN, MLP
import os
from scipy import sparse
from train import get_trained_gcn
from copy import copy, deepcopy
import pickle as pk
import multiprocessing as mp
import math
import sys
from sklearn.metrics import accuracy_score
from scipy.stats import entropy
import math
"""
Moving the nodes around experiment
"""
# Train the GCN
QUICK_MODE = False
w_0, w_1, A_tilde, FLAGS, old_softmax = get_trained_gcn(QUICK_MODE)
A_index = A_tilde[0][0]
A_values = A_tilde[0][1]
A_shape = A_tilde[0][2]
result_folder = "results/classification"
# Get features and labels
adj, initial_features, y_train, y_val, y_test, train_mask, val_mask, test_mask, labels = load_data(FLAGS.dataset)
full_A_tilde = preprocess_adj(adj, True)
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis=1)
def fast_localized_softmax(features, new_spot):
neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]
A_neig = full_A_tilde[neighbors_index, :]
H_out = np.matmul(np.matmul(A_neig, features), w_0)
relu_out = np.maximum(H_out, 0, H_out)
A_i_neigh = full_A_tilde[new_spot, neighbors_index]
H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)
return softmax(H2_out)
train_index = np.argwhere(train_mask).flatten()
val_index = np.argwhere(val_mask).flatten()
test_index = np.argwhere(test_mask).flatten()
features_sparse = preprocess_features(initial_features)
feature_matrix = features_sparse.todense()
number_nodes = feature_matrix.shape[0]
number_labels = labels.shape[1]
nodes_to_classify = test_index[int(sys.argv[1]):int(sys.argv[2])]
list_new_posititons = range(number_nodes)
#list_new_posititons = random.sample(list(range(number_nodes)), 30)
# nodes_to_classify = random.sample(list(test_index), 3)
j = 0
old_soft = np.zeros((2708, 7))
for i in range(number_nodes):
saved_features = deepcopy(feature_matrix[i]) # save replaced node features to do everything in place (memory)
feature_matrix[i] = np.zeros((1, 1433)) # move the node to the new position
old_soft[i] = fast_localized_softmax(feature_matrix, i)
feature_matrix[i] = saved_features
pk.dump(old_soft, open(os.path.join(result_folder, "initial_neigh.pk"), 'wb'))
start = time.time()
softmax_results = np.zeros((number_nodes, len(list_new_posititons), number_labels))
for node_index in nodes_to_classify: # TODO in parrallel copy features matrix
node_features = deepcopy(feature_matrix[node_index])
start_time = time.time()
node_true_label = int(np.argwhere(labels[node_index]))
print(str(j) + "/" + str(len(nodes_to_classify)))
# To store results
softmax_output_list = np.zeros((len(list_new_posititons), number_labels))
#classes_count = np.zeros((1, number_labels))
label_list = []
i = 0
for new_spot in list_new_posititons:
replaced_node_label = int(np.argwhere(labels[new_spot]))
label_list.append(replaced_node_label) # to keep track of the label of the replaced node
saved_features = deepcopy(
feature_matrix[new_spot]) # save replaced node features to do everything in place (memory)
feature_matrix[new_spot] = node_features # move the node to the new position
#features = sparse_to_tuple(sparse.csr_matrix(feature_matrix))
softmax_output_of_node = fast_localized_softmax(feature_matrix,
new_spot) # get new softmax output at this position
# softmax_output_of_node = old_softmax(features,new_spot)
# classes_count[0, np.argmax(softmax_output_of_node)] = classes_count[0, np.argmax(softmax_output_of_node)] + 1
softmax_output_list[i] = softmax_output_of_node # Store results
i += 1
# print("put at " + str(replaced_node_label) + " = " + str(np.argmax(softmax_output_of_node)))
feature_matrix[new_spot] = saved_features # undo changes on the feature matrix
j += 1
softmax_results[node_index] = softmax_output_list
#classes_results[node_index] = classes_count
# Store data
pk.dump(softmax_results, open(os.path.join(result_folder, "full" + sys.argv[1] + ".pk"), 'wb'))
| [
"import random\nimport time\nimport tensorflow as tf\n\nfrom utils import *\nfrom models import GCN, MLP\nimport os\nfrom scipy import sparse\nfrom train import get_trained_gcn\nfrom copy import copy, deepcopy\nimport pickle as pk\nimport multiprocessing as mp\nimport math\nimport sys\nfrom sklearn.metrics import accuracy_score\nfrom scipy.stats import entropy\nimport math\n\"\"\"\n\n Moving the nodes around experiment\n\n\"\"\"\n\n# Train the GCN\nQUICK_MODE = False\nw_0, w_1, A_tilde, FLAGS, old_softmax = get_trained_gcn(QUICK_MODE)\n\nA_index = A_tilde[0][0]\nA_values = A_tilde[0][1]\nA_shape = A_tilde[0][2]\nresult_folder = \"results/classification\"\n# Get features and labels\nadj, initial_features, y_train, y_val, y_test, train_mask, val_mask, test_mask, labels = load_data(FLAGS.dataset)\n\nfull_A_tilde = preprocess_adj(adj, True)\n\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=1)\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\ntrain_index = np.argwhere(train_mask).flatten()\nval_index = np.argwhere(val_mask).flatten()\ntest_index = np.argwhere(test_mask).flatten()\nfeatures_sparse = preprocess_features(initial_features)\nfeature_matrix = features_sparse.todense()\nnumber_nodes = feature_matrix.shape[0]\nnumber_labels = labels.shape[1]\n\nnodes_to_classify = test_index[int(sys.argv[1]):int(sys.argv[2])]\nlist_new_posititons = range(number_nodes)\n#list_new_posititons = random.sample(list(range(number_nodes)), 30)\n# nodes_to_classify = random.sample(list(test_index), 3)\nj = 0\nold_soft = np.zeros((2708, 7))\nfor i in range(number_nodes):\n saved_features = deepcopy(feature_matrix[i]) # save replaced node features to do everything in place (memory)\n feature_matrix[i] = np.zeros((1, 1433)) # move the node to the new position\n old_soft[i] = fast_localized_softmax(feature_matrix, i)\n feature_matrix[i] = saved_features\npk.dump(old_soft, open(os.path.join(result_folder, \"initial_neigh.pk\"), 'wb'))\n\nstart = time.time()\n\nsoftmax_results = np.zeros((number_nodes, len(list_new_posititons), number_labels))\n\nfor node_index in nodes_to_classify: # TODO in parrallel copy features matrix\n\n node_features = deepcopy(feature_matrix[node_index])\n start_time = time.time()\n\n node_true_label = int(np.argwhere(labels[node_index]))\n print(str(j) + \"/\" + str(len(nodes_to_classify)))\n # To store results\n softmax_output_list = np.zeros((len(list_new_posititons), number_labels))\n #classes_count = np.zeros((1, number_labels))\n label_list = []\n i = 0\n\n for new_spot in list_new_posititons:\n\n replaced_node_label = int(np.argwhere(labels[new_spot]))\n label_list.append(replaced_node_label) # to keep track of the label of the replaced node\n\n saved_features = deepcopy(\n feature_matrix[new_spot]) # save replaced node features to do everything in place (memory)\n\n feature_matrix[new_spot] = node_features # move the node to the new position\n\n #features = sparse_to_tuple(sparse.csr_matrix(feature_matrix))\n softmax_output_of_node = fast_localized_softmax(feature_matrix,\n new_spot) # get new softmax output at this position\n # softmax_output_of_node = old_softmax(features,new_spot)\n\n # classes_count[0, np.argmax(softmax_output_of_node)] = classes_count[0, np.argmax(softmax_output_of_node)] + 1\n softmax_output_list[i] = softmax_output_of_node # Store results\n i += 1\n # print(\"put at \" + str(replaced_node_label) + \" = \" + str(np.argmax(softmax_output_of_node)))\n\n feature_matrix[new_spot] = saved_features # undo changes on the feature matrix\n j += 1\n softmax_results[node_index] = softmax_output_list\n #classes_results[node_index] = classes_count\n\n# Store data\npk.dump(softmax_results, open(os.path.join(result_folder, \"full\" + sys.argv[1] + \".pk\"), 'wb'))\n",
"import random\nimport time\nimport tensorflow as tf\nfrom utils import *\nfrom models import GCN, MLP\nimport os\nfrom scipy import sparse\nfrom train import get_trained_gcn\nfrom copy import copy, deepcopy\nimport pickle as pk\nimport multiprocessing as mp\nimport math\nimport sys\nfrom sklearn.metrics import accuracy_score\nfrom scipy.stats import entropy\nimport math\n<docstring token>\nQUICK_MODE = False\nw_0, w_1, A_tilde, FLAGS, old_softmax = get_trained_gcn(QUICK_MODE)\nA_index = A_tilde[0][0]\nA_values = A_tilde[0][1]\nA_shape = A_tilde[0][2]\nresult_folder = 'results/classification'\n(adj, initial_features, y_train, y_val, y_test, train_mask, val_mask,\n test_mask, labels) = load_data(FLAGS.dataset)\nfull_A_tilde = preprocess_adj(adj, True)\n\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=1)\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\ntrain_index = np.argwhere(train_mask).flatten()\nval_index = np.argwhere(val_mask).flatten()\ntest_index = np.argwhere(test_mask).flatten()\nfeatures_sparse = preprocess_features(initial_features)\nfeature_matrix = features_sparse.todense()\nnumber_nodes = feature_matrix.shape[0]\nnumber_labels = labels.shape[1]\nnodes_to_classify = test_index[int(sys.argv[1]):int(sys.argv[2])]\nlist_new_posititons = range(number_nodes)\nj = 0\nold_soft = np.zeros((2708, 7))\nfor i in range(number_nodes):\n saved_features = deepcopy(feature_matrix[i])\n feature_matrix[i] = np.zeros((1, 1433))\n old_soft[i] = fast_localized_softmax(feature_matrix, i)\n feature_matrix[i] = saved_features\npk.dump(old_soft, open(os.path.join(result_folder, 'initial_neigh.pk'), 'wb'))\nstart = time.time()\nsoftmax_results = np.zeros((number_nodes, len(list_new_posititons),\n number_labels))\nfor node_index in nodes_to_classify:\n node_features = deepcopy(feature_matrix[node_index])\n start_time = time.time()\n node_true_label = int(np.argwhere(labels[node_index]))\n print(str(j) + '/' + str(len(nodes_to_classify)))\n softmax_output_list = np.zeros((len(list_new_posititons), number_labels))\n label_list = []\n i = 0\n for new_spot in list_new_posititons:\n replaced_node_label = int(np.argwhere(labels[new_spot]))\n label_list.append(replaced_node_label)\n saved_features = deepcopy(feature_matrix[new_spot])\n feature_matrix[new_spot] = node_features\n softmax_output_of_node = fast_localized_softmax(feature_matrix,\n new_spot)\n softmax_output_list[i] = softmax_output_of_node\n i += 1\n feature_matrix[new_spot] = saved_features\n j += 1\n softmax_results[node_index] = softmax_output_list\npk.dump(softmax_results, open(os.path.join(result_folder, 'full' + sys.argv\n [1] + '.pk'), 'wb'))\n",
"<import token>\n<docstring token>\nQUICK_MODE = False\nw_0, w_1, A_tilde, FLAGS, old_softmax = get_trained_gcn(QUICK_MODE)\nA_index = A_tilde[0][0]\nA_values = A_tilde[0][1]\nA_shape = A_tilde[0][2]\nresult_folder = 'results/classification'\n(adj, initial_features, y_train, y_val, y_test, train_mask, val_mask,\n test_mask, labels) = load_data(FLAGS.dataset)\nfull_A_tilde = preprocess_adj(adj, True)\n\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=1)\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\ntrain_index = np.argwhere(train_mask).flatten()\nval_index = np.argwhere(val_mask).flatten()\ntest_index = np.argwhere(test_mask).flatten()\nfeatures_sparse = preprocess_features(initial_features)\nfeature_matrix = features_sparse.todense()\nnumber_nodes = feature_matrix.shape[0]\nnumber_labels = labels.shape[1]\nnodes_to_classify = test_index[int(sys.argv[1]):int(sys.argv[2])]\nlist_new_posititons = range(number_nodes)\nj = 0\nold_soft = np.zeros((2708, 7))\nfor i in range(number_nodes):\n saved_features = deepcopy(feature_matrix[i])\n feature_matrix[i] = np.zeros((1, 1433))\n old_soft[i] = fast_localized_softmax(feature_matrix, i)\n feature_matrix[i] = saved_features\npk.dump(old_soft, open(os.path.join(result_folder, 'initial_neigh.pk'), 'wb'))\nstart = time.time()\nsoftmax_results = np.zeros((number_nodes, len(list_new_posititons),\n number_labels))\nfor node_index in nodes_to_classify:\n node_features = deepcopy(feature_matrix[node_index])\n start_time = time.time()\n node_true_label = int(np.argwhere(labels[node_index]))\n print(str(j) + '/' + str(len(nodes_to_classify)))\n softmax_output_list = np.zeros((len(list_new_posititons), number_labels))\n label_list = []\n i = 0\n for new_spot in list_new_posititons:\n replaced_node_label = int(np.argwhere(labels[new_spot]))\n label_list.append(replaced_node_label)\n saved_features = deepcopy(feature_matrix[new_spot])\n feature_matrix[new_spot] = node_features\n softmax_output_of_node = fast_localized_softmax(feature_matrix,\n new_spot)\n softmax_output_list[i] = softmax_output_of_node\n i += 1\n feature_matrix[new_spot] = saved_features\n j += 1\n softmax_results[node_index] = softmax_output_list\npk.dump(softmax_results, open(os.path.join(result_folder, 'full' + sys.argv\n [1] + '.pk'), 'wb'))\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=1)\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\n<assignment token>\nfor i in range(number_nodes):\n saved_features = deepcopy(feature_matrix[i])\n feature_matrix[i] = np.zeros((1, 1433))\n old_soft[i] = fast_localized_softmax(feature_matrix, i)\n feature_matrix[i] = saved_features\npk.dump(old_soft, open(os.path.join(result_folder, 'initial_neigh.pk'), 'wb'))\n<assignment token>\nfor node_index in nodes_to_classify:\n node_features = deepcopy(feature_matrix[node_index])\n start_time = time.time()\n node_true_label = int(np.argwhere(labels[node_index]))\n print(str(j) + '/' + str(len(nodes_to_classify)))\n softmax_output_list = np.zeros((len(list_new_posititons), number_labels))\n label_list = []\n i = 0\n for new_spot in list_new_posititons:\n replaced_node_label = int(np.argwhere(labels[new_spot]))\n label_list.append(replaced_node_label)\n saved_features = deepcopy(feature_matrix[new_spot])\n feature_matrix[new_spot] = node_features\n softmax_output_of_node = fast_localized_softmax(feature_matrix,\n new_spot)\n softmax_output_list[i] = softmax_output_of_node\n i += 1\n feature_matrix[new_spot] = saved_features\n j += 1\n softmax_results[node_index] = softmax_output_list\npk.dump(softmax_results, open(os.path.join(result_folder, 'full' + sys.argv\n [1] + '.pk'), 'wb'))\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=1)\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n\n\ndef fast_localized_softmax(features, new_spot):\n neighbors_index = np.argwhere(full_A_tilde[new_spot, :])[:, 1]\n A_neig = full_A_tilde[neighbors_index, :]\n H_out = np.matmul(np.matmul(A_neig, features), w_0)\n relu_out = np.maximum(H_out, 0, H_out)\n A_i_neigh = full_A_tilde[new_spot, neighbors_index]\n H2_out = np.matmul(np.matmul(A_i_neigh, relu_out), w_1)\n return softmax(H2_out)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,728 | c0746dd762c8907fa455bf079fbfe4a042d2c91e | format='python' # jika di vps pakai python3
nama_script='telefullv3.py' # sesuaikan nama script
currency='zec' # jenis currency yang ingin di japankan
jumlah_akun=5 #jumlah akun per jeda jangan terlalu banyak agar perangkat tidak panas terutama jika ram kecil
jeda_perakun=1200 # hitungan detik
jeda_reload_ke_awal=12000 # hitungan detik
kembali_ke='sh run.sh'
# bagian bawah ini tidak perlu di edit
###
import os
from time import *
if os.path.exists('multiakunzec.sh'):os.remove('multiakunzec.sh')
if os.path.exists('multi.txt'):os.remove('multi.txt')
o=0
ar = os.listdir('session/')
for phone in ar:
if phone.endswith(".session-journal"):
os.remove('session/'+phone)
else:
nomor = phone.replace('.session','')
try:
o+=1
print(f'[{str(o)}]'+nomor)
with open('multi.txt','a+') as mu:
mu.write(nomor+'\n')
except Exception as e:
print(e)
merah='\\033[1;31m'
cyan='\\033[1;36m'
insert = f"""
x={jeda_perakun}
while [ $x -gt 0 ]
do
sleep 20s
clear
echo "{cyan}"""
insert2=f"""ke {jumlah_akun} akun lagi sisa Waktu anda $x Detik"
x=$(( $x - 20 ))
done
"""
bottom = f"""
x={jeda_reload_ke_awal}
while [ $x -gt 0 ]
do
sleep 20s
clear
echo " \\033[1;36m lanjut ke Multi clickbot sisa Waktu anda $x Detik"
x=$(( $x - 20 ))
done
sh run.sh
done"""
head = f"""#!/bin/bash
clear
echo "{merah} Multi Akun "
echo "{merah} Bersiaplah kita akan mulai "
sleep 2s
"""
neo= open("multi.txt","r")
grp=neo.read().splitlines()
ju=len(grp)
print(f'\n\ntotal akun : {ju}')
with open('multiakunzec.sh','a+') as mau:
mau.write(head)
ur=0
i=0
k=0
nom=0
kadal=jumlah_akun-1
sleep(2)
for i in range(ju):
k+=1
try:
dia=grp[i]
if(ur==kadal):
with open('multiakunzec.sh','a+') as mau:
mau.write(f'{format} {nama_script} {dia} {currency}\n')
ur+=1
else:
if(ju==k):
with open('multiakunzec.sh','a+') as mau:
mau.write(f'{format} {nama_script} {dia} {currency}\n')
ur+=1
else:
with open('multiakunzec.sh','a+') as mau:
mau.write(f'{format} {nama_script} {dia} {currency} &\n')
ur+=1
except Exception as e:
print(e)
pass
if (ur==jumlah_akun):
if (k==ju):
pass
else:
nom+=1
with open('multiakunzec.sh','a+') as mau:
mau.write(f'{insert} [ {str(nom)} ] {insert2}')
ur=0
with open('multiakunzec.sh','a+') as mau:
mau.write(bottom)
mau.close()
os.remove('multi.txt')
exit()
| [
"format='python' # jika di vps pakai python3\nnama_script='telefullv3.py' # sesuaikan nama script\ncurrency='zec' # jenis currency yang ingin di japankan\njumlah_akun=5 #jumlah akun per jeda jangan terlalu banyak agar perangkat tidak panas terutama jika ram kecil\njeda_perakun=1200 # hitungan detik\njeda_reload_ke_awal=12000 # hitungan detik\nkembali_ke='sh run.sh'\n\n# bagian bawah ini tidak perlu di edit\n###\nimport os\nfrom time import *\nif os.path.exists('multiakunzec.sh'):os.remove('multiakunzec.sh')\nif os.path.exists('multi.txt'):os.remove('multi.txt')\no=0\nar = os.listdir('session/')\nfor phone in ar:\n if phone.endswith(\".session-journal\"):\n os.remove('session/'+phone)\n else:\n nomor = phone.replace('.session','')\n try:\n o+=1\n print(f'[{str(o)}]'+nomor)\n with open('multi.txt','a+') as mu:\n mu.write(nomor+'\\n')\n except Exception as e:\n print(e)\nmerah='\\\\033[1;31m'\ncyan='\\\\033[1;36m'\ninsert = f\"\"\"\nx={jeda_perakun}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \"{cyan}\"\"\"\ninsert2=f\"\"\"ke {jumlah_akun} akun lagi sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\n\n\"\"\"\nbottom = f\"\"\"\nx={jeda_reload_ke_awal}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \" \\\\033[1;36m lanjut ke Multi clickbot sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\nsh run.sh\ndone\"\"\"\nhead = f\"\"\"#!/bin/bash\nclear\necho \"{merah} Multi Akun \"\necho \"{merah} Bersiaplah kita akan mulai \"\nsleep 2s\n\n\"\"\"\nneo= open(\"multi.txt\",\"r\")\ngrp=neo.read().splitlines()\nju=len(grp)\nprint(f'\\n\\ntotal akun : {ju}')\nwith open('multiakunzec.sh','a+') as mau:\n mau.write(head)\nur=0\ni=0\nk=0\nnom=0\nkadal=jumlah_akun-1\nsleep(2)\nfor i in range(ju):\n k+=1\n try:\n dia=grp[i]\n if(ur==kadal):\n with open('multiakunzec.sh','a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur+=1\n else:\n if(ju==k):\n with open('multiakunzec.sh','a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur+=1\n else:\n with open('multiakunzec.sh','a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency} &\\n')\n ur+=1 \n except Exception as e:\n print(e)\n pass\n if (ur==jumlah_akun):\n if (k==ju):\n pass\n else:\n nom+=1\n with open('multiakunzec.sh','a+') as mau:\n mau.write(f'{insert} [ {str(nom)} ] {insert2}')\n ur=0\nwith open('multiakunzec.sh','a+') as mau:\n mau.write(bottom)\n mau.close()\nos.remove('multi.txt')\nexit()\n\n\n",
"format = 'python'\nnama_script = 'telefullv3.py'\ncurrency = 'zec'\njumlah_akun = 5\njeda_perakun = 1200\njeda_reload_ke_awal = 12000\nkembali_ke = 'sh run.sh'\nimport os\nfrom time import *\nif os.path.exists('multiakunzec.sh'):\n os.remove('multiakunzec.sh')\nif os.path.exists('multi.txt'):\n os.remove('multi.txt')\no = 0\nar = os.listdir('session/')\nfor phone in ar:\n if phone.endswith('.session-journal'):\n os.remove('session/' + phone)\n else:\n nomor = phone.replace('.session', '')\n try:\n o += 1\n print(f'[{str(o)}]' + nomor)\n with open('multi.txt', 'a+') as mu:\n mu.write(nomor + '\\n')\n except Exception as e:\n print(e)\nmerah = '\\\\033[1;31m'\ncyan = '\\\\033[1;36m'\ninsert = f\"\"\"\nx={jeda_perakun}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \"{cyan}\"\"\"\ninsert2 = f\"\"\"ke {jumlah_akun} akun lagi sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\n\n\"\"\"\nbottom = f\"\"\"\nx={jeda_reload_ke_awal}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \" \\\\033[1;36m lanjut ke Multi clickbot sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\nsh run.sh\ndone\"\"\"\nhead = f\"\"\"#!/bin/bash\nclear\necho \"{merah} Multi Akun \"\necho \"{merah} Bersiaplah kita akan mulai \"\nsleep 2s\n\n\"\"\"\nneo = open('multi.txt', 'r')\ngrp = neo.read().splitlines()\nju = len(grp)\nprint(f\"\"\"\n\ntotal akun : {ju}\"\"\")\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(head)\nur = 0\ni = 0\nk = 0\nnom = 0\nkadal = jumlah_akun - 1\nsleep(2)\nfor i in range(ju):\n k += 1\n try:\n dia = grp[i]\n if ur == kadal:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n elif ju == k:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n else:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency} &\\n')\n ur += 1\n except Exception as e:\n print(e)\n pass\n if ur == jumlah_akun:\n if k == ju:\n pass\n else:\n nom += 1\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{insert} [ {str(nom)} ] {insert2}')\n ur = 0\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(bottom)\n mau.close()\nos.remove('multi.txt')\nexit()\n",
"format = 'python'\nnama_script = 'telefullv3.py'\ncurrency = 'zec'\njumlah_akun = 5\njeda_perakun = 1200\njeda_reload_ke_awal = 12000\nkembali_ke = 'sh run.sh'\n<import token>\nif os.path.exists('multiakunzec.sh'):\n os.remove('multiakunzec.sh')\nif os.path.exists('multi.txt'):\n os.remove('multi.txt')\no = 0\nar = os.listdir('session/')\nfor phone in ar:\n if phone.endswith('.session-journal'):\n os.remove('session/' + phone)\n else:\n nomor = phone.replace('.session', '')\n try:\n o += 1\n print(f'[{str(o)}]' + nomor)\n with open('multi.txt', 'a+') as mu:\n mu.write(nomor + '\\n')\n except Exception as e:\n print(e)\nmerah = '\\\\033[1;31m'\ncyan = '\\\\033[1;36m'\ninsert = f\"\"\"\nx={jeda_perakun}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \"{cyan}\"\"\"\ninsert2 = f\"\"\"ke {jumlah_akun} akun lagi sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\n\n\"\"\"\nbottom = f\"\"\"\nx={jeda_reload_ke_awal}\nwhile [ $x -gt 0 ]\ndo\nsleep 20s\nclear\necho \" \\\\033[1;36m lanjut ke Multi clickbot sisa Waktu anda $x Detik\"\nx=$(( $x - 20 ))\ndone\nsh run.sh\ndone\"\"\"\nhead = f\"\"\"#!/bin/bash\nclear\necho \"{merah} Multi Akun \"\necho \"{merah} Bersiaplah kita akan mulai \"\nsleep 2s\n\n\"\"\"\nneo = open('multi.txt', 'r')\ngrp = neo.read().splitlines()\nju = len(grp)\nprint(f\"\"\"\n\ntotal akun : {ju}\"\"\")\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(head)\nur = 0\ni = 0\nk = 0\nnom = 0\nkadal = jumlah_akun - 1\nsleep(2)\nfor i in range(ju):\n k += 1\n try:\n dia = grp[i]\n if ur == kadal:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n elif ju == k:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n else:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency} &\\n')\n ur += 1\n except Exception as e:\n print(e)\n pass\n if ur == jumlah_akun:\n if k == ju:\n pass\n else:\n nom += 1\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{insert} [ {str(nom)} ] {insert2}')\n ur = 0\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(bottom)\n mau.close()\nos.remove('multi.txt')\nexit()\n",
"<assignment token>\n<import token>\nif os.path.exists('multiakunzec.sh'):\n os.remove('multiakunzec.sh')\nif os.path.exists('multi.txt'):\n os.remove('multi.txt')\n<assignment token>\nfor phone in ar:\n if phone.endswith('.session-journal'):\n os.remove('session/' + phone)\n else:\n nomor = phone.replace('.session', '')\n try:\n o += 1\n print(f'[{str(o)}]' + nomor)\n with open('multi.txt', 'a+') as mu:\n mu.write(nomor + '\\n')\n except Exception as e:\n print(e)\n<assignment token>\nprint(f\"\"\"\n\ntotal akun : {ju}\"\"\")\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(head)\n<assignment token>\nsleep(2)\nfor i in range(ju):\n k += 1\n try:\n dia = grp[i]\n if ur == kadal:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n elif ju == k:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency}\\n')\n ur += 1\n else:\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{format} {nama_script} {dia} {currency} &\\n')\n ur += 1\n except Exception as e:\n print(e)\n pass\n if ur == jumlah_akun:\n if k == ju:\n pass\n else:\n nom += 1\n with open('multiakunzec.sh', 'a+') as mau:\n mau.write(f'{insert} [ {str(nom)} ] {insert2}')\n ur = 0\nwith open('multiakunzec.sh', 'a+') as mau:\n mau.write(bottom)\n mau.close()\nos.remove('multi.txt')\nexit()\n",
"<assignment token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,729 | f21bbc9baad9e50d6154362458485bd35ddeaa86 | class Solution:
def countTriplets(self, arr: List[int]) -> int:
xors = [None] * len(arr)
xors[0] = arr[0]
xorsToIndices = {0: [-1]}
for i in range(len(arr)):
newXor = None
if i == 0:
newXor = arr[0]
else:
newXor = xors[i - 1] ^ arr[i]
xors[i] = newXor
if newXor not in xorsToIndices: xorsToIndices[newXor] = []
xorsToIndices[newXor].append(i)
# print(xors)
# print(xorsToIndices)
total_counts = 0
for xorVal, indices in xorsToIndices.items():
total_counts += self.getComboCounts(indices)
return total_counts
def getComboCounts(self, indices: List[int]) -> int:
if len(indices) == 1: return 0
count = 0
for i in range(len(indices) - 1):
for j in range(i + 1, len(indices)):
iIndex = indices[i]
jIndex = indices[j]
count += jIndex - iIndex - 1
return count
| [
"class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n xors = [None] * len(arr)\n xors[0] = arr[0]\n\n xorsToIndices = {0: [-1]}\n for i in range(len(arr)):\n newXor = None\n if i == 0:\n newXor = arr[0]\n else:\n newXor = xors[i - 1] ^ arr[i]\n xors[i] = newXor\n if newXor not in xorsToIndices: xorsToIndices[newXor] = []\n xorsToIndices[newXor].append(i)\n \n # print(xors)\n # print(xorsToIndices)\n\n total_counts = 0\n for xorVal, indices in xorsToIndices.items():\n total_counts += self.getComboCounts(indices)\n\n return total_counts\n def getComboCounts(self, indices: List[int]) -> int:\n if len(indices) == 1: return 0\n count = 0\n for i in range(len(indices) - 1):\n for j in range(i + 1, len(indices)):\n iIndex = indices[i]\n jIndex = indices[j]\n count += jIndex - iIndex - 1\n return count\n\n",
"class Solution:\n\n def countTriplets(self, arr: List[int]) ->int:\n xors = [None] * len(arr)\n xors[0] = arr[0]\n xorsToIndices = {(0): [-1]}\n for i in range(len(arr)):\n newXor = None\n if i == 0:\n newXor = arr[0]\n else:\n newXor = xors[i - 1] ^ arr[i]\n xors[i] = newXor\n if newXor not in xorsToIndices:\n xorsToIndices[newXor] = []\n xorsToIndices[newXor].append(i)\n total_counts = 0\n for xorVal, indices in xorsToIndices.items():\n total_counts += self.getComboCounts(indices)\n return total_counts\n\n def getComboCounts(self, indices: List[int]) ->int:\n if len(indices) == 1:\n return 0\n count = 0\n for i in range(len(indices) - 1):\n for j in range(i + 1, len(indices)):\n iIndex = indices[i]\n jIndex = indices[j]\n count += jIndex - iIndex - 1\n return count\n",
"class Solution:\n <function token>\n\n def getComboCounts(self, indices: List[int]) ->int:\n if len(indices) == 1:\n return 0\n count = 0\n for i in range(len(indices) - 1):\n for j in range(i + 1, len(indices)):\n iIndex = indices[i]\n jIndex = indices[j]\n count += jIndex - iIndex - 1\n return count\n",
"class Solution:\n <function token>\n <function token>\n",
"<class token>\n"
] | false |
99,730 | 4870f774a597974fdf1b76cb870b431ada64cd61 | # import unittest
# from selenium import webdriver
# from page.home.login_page import LoginPage
# from selenium.webdriver.common.by import By
#
#
# class LoginTests(unittest.TestCase):
#
# baseUrl = "https://learn.letskodeit.com/"
# driver = webdriver.Firefox()
# driver.maximize_window()
# driver.get(baseUrl)
# driver.implicitly_wait(10)
#
# lp = LoginPage(driver)
# lp.login('[email protected]', 'abcabc')
import unittest
from page.home.login_page import LoginPage
from utilities.teststatus import TestStatus
import pytest
from time import sleep
@pytest.mark.usefixtures("OneTimeSetUP", "setUp")
class LoginTests(unittest.TestCase):
@pytest.fixture(autouse=True)
def classSetUp(self, OneTimeSetUP):
self.lp = LoginPage(self.driver)
self.tc = TestStatus(self.driver)
@pytest.mark.run(order=2)
def test_ValidLogin(self):
self.driver.implicitly_wait(5)
self.lp.login('[email protected]', 'abcabc')
result1 = self.lp.verifyLoginTitle()
# assert result1 == True
self.tc.mark(result1, " Title is not correct")
result2 = self.lp.verifyLoginSuccessful()
# assert result2 == True
self.tc.markFinal("test_ValidLogin", result2, " Element not present here")
@pytest.mark.run(order=1)
def test_invalidLogin(self):
self.driver.implicitly_wait(10)
# INVALID DATA OPTIONS
self.lp.logout()
sleep(3)
self.lp.login('test.email@com', 'qwe')
#self.lp.login()
#self.lp.login(username='test.email@com')
#self.lp.login(userpassword='abcabc')
result = self.lp.verifyLiginFailed()
assert result == True
| [
"# import unittest\n# from selenium import webdriver\n# from page.home.login_page import LoginPage\n# from selenium.webdriver.common.by import By\n#\n#\n# class LoginTests(unittest.TestCase):\n#\n# baseUrl = \"https://learn.letskodeit.com/\"\n# driver = webdriver.Firefox()\n# driver.maximize_window()\n# driver.get(baseUrl)\n# driver.implicitly_wait(10)\n#\n# lp = LoginPage(driver)\n# lp.login('[email protected]', 'abcabc')\n\n\nimport unittest\nfrom page.home.login_page import LoginPage\nfrom utilities.teststatus import TestStatus\nimport pytest\nfrom time import sleep\n\n\[email protected](\"OneTimeSetUP\", \"setUp\")\nclass LoginTests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetUp(self, OneTimeSetUP):\n self.lp = LoginPage(self.driver)\n self.tc = TestStatus(self.driver)\n\n\n @pytest.mark.run(order=2)\n def test_ValidLogin(self):\n\n self.driver.implicitly_wait(5)\n\n self.lp.login('[email protected]', 'abcabc')\n\n result1 = self.lp.verifyLoginTitle()\n # assert result1 == True\n self.tc.mark(result1, \" Title is not correct\")\n\n\n result2 = self.lp.verifyLoginSuccessful()\n # assert result2 == True\n self.tc.markFinal(\"test_ValidLogin\", result2, \" Element not present here\")\n\n\n\n @pytest.mark.run(order=1)\n def test_invalidLogin(self):\n\n self.driver.implicitly_wait(10)\n\n # INVALID DATA OPTIONS\n self.lp.logout()\n sleep(3)\n\n self.lp.login('test.email@com', 'qwe')\n\n #self.lp.login()\n #self.lp.login(username='test.email@com')\n #self.lp.login(userpassword='abcabc')\n\n result = self.lp.verifyLiginFailed()\n assert result == True\n\n\n\n\n\n\n\n\n\n\n\n",
"import unittest\nfrom page.home.login_page import LoginPage\nfrom utilities.teststatus import TestStatus\nimport pytest\nfrom time import sleep\n\n\[email protected]('OneTimeSetUP', 'setUp')\nclass LoginTests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetUp(self, OneTimeSetUP):\n self.lp = LoginPage(self.driver)\n self.tc = TestStatus(self.driver)\n\n @pytest.mark.run(order=2)\n def test_ValidLogin(self):\n self.driver.implicitly_wait(5)\n self.lp.login('[email protected]', 'abcabc')\n result1 = self.lp.verifyLoginTitle()\n self.tc.mark(result1, ' Title is not correct')\n result2 = self.lp.verifyLoginSuccessful()\n self.tc.markFinal('test_ValidLogin', result2,\n ' Element not present here')\n\n @pytest.mark.run(order=1)\n def test_invalidLogin(self):\n self.driver.implicitly_wait(10)\n self.lp.logout()\n sleep(3)\n self.lp.login('test.email@com', 'qwe')\n result = self.lp.verifyLiginFailed()\n assert result == True\n",
"<import token>\n\n\[email protected]('OneTimeSetUP', 'setUp')\nclass LoginTests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetUp(self, OneTimeSetUP):\n self.lp = LoginPage(self.driver)\n self.tc = TestStatus(self.driver)\n\n @pytest.mark.run(order=2)\n def test_ValidLogin(self):\n self.driver.implicitly_wait(5)\n self.lp.login('[email protected]', 'abcabc')\n result1 = self.lp.verifyLoginTitle()\n self.tc.mark(result1, ' Title is not correct')\n result2 = self.lp.verifyLoginSuccessful()\n self.tc.markFinal('test_ValidLogin', result2,\n ' Element not present here')\n\n @pytest.mark.run(order=1)\n def test_invalidLogin(self):\n self.driver.implicitly_wait(10)\n self.lp.logout()\n sleep(3)\n self.lp.login('test.email@com', 'qwe')\n result = self.lp.verifyLiginFailed()\n assert result == True\n",
"<import token>\n\n\[email protected]('OneTimeSetUP', 'setUp')\nclass LoginTests(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetUp(self, OneTimeSetUP):\n self.lp = LoginPage(self.driver)\n self.tc = TestStatus(self.driver)\n\n @pytest.mark.run(order=2)\n def test_ValidLogin(self):\n self.driver.implicitly_wait(5)\n self.lp.login('[email protected]', 'abcabc')\n result1 = self.lp.verifyLoginTitle()\n self.tc.mark(result1, ' Title is not correct')\n result2 = self.lp.verifyLoginSuccessful()\n self.tc.markFinal('test_ValidLogin', result2,\n ' Element not present here')\n <function token>\n",
"<import token>\n\n\[email protected]('OneTimeSetUP', 'setUp')\nclass LoginTests(unittest.TestCase):\n <function token>\n\n @pytest.mark.run(order=2)\n def test_ValidLogin(self):\n self.driver.implicitly_wait(5)\n self.lp.login('[email protected]', 'abcabc')\n result1 = self.lp.verifyLoginTitle()\n self.tc.mark(result1, ' Title is not correct')\n result2 = self.lp.verifyLoginSuccessful()\n self.tc.markFinal('test_ValidLogin', result2,\n ' Element not present here')\n <function token>\n",
"<import token>\n\n\[email protected]('OneTimeSetUP', 'setUp')\nclass LoginTests(unittest.TestCase):\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,731 | a02e6f360413799be0083419c4637759823bf8a5 | str=raw_input()
print str
| [
"str=raw_input()\nprint str\n"
] | true |
99,732 | 937cc7f96d180e2e9872467d13ccef6c766cac0d | #!/usr/bin/python
from ext_cloud import get_ext_cloud
import warnings
warnings.filterwarnings("ignore")
import sys
cloud_obj = get_ext_cloud("openstack")
instances = cloud_obj.compute.get_instances_by_error_state()
if len(instances) == 0:
sys.exit(0)
msg = '{} instance(s) in ERROR state.[Instance id: name] '.format(len(instances))
for instance in instances:
msg += '[' + instance.id + ':' + instance.name + '] '
print msg
sys.exit(1)
| [
"#!/usr/bin/python\nfrom ext_cloud import get_ext_cloud\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport sys\ncloud_obj = get_ext_cloud(\"openstack\")\n\ninstances = cloud_obj.compute.get_instances_by_error_state()\n\nif len(instances) == 0:\n\tsys.exit(0)\n\nmsg = '{} instance(s) in ERROR state.[Instance id: name] '.format(len(instances))\n\nfor instance in instances:\n\tmsg += '[' + instance.id + ':' + instance.name + '] '\t\nprint msg\nsys.exit(1)\n"
] | true |
99,733 | 3634b9e7569af5d7afc5aa9e0e726559a8d13073 | import os
import random
import numpy as np
import cv2
import cv2.aruco as aruco
# Get dictionary by name
def get_dictionary(DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=False):
dictionary = []
if DICT_4X4_50:
dictionary.append([aruco.DICT_4X4_50, 50])
if DICT_4X4_100:
dictionary.append([aruco.DICT_4X4_100, 100])
if DICT_4X4_250:
dictionary.append([aruco.DICT_4X4_250, 250])
if DICT_4X4_1000:
dictionary.append([aruco.DICT_4X4_1000, 1000])
if DICT_5X5_50:
dictionary.append([aruco.DICT_5X5_50, 50])
if DICT_5X5_100:
dictionary.append([aruco.DICT_5X5_100, 100])
if DICT_5X5_250:
dictionary.append([aruco.DICT_5X5_250, 250])
if DICT_5X5_1000:
dictionary.append([aruco.DICT_5X5_1000, 1000])
if DICT_6X6_50:
dictionary.append([aruco.DICT_6X6_50, 50])
if DICT_6X6_100:
dictionary.append([aruco.DICT_6X6_100, 100])
if DICT_6X6_250:
dictionary.append([aruco.DICT_6X6_250, 250])
if DICT_6X6_1000:
dictionary.append([aruco.DICT_6X6_1000, 1000])
if DICT_7X7_50:
dictionary.append([aruco.DICT_7X7_50, 50])
if DICT_7X7_100:
dictionary.append([aruco.DICT_7X7_100, 100])
if DICT_7X7_250:
dictionary.append([aruco.DICT_7X7_250, 250])
if DICT_7X7_1000:
dictionary.append([aruco.DICT_7X7_1000, 1000])
if DICT_ARUCO_ORIGINAL:
dictionary.append([aruco.DICT_ARUCO_ORIGINAL, 1024])
if DICT_APRILTAG_16h5:
dictionary.append([aruco.DICT_APRILTAG_16h5, 30])
if DICT_APRILTAG_25h9:
dictionary.append([aruco.DICT_APRILTAG_25h9, 35])
if DICT_APRILTAG_36h10:
dictionary.append([aruco.DICT_APRILTAG_36h10, 2320])
if DICT_APRILTAG_36h11:
dictionary.append([aruco.DICT_APRILTAG_36h11, 587])
return dictionary
# Generate a random marker with random id
def get_random_marker(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):
# Create dictionary list with all enabled families
dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)
dictionary = random.choice(dictionary)
# Generate the marker with a white border
marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]), random.randint(0, dictionary[1]-1), int(shape[0] / 2) - 1)
marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=255)
# Convert to bgr to have three channels
marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)
# Change the marker color with random ofset
marker[np.where((marker==[255,255,255]).all(axis=2))] = random.randint(245, 255)
marker[np.where((marker==[0,0,0]).all(axis=2))] = random.randint(0, 15)
return marker
# Put the marker randomly on the background
def generate_sample_with_given_background(background, marker):
# Resize the marker randomly
marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9)/10)),
int(marker.shape[0] * (random.randint(3, 9)/10))), interpolation=cv2.INTER_AREA)
height, width, _ = marker.shape
# Make a random perspective transformation
marker = cv2.warpPerspective(marker,
cv2.getPerspectiveTransform(
np.float32([[0, 0], [width, 0], [0, height], [width, height]]),
np.float32([[(random.randint(0,10)/100)*width, (random.randint(0,10)/100)*height],
[width-((random.randint(0,10)/100)*width), (random.randint(0,10)/100)*height],
[(random.randint(0,10)/100)*width, height-((random.randint(0,10)/100)*height)],
[width-((random.randint(0,10)/100)*width), height-((random.randint(0,10)/100)*height)]])
),
(width, height), borderValue=(1, 1, 1))
# Rotate randomly
angle_rot = random.randint(0, 360)
marker = cv2.warpAffine(marker,
cv2.getRotationMatrix2D((width/2, height/2), np.random.uniform(angle_rot)-angle_rot/2,1),
(width, height), borderValue=(1, 1, 1))
# Put the marker on a new image with transparent background equal to one
marker2 = np.ones(shape=background.shape).astype(np.uint8)
x = random.randint(0, background.shape[1] - marker.shape[1])
y = random.randint(0, background.shape[0] - marker.shape[0])
marker2[y:y+marker.shape[0], x:x+marker.shape[1]] = marker[0:marker.shape[0], 0:marker.shape[1]]
# Generate the ground through mask
mask = np.zeros(shape=(background.shape[0], background.shape[1], background.shape[2])).astype(np.uint8)
mask[np.where((marker2==[1,1,1]).all(axis=2))] = 255
mask = 255 - mask
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
# Put the non transparent background (marker) on the background image
idx = (mask == 255)
background[idx]= marker2[idx]
# Create random illuminations
illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)
shape = background.shape
for _ in range(random.randint(0, 5)):
randomNo = random.randint(5,80)
cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.randint(1, shape[0])),
int((shape[1] + shape[0]) * (random.randint(1, 20)/100)),
(randomNo,randomNo,randomNo), -1)
for _ in range(random.randint(0, 9)):
randomNo = random.randint(5,80)
cv2.line(illuminationMask, (random.randint(1, shape[1]), random.randint(1, shape[0])),
(random.randint(1, shape[1]), random.randint(1, shape[0])),
(randomNo,randomNo,randomNo),
random.randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10)/100))))
illuminationMask = cv2.GaussianBlur(illuminationMask, (35,35), 0)
if random.randint(0,1) == 0:
background = cv2.subtract(background, illuminationMask)
else:
background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)
return background, mask
# Generate sample with an random background
def generate_random_full_synthetic_sample(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):
# Generate an blank image
background = np.random.randint(255, size=shape, dtype=np.uint8)
# Draw one to five random circles
for _ in range(random.randint(1, 5)):
cv2.circle(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),
int((shape[1] + shape[0]) * (random.randint(1, 20)/100)),
(random.randint(0,255), random.randint(0,255), random.randint(0,255)), -1)
# Draw two to five random rectangles
for _ in range(random.randint(2, 5)):
cv2.rectangle(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),
(random.randint(1, shape[1]), random.randint(1, shape[0])),
(random.randint(0,255), random.randint(0,255), random.randint(0,255)), cv2.FILLED)
# Draw five to 15 random lines
for _ in range(random.randint(5, 15)):
cv2.line(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),
(random.randint(1, shape[1]), random.randint(1, shape[0])),
(random.randint(0,255), random.randint(0,255), random.randint(0,255)),
random.randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10)/100))))
# Generate a marker and put them randomly on the background image
return generate_sample_with_given_background(background, get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))
# Generate sample with an random image background
def generate_random_half_synthetic_sample(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):
# Load a random image from bg directory
background = None
while background is None:
background = cv2.imread("./bg/" + os.listdir("./bg/")[(random.randint(0, len(os.listdir("./bg/")) - 1))], 3)
# Resize image to network size
background = cv2.resize(background, (shape[0], shape[1]))
# Generate a marker and put them randomly on the background image
return generate_sample_with_given_background(background, get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)) | [
"import os\nimport random\nimport numpy as np\nimport cv2\nimport cv2.aruco as aruco\n\n# Get dictionary by name\ndef get_dictionary(DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=False):\n dictionary = []\n if DICT_4X4_50:\n dictionary.append([aruco.DICT_4X4_50, 50])\n if DICT_4X4_100:\n dictionary.append([aruco.DICT_4X4_100, 100])\n if DICT_4X4_250:\n dictionary.append([aruco.DICT_4X4_250, 250])\n if DICT_4X4_1000:\n dictionary.append([aruco.DICT_4X4_1000, 1000])\n if DICT_5X5_50:\n dictionary.append([aruco.DICT_5X5_50, 50])\n if DICT_5X5_100:\n dictionary.append([aruco.DICT_5X5_100, 100])\n if DICT_5X5_250:\n dictionary.append([aruco.DICT_5X5_250, 250])\n if DICT_5X5_1000:\n dictionary.append([aruco.DICT_5X5_1000, 1000])\n if DICT_6X6_50:\n dictionary.append([aruco.DICT_6X6_50, 50])\n if DICT_6X6_100:\n dictionary.append([aruco.DICT_6X6_100, 100])\n if DICT_6X6_250:\n dictionary.append([aruco.DICT_6X6_250, 250])\n if DICT_6X6_1000:\n dictionary.append([aruco.DICT_6X6_1000, 1000])\n if DICT_7X7_50:\n dictionary.append([aruco.DICT_7X7_50, 50])\n if DICT_7X7_100:\n dictionary.append([aruco.DICT_7X7_100, 100])\n if DICT_7X7_250:\n dictionary.append([aruco.DICT_7X7_250, 250])\n if DICT_7X7_1000:\n dictionary.append([aruco.DICT_7X7_1000, 1000])\n if DICT_ARUCO_ORIGINAL:\n dictionary.append([aruco.DICT_ARUCO_ORIGINAL, 1024])\n if DICT_APRILTAG_16h5:\n dictionary.append([aruco.DICT_APRILTAG_16h5, 30])\n if DICT_APRILTAG_25h9:\n dictionary.append([aruco.DICT_APRILTAG_25h9, 35])\n if DICT_APRILTAG_36h10:\n dictionary.append([aruco.DICT_APRILTAG_36h10, 2320])\n if DICT_APRILTAG_36h11:\n dictionary.append([aruco.DICT_APRILTAG_36h11, 587])\n return dictionary\n\n# Generate a random marker with random id \ndef get_random_marker(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n # Create dictionary list with all enabled families\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n # Generate the marker with a white border\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]), random.randint(0, dictionary[1]-1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=255)\n # Convert to bgr to have three channels\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n # Change the marker color with random ofset\n marker[np.where((marker==[255,255,255]).all(axis=2))] = random.randint(245, 255)\n marker[np.where((marker==[0,0,0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n# Put the marker randomly on the background\ndef generate_sample_with_given_background(background, marker):\n # Resize the marker randomly\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9)/10)),\n int(marker.shape[0] * (random.randint(3, 9)/10))), interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n\n # Make a random perspective transformation\n marker = cv2.warpPerspective(marker,\n cv2.getPerspectiveTransform(\n np.float32([[0, 0], [width, 0], [0, height], [width, height]]),\n np.float32([[(random.randint(0,10)/100)*width, (random.randint(0,10)/100)*height],\n [width-((random.randint(0,10)/100)*width), (random.randint(0,10)/100)*height],\n [(random.randint(0,10)/100)*width, height-((random.randint(0,10)/100)*height)],\n [width-((random.randint(0,10)/100)*width), height-((random.randint(0,10)/100)*height)]])\n ),\n (width, height), borderValue=(1, 1, 1))\n\n # Rotate randomly\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker,\n cv2.getRotationMatrix2D((width/2, height/2), np.random.uniform(angle_rot)-angle_rot/2,1),\n (width, height), borderValue=(1, 1, 1))\n\n # Put the marker on a new image with transparent background equal to one\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y+marker.shape[0], x:x+marker.shape[1]] = marker[0:marker.shape[0], 0:marker.shape[1]]\n\n # Generate the ground through mask\n mask = np.zeros(shape=(background.shape[0], background.shape[1], background.shape[2])).astype(np.uint8)\n mask[np.where((marker2==[1,1,1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n\n # Put the non transparent background (marker) on the background image\n idx = (mask == 255)\n background[idx]= marker2[idx]\n \n # Create random illuminations\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5,80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.randint(1, shape[0])),\n int((shape[1] + shape[0]) * (random.randint(1, 20)/100)),\n (randomNo,randomNo,randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5,80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (randomNo,randomNo,randomNo),\n random.randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10)/100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35,35), 0)\n if random.randint(0,1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n\n return background, mask\n\n# Generate sample with an random background\ndef generate_random_full_synthetic_sample(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n # Generate an blank image\n background = np.random.randint(255, size=shape, dtype=np.uint8)\n # Draw one to five random circles \n for _ in range(random.randint(1, 5)):\n cv2.circle(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),\n int((shape[1] + shape[0]) * (random.randint(1, 20)/100)),\n (random.randint(0,255), random.randint(0,255), random.randint(0,255)), -1)\n # Draw two to five random rectangles\n for _ in range(random.randint(2, 5)):\n cv2.rectangle(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (random.randint(0,255), random.randint(0,255), random.randint(0,255)), cv2.FILLED)\n # Draw five to 15 random lines\n for _ in range(random.randint(5, 15)):\n cv2.line(background, (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (random.randint(1, shape[1]), random.randint(1, shape[0])),\n (random.randint(0,255), random.randint(0,255), random.randint(0,255)),\n random.randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10)/100))))\n # Generate a marker and put them randomly on the background image\n return generate_sample_with_given_background(background, get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n\n# Generate sample with an random image background\ndef generate_random_half_synthetic_sample(shape=(512,512,3), DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n # Load a random image from bg directory\n background = None\n while background is None:\n background = cv2.imread(\"./bg/\" + os.listdir(\"./bg/\")[(random.randint(0, len(os.listdir(\"./bg/\")) - 1))], 3)\n # Resize image to network size\n background = cv2.resize(background, (shape[0], shape[1]))\n # Generate a marker and put them randomly on the background image\n return generate_sample_with_given_background(background, get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250, DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250, DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250, DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250, DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5, DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))",
"import os\nimport random\nimport numpy as np\nimport cv2\nimport cv2.aruco as aruco\n\n\ndef get_dictionary(DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=\n False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False,\n DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False,\n DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False,\n DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False,\n DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=\n False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False,\n DICT_APRILTAG_36h11=False):\n dictionary = []\n if DICT_4X4_50:\n dictionary.append([aruco.DICT_4X4_50, 50])\n if DICT_4X4_100:\n dictionary.append([aruco.DICT_4X4_100, 100])\n if DICT_4X4_250:\n dictionary.append([aruco.DICT_4X4_250, 250])\n if DICT_4X4_1000:\n dictionary.append([aruco.DICT_4X4_1000, 1000])\n if DICT_5X5_50:\n dictionary.append([aruco.DICT_5X5_50, 50])\n if DICT_5X5_100:\n dictionary.append([aruco.DICT_5X5_100, 100])\n if DICT_5X5_250:\n dictionary.append([aruco.DICT_5X5_250, 250])\n if DICT_5X5_1000:\n dictionary.append([aruco.DICT_5X5_1000, 1000])\n if DICT_6X6_50:\n dictionary.append([aruco.DICT_6X6_50, 50])\n if DICT_6X6_100:\n dictionary.append([aruco.DICT_6X6_100, 100])\n if DICT_6X6_250:\n dictionary.append([aruco.DICT_6X6_250, 250])\n if DICT_6X6_1000:\n dictionary.append([aruco.DICT_6X6_1000, 1000])\n if DICT_7X7_50:\n dictionary.append([aruco.DICT_7X7_50, 50])\n if DICT_7X7_100:\n dictionary.append([aruco.DICT_7X7_100, 100])\n if DICT_7X7_250:\n dictionary.append([aruco.DICT_7X7_250, 250])\n if DICT_7X7_1000:\n dictionary.append([aruco.DICT_7X7_1000, 1000])\n if DICT_ARUCO_ORIGINAL:\n dictionary.append([aruco.DICT_ARUCO_ORIGINAL, 1024])\n if DICT_APRILTAG_16h5:\n dictionary.append([aruco.DICT_APRILTAG_16h5, 30])\n if DICT_APRILTAG_25h9:\n dictionary.append([aruco.DICT_APRILTAG_25h9, 35])\n if DICT_APRILTAG_36h10:\n dictionary.append([aruco.DICT_APRILTAG_36h10, 2320])\n if DICT_APRILTAG_36h11:\n dictionary.append([aruco.DICT_APRILTAG_36h11, 587])\n return dictionary\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\ndef generate_sample_with_given_background(background, marker):\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9\n ) / 10)), int(marker.shape[0] * (random.randint(3, 9) / 10))),\n interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n marker = cv2.warpPerspective(marker, cv2.getPerspectiveTransform(np.\n float32([[0, 0], [width, 0], [0, height], [width, height]]), np.\n float32([[random.randint(0, 10) / 100 * width, random.randint(0, 10\n ) / 100 * height], [width - random.randint(0, 10) / 100 * width, \n random.randint(0, 10) / 100 * height], [random.randint(0, 10) / 100 *\n width, height - random.randint(0, 10) / 100 * height], [width - \n random.randint(0, 10) / 100 * width, height - random.randint(0, 10) /\n 100 * height]])), (width, height), borderValue=(1, 1, 1))\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker, cv2.getRotationMatrix2D((width / 2, \n height / 2), np.random.uniform(angle_rot) - angle_rot / 2, 1), (\n width, height), borderValue=(1, 1, 1))\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y + marker.shape[0], x:x + marker.shape[1]] = marker[0:marker\n .shape[0], 0:marker.shape[1]]\n mask = np.zeros(shape=(background.shape[0], background.shape[1],\n background.shape[2])).astype(np.uint8)\n mask[np.where((marker2 == [1, 1, 1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.\n getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n idx = mask == 255\n background[idx] = marker2[idx]\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5, 80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), int((shape[1] + shape[0]) * (random.\n randint(1, 20) / 100)), (randomNo, randomNo, randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5, 80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (randomNo, randomNo, randomNo), random.\n randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10) /\n 100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35, 35), 0)\n if random.randint(0, 1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n return background, mask\n\n\ndef generate_random_full_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = np.random.randint(255, size=shape, dtype=np.uint8)\n for _ in range(random.randint(1, 5)):\n cv2.circle(background, (random.randint(1, shape[1]), random.randint\n (1, shape[0])), int((shape[1] + shape[0]) * (random.randint(1, \n 20) / 100)), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), -1)\n for _ in range(random.randint(2, 5)):\n cv2.rectangle(background, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(0, 255), random.randint(\n 0, 255), random.randint(0, 255)), cv2.FILLED)\n for _ in range(random.randint(5, 15)):\n cv2.line(background, (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), random.randint(3, int((shape[1] +\n shape[0]) * (random.randint(1, 10) / 100))))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n\n\ndef generate_random_half_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = None\n while background is None:\n background = cv2.imread('./bg/' + os.listdir('./bg/')[random.\n randint(0, len(os.listdir('./bg/')) - 1)], 3)\n background = cv2.resize(background, (shape[0], shape[1]))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n",
"<import token>\n\n\ndef get_dictionary(DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=\n False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False,\n DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False,\n DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False,\n DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False,\n DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=\n False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False,\n DICT_APRILTAG_36h11=False):\n dictionary = []\n if DICT_4X4_50:\n dictionary.append([aruco.DICT_4X4_50, 50])\n if DICT_4X4_100:\n dictionary.append([aruco.DICT_4X4_100, 100])\n if DICT_4X4_250:\n dictionary.append([aruco.DICT_4X4_250, 250])\n if DICT_4X4_1000:\n dictionary.append([aruco.DICT_4X4_1000, 1000])\n if DICT_5X5_50:\n dictionary.append([aruco.DICT_5X5_50, 50])\n if DICT_5X5_100:\n dictionary.append([aruco.DICT_5X5_100, 100])\n if DICT_5X5_250:\n dictionary.append([aruco.DICT_5X5_250, 250])\n if DICT_5X5_1000:\n dictionary.append([aruco.DICT_5X5_1000, 1000])\n if DICT_6X6_50:\n dictionary.append([aruco.DICT_6X6_50, 50])\n if DICT_6X6_100:\n dictionary.append([aruco.DICT_6X6_100, 100])\n if DICT_6X6_250:\n dictionary.append([aruco.DICT_6X6_250, 250])\n if DICT_6X6_1000:\n dictionary.append([aruco.DICT_6X6_1000, 1000])\n if DICT_7X7_50:\n dictionary.append([aruco.DICT_7X7_50, 50])\n if DICT_7X7_100:\n dictionary.append([aruco.DICT_7X7_100, 100])\n if DICT_7X7_250:\n dictionary.append([aruco.DICT_7X7_250, 250])\n if DICT_7X7_1000:\n dictionary.append([aruco.DICT_7X7_1000, 1000])\n if DICT_ARUCO_ORIGINAL:\n dictionary.append([aruco.DICT_ARUCO_ORIGINAL, 1024])\n if DICT_APRILTAG_16h5:\n dictionary.append([aruco.DICT_APRILTAG_16h5, 30])\n if DICT_APRILTAG_25h9:\n dictionary.append([aruco.DICT_APRILTAG_25h9, 35])\n if DICT_APRILTAG_36h10:\n dictionary.append([aruco.DICT_APRILTAG_36h10, 2320])\n if DICT_APRILTAG_36h11:\n dictionary.append([aruco.DICT_APRILTAG_36h11, 587])\n return dictionary\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\ndef generate_sample_with_given_background(background, marker):\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9\n ) / 10)), int(marker.shape[0] * (random.randint(3, 9) / 10))),\n interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n marker = cv2.warpPerspective(marker, cv2.getPerspectiveTransform(np.\n float32([[0, 0], [width, 0], [0, height], [width, height]]), np.\n float32([[random.randint(0, 10) / 100 * width, random.randint(0, 10\n ) / 100 * height], [width - random.randint(0, 10) / 100 * width, \n random.randint(0, 10) / 100 * height], [random.randint(0, 10) / 100 *\n width, height - random.randint(0, 10) / 100 * height], [width - \n random.randint(0, 10) / 100 * width, height - random.randint(0, 10) /\n 100 * height]])), (width, height), borderValue=(1, 1, 1))\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker, cv2.getRotationMatrix2D((width / 2, \n height / 2), np.random.uniform(angle_rot) - angle_rot / 2, 1), (\n width, height), borderValue=(1, 1, 1))\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y + marker.shape[0], x:x + marker.shape[1]] = marker[0:marker\n .shape[0], 0:marker.shape[1]]\n mask = np.zeros(shape=(background.shape[0], background.shape[1],\n background.shape[2])).astype(np.uint8)\n mask[np.where((marker2 == [1, 1, 1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.\n getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n idx = mask == 255\n background[idx] = marker2[idx]\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5, 80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), int((shape[1] + shape[0]) * (random.\n randint(1, 20) / 100)), (randomNo, randomNo, randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5, 80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (randomNo, randomNo, randomNo), random.\n randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10) /\n 100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35, 35), 0)\n if random.randint(0, 1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n return background, mask\n\n\ndef generate_random_full_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = np.random.randint(255, size=shape, dtype=np.uint8)\n for _ in range(random.randint(1, 5)):\n cv2.circle(background, (random.randint(1, shape[1]), random.randint\n (1, shape[0])), int((shape[1] + shape[0]) * (random.randint(1, \n 20) / 100)), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), -1)\n for _ in range(random.randint(2, 5)):\n cv2.rectangle(background, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(0, 255), random.randint(\n 0, 255), random.randint(0, 255)), cv2.FILLED)\n for _ in range(random.randint(5, 15)):\n cv2.line(background, (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), random.randint(3, int((shape[1] +\n shape[0]) * (random.randint(1, 10) / 100))))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n\n\ndef generate_random_half_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = None\n while background is None:\n background = cv2.imread('./bg/' + os.listdir('./bg/')[random.\n randint(0, len(os.listdir('./bg/')) - 1)], 3)\n background = cv2.resize(background, (shape[0], shape[1]))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n",
"<import token>\n\n\ndef get_dictionary(DICT_4X4_50=False, DICT_4X4_100=False, DICT_4X4_250=\n False, DICT_4X4_1000=False, DICT_5X5_50=False, DICT_5X5_100=False,\n DICT_5X5_250=False, DICT_5X5_1000=False, DICT_6X6_50=False,\n DICT_6X6_100=False, DICT_6X6_250=False, DICT_6X6_1000=False,\n DICT_7X7_50=False, DICT_7X7_100=False, DICT_7X7_250=False,\n DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=\n False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10=False,\n DICT_APRILTAG_36h11=False):\n dictionary = []\n if DICT_4X4_50:\n dictionary.append([aruco.DICT_4X4_50, 50])\n if DICT_4X4_100:\n dictionary.append([aruco.DICT_4X4_100, 100])\n if DICT_4X4_250:\n dictionary.append([aruco.DICT_4X4_250, 250])\n if DICT_4X4_1000:\n dictionary.append([aruco.DICT_4X4_1000, 1000])\n if DICT_5X5_50:\n dictionary.append([aruco.DICT_5X5_50, 50])\n if DICT_5X5_100:\n dictionary.append([aruco.DICT_5X5_100, 100])\n if DICT_5X5_250:\n dictionary.append([aruco.DICT_5X5_250, 250])\n if DICT_5X5_1000:\n dictionary.append([aruco.DICT_5X5_1000, 1000])\n if DICT_6X6_50:\n dictionary.append([aruco.DICT_6X6_50, 50])\n if DICT_6X6_100:\n dictionary.append([aruco.DICT_6X6_100, 100])\n if DICT_6X6_250:\n dictionary.append([aruco.DICT_6X6_250, 250])\n if DICT_6X6_1000:\n dictionary.append([aruco.DICT_6X6_1000, 1000])\n if DICT_7X7_50:\n dictionary.append([aruco.DICT_7X7_50, 50])\n if DICT_7X7_100:\n dictionary.append([aruco.DICT_7X7_100, 100])\n if DICT_7X7_250:\n dictionary.append([aruco.DICT_7X7_250, 250])\n if DICT_7X7_1000:\n dictionary.append([aruco.DICT_7X7_1000, 1000])\n if DICT_ARUCO_ORIGINAL:\n dictionary.append([aruco.DICT_ARUCO_ORIGINAL, 1024])\n if DICT_APRILTAG_16h5:\n dictionary.append([aruco.DICT_APRILTAG_16h5, 30])\n if DICT_APRILTAG_25h9:\n dictionary.append([aruco.DICT_APRILTAG_25h9, 35])\n if DICT_APRILTAG_36h10:\n dictionary.append([aruco.DICT_APRILTAG_36h10, 2320])\n if DICT_APRILTAG_36h11:\n dictionary.append([aruco.DICT_APRILTAG_36h11, 587])\n return dictionary\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\ndef generate_sample_with_given_background(background, marker):\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9\n ) / 10)), int(marker.shape[0] * (random.randint(3, 9) / 10))),\n interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n marker = cv2.warpPerspective(marker, cv2.getPerspectiveTransform(np.\n float32([[0, 0], [width, 0], [0, height], [width, height]]), np.\n float32([[random.randint(0, 10) / 100 * width, random.randint(0, 10\n ) / 100 * height], [width - random.randint(0, 10) / 100 * width, \n random.randint(0, 10) / 100 * height], [random.randint(0, 10) / 100 *\n width, height - random.randint(0, 10) / 100 * height], [width - \n random.randint(0, 10) / 100 * width, height - random.randint(0, 10) /\n 100 * height]])), (width, height), borderValue=(1, 1, 1))\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker, cv2.getRotationMatrix2D((width / 2, \n height / 2), np.random.uniform(angle_rot) - angle_rot / 2, 1), (\n width, height), borderValue=(1, 1, 1))\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y + marker.shape[0], x:x + marker.shape[1]] = marker[0:marker\n .shape[0], 0:marker.shape[1]]\n mask = np.zeros(shape=(background.shape[0], background.shape[1],\n background.shape[2])).astype(np.uint8)\n mask[np.where((marker2 == [1, 1, 1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.\n getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n idx = mask == 255\n background[idx] = marker2[idx]\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5, 80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), int((shape[1] + shape[0]) * (random.\n randint(1, 20) / 100)), (randomNo, randomNo, randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5, 80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (randomNo, randomNo, randomNo), random.\n randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10) /\n 100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35, 35), 0)\n if random.randint(0, 1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n return background, mask\n\n\ndef generate_random_full_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = np.random.randint(255, size=shape, dtype=np.uint8)\n for _ in range(random.randint(1, 5)):\n cv2.circle(background, (random.randint(1, shape[1]), random.randint\n (1, shape[0])), int((shape[1] + shape[0]) * (random.randint(1, \n 20) / 100)), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), -1)\n for _ in range(random.randint(2, 5)):\n cv2.rectangle(background, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(0, 255), random.randint(\n 0, 255), random.randint(0, 255)), cv2.FILLED)\n for _ in range(random.randint(5, 15)):\n cv2.line(background, (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), random.randint(3, int((shape[1] +\n shape[0]) * (random.randint(1, 10) / 100))))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n\n\n<function token>\n",
"<import token>\n<function token>\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\ndef generate_sample_with_given_background(background, marker):\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9\n ) / 10)), int(marker.shape[0] * (random.randint(3, 9) / 10))),\n interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n marker = cv2.warpPerspective(marker, cv2.getPerspectiveTransform(np.\n float32([[0, 0], [width, 0], [0, height], [width, height]]), np.\n float32([[random.randint(0, 10) / 100 * width, random.randint(0, 10\n ) / 100 * height], [width - random.randint(0, 10) / 100 * width, \n random.randint(0, 10) / 100 * height], [random.randint(0, 10) / 100 *\n width, height - random.randint(0, 10) / 100 * height], [width - \n random.randint(0, 10) / 100 * width, height - random.randint(0, 10) /\n 100 * height]])), (width, height), borderValue=(1, 1, 1))\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker, cv2.getRotationMatrix2D((width / 2, \n height / 2), np.random.uniform(angle_rot) - angle_rot / 2, 1), (\n width, height), borderValue=(1, 1, 1))\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y + marker.shape[0], x:x + marker.shape[1]] = marker[0:marker\n .shape[0], 0:marker.shape[1]]\n mask = np.zeros(shape=(background.shape[0], background.shape[1],\n background.shape[2])).astype(np.uint8)\n mask[np.where((marker2 == [1, 1, 1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.\n getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n idx = mask == 255\n background[idx] = marker2[idx]\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5, 80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), int((shape[1] + shape[0]) * (random.\n randint(1, 20) / 100)), (randomNo, randomNo, randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5, 80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (randomNo, randomNo, randomNo), random.\n randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10) /\n 100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35, 35), 0)\n if random.randint(0, 1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n return background, mask\n\n\ndef generate_random_full_synthetic_sample(shape=(512, 512, 3), DICT_4X4_50=\n False, DICT_4X4_100=False, DICT_4X4_250=False, DICT_4X4_1000=False,\n DICT_5X5_50=False, DICT_5X5_100=False, DICT_5X5_250=False,\n DICT_5X5_1000=False, DICT_6X6_50=False, DICT_6X6_100=False,\n DICT_6X6_250=False, DICT_6X6_1000=False, DICT_7X7_50=False,\n DICT_7X7_100=False, DICT_7X7_250=False, DICT_7X7_1000=False,\n DICT_ARUCO_ORIGINAL=False, DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9\n =False, DICT_APRILTAG_36h10=False, DICT_APRILTAG_36h11=True):\n background = np.random.randint(255, size=shape, dtype=np.uint8)\n for _ in range(random.randint(1, 5)):\n cv2.circle(background, (random.randint(1, shape[1]), random.randint\n (1, shape[0])), int((shape[1] + shape[0]) * (random.randint(1, \n 20) / 100)), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), -1)\n for _ in range(random.randint(2, 5)):\n cv2.rectangle(background, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(0, 255), random.randint(\n 0, 255), random.randint(0, 255)), cv2.FILLED)\n for _ in range(random.randint(5, 15)):\n cv2.line(background, (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(1, shape[1]), random.randint(1,\n shape[0])), (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255)), random.randint(3, int((shape[1] +\n shape[0]) * (random.randint(1, 10) / 100))))\n return generate_sample_with_given_background(background,\n get_random_marker(shape, DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11))\n\n\n<function token>\n",
"<import token>\n<function token>\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\ndef generate_sample_with_given_background(background, marker):\n marker = cv2.resize(marker, (int(marker.shape[1] * (random.randint(3, 9\n ) / 10)), int(marker.shape[0] * (random.randint(3, 9) / 10))),\n interpolation=cv2.INTER_AREA)\n height, width, _ = marker.shape\n marker = cv2.warpPerspective(marker, cv2.getPerspectiveTransform(np.\n float32([[0, 0], [width, 0], [0, height], [width, height]]), np.\n float32([[random.randint(0, 10) / 100 * width, random.randint(0, 10\n ) / 100 * height], [width - random.randint(0, 10) / 100 * width, \n random.randint(0, 10) / 100 * height], [random.randint(0, 10) / 100 *\n width, height - random.randint(0, 10) / 100 * height], [width - \n random.randint(0, 10) / 100 * width, height - random.randint(0, 10) /\n 100 * height]])), (width, height), borderValue=(1, 1, 1))\n angle_rot = random.randint(0, 360)\n marker = cv2.warpAffine(marker, cv2.getRotationMatrix2D((width / 2, \n height / 2), np.random.uniform(angle_rot) - angle_rot / 2, 1), (\n width, height), borderValue=(1, 1, 1))\n marker2 = np.ones(shape=background.shape).astype(np.uint8)\n x = random.randint(0, background.shape[1] - marker.shape[1])\n y = random.randint(0, background.shape[0] - marker.shape[0])\n marker2[y:y + marker.shape[0], x:x + marker.shape[1]] = marker[0:marker\n .shape[0], 0:marker.shape[1]]\n mask = np.zeros(shape=(background.shape[0], background.shape[1],\n background.shape[2])).astype(np.uint8)\n mask[np.where((marker2 == [1, 1, 1]).all(axis=2))] = 255\n mask = 255 - mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.\n getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))\n idx = mask == 255\n background[idx] = marker2[idx]\n illuminationMask = np.zeros(shape=background.shape, dtype=np.uint8)\n shape = background.shape\n for _ in range(random.randint(0, 5)):\n randomNo = random.randint(5, 80)\n cv2.circle(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), int((shape[1] + shape[0]) * (random.\n randint(1, 20) / 100)), (randomNo, randomNo, randomNo), -1)\n for _ in range(random.randint(0, 9)):\n randomNo = random.randint(5, 80)\n cv2.line(illuminationMask, (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (random.randint(1, shape[1]), random.\n randint(1, shape[0])), (randomNo, randomNo, randomNo), random.\n randint(3, int((shape[1] + shape[0]) * (random.randint(1, 10) /\n 100))))\n illuminationMask = cv2.GaussianBlur(illuminationMask, (35, 35), 0)\n if random.randint(0, 1) == 0:\n background = cv2.subtract(background, illuminationMask)\n else:\n background = cv2.addWeighted(background, 1.0, illuminationMask, 0.5, 0)\n return background, mask\n\n\n<function token>\n<function token>\n",
"<import token>\n<function token>\n\n\ndef get_random_marker(shape=(512, 512, 3), DICT_4X4_50=False, DICT_4X4_100=\n False, DICT_4X4_250=False, DICT_4X4_1000=False, DICT_5X5_50=False,\n DICT_5X5_100=False, DICT_5X5_250=False, DICT_5X5_1000=False,\n DICT_6X6_50=False, DICT_6X6_100=False, DICT_6X6_250=False,\n DICT_6X6_1000=False, DICT_7X7_50=False, DICT_7X7_100=False,\n DICT_7X7_250=False, DICT_7X7_1000=False, DICT_ARUCO_ORIGINAL=False,\n DICT_APRILTAG_16h5=False, DICT_APRILTAG_25h9=False, DICT_APRILTAG_36h10\n =False, DICT_APRILTAG_36h11=True):\n dictionary = get_dictionary(DICT_4X4_50, DICT_4X4_100, DICT_4X4_250,\n DICT_4X4_1000, DICT_5X5_50, DICT_5X5_100, DICT_5X5_250,\n DICT_5X5_1000, DICT_6X6_50, DICT_6X6_100, DICT_6X6_250,\n DICT_6X6_1000, DICT_7X7_50, DICT_7X7_100, DICT_7X7_250,\n DICT_7X7_1000, DICT_ARUCO_ORIGINAL, DICT_APRILTAG_16h5,\n DICT_APRILTAG_25h9, DICT_APRILTAG_36h10, DICT_APRILTAG_36h11)\n dictionary = random.choice(dictionary)\n marker = aruco.drawMarker(aruco.getPredefinedDictionary(dictionary[0]),\n random.randint(0, dictionary[1] - 1), int(shape[0] / 2) - 1)\n marker = cv2.copyMakeBorder(marker, 20, 20, 20, 20, cv2.BORDER_CONSTANT,\n value=255)\n marker = cv2.cvtColor(marker, cv2.COLOR_GRAY2BGR)\n marker[np.where((marker == [255, 255, 255]).all(axis=2))] = random.randint(\n 245, 255)\n marker[np.where((marker == [0, 0, 0]).all(axis=2))] = random.randint(0, 15)\n return marker\n\n\n<function token>\n<function token>\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,734 | 713f7f7fc3c912e08c74e562662ece5862c7c648 | from . import blueprint
from flask import render_template
from flask_login import login_required
from Dashboard import Dash_App1, Dash_App2, Dash_App3, Dash_App4
@blueprint.route('/app1')
@login_required
def app1_template():
return render_template('app1.html', dash_url = Dash_App1.url_base)
@blueprint.route('/app2')
@login_required
def app2_template():
return render_template('app2.html', dash_url = Dash_App2.url_base)
@blueprint.route('/app3')
@login_required
def app3_template():
return render_template('app3.html', dash_url = Dash_App3.url_base)
@blueprint.route('/app4')
@login_required
def app4_template():
return render_template('app4.html', dash_url = Dash_App4.url_base) | [
"from . import blueprint\nfrom flask import render_template\nfrom flask_login import login_required\nfrom Dashboard import Dash_App1, Dash_App2, Dash_App3, Dash_App4\n\[email protected]('/app1')\n@login_required\ndef app1_template():\n return render_template('app1.html', dash_url = Dash_App1.url_base)\n\[email protected]('/app2')\n@login_required\ndef app2_template():\n return render_template('app2.html', dash_url = Dash_App2.url_base)\n\[email protected]('/app3')\n@login_required\ndef app3_template():\n return render_template('app3.html', dash_url = Dash_App3.url_base)\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url = Dash_App4.url_base)",
"from . import blueprint\nfrom flask import render_template\nfrom flask_login import login_required\nfrom Dashboard import Dash_App1, Dash_App2, Dash_App3, Dash_App4\n\n\[email protected]('/app1')\n@login_required\ndef app1_template():\n return render_template('app1.html', dash_url=Dash_App1.url_base)\n\n\[email protected]('/app2')\n@login_required\ndef app2_template():\n return render_template('app2.html', dash_url=Dash_App2.url_base)\n\n\[email protected]('/app3')\n@login_required\ndef app3_template():\n return render_template('app3.html', dash_url=Dash_App3.url_base)\n\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url=Dash_App4.url_base)\n",
"<import token>\n\n\[email protected]('/app1')\n@login_required\ndef app1_template():\n return render_template('app1.html', dash_url=Dash_App1.url_base)\n\n\[email protected]('/app2')\n@login_required\ndef app2_template():\n return render_template('app2.html', dash_url=Dash_App2.url_base)\n\n\[email protected]('/app3')\n@login_required\ndef app3_template():\n return render_template('app3.html', dash_url=Dash_App3.url_base)\n\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url=Dash_App4.url_base)\n",
"<import token>\n\n\[email protected]('/app1')\n@login_required\ndef app1_template():\n return render_template('app1.html', dash_url=Dash_App1.url_base)\n\n\[email protected]('/app2')\n@login_required\ndef app2_template():\n return render_template('app2.html', dash_url=Dash_App2.url_base)\n\n\n<function token>\n\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url=Dash_App4.url_base)\n",
"<import token>\n<function token>\n\n\[email protected]('/app2')\n@login_required\ndef app2_template():\n return render_template('app2.html', dash_url=Dash_App2.url_base)\n\n\n<function token>\n\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url=Dash_App4.url_base)\n",
"<import token>\n<function token>\n<function token>\n<function token>\n\n\[email protected]('/app4')\n@login_required\ndef app4_template():\n return render_template('app4.html', dash_url=Dash_App4.url_base)\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,735 | 3bb749aa8b97ce7cc3c65c4152fed4395fb8e44c | import sys
import json
import socket
import threading
import random
import time
import mutex
from pythonchord.address import Address, inrange
from pythonchord.remote import Remote
from pythonchord.settings import *
from network import *
from pythonchord.chord import *
def generate_id(x, y, range):
return int(int(x)/range*360/range+int(y)/range)
class Taxi(object):
def __init__(self, x, y, local_address, remote_address = None):
self.x = x
self.y = y
self.address = local_address
if remote_address is None:
self.local = Local(local_address)
else:
self.local = Local(local_address, remote_address)
self.local.start()
# x, y, local_ip , port for 1x1, port for 20x20, remote_ip_1x1, remote port for 1x1, remote_ip_20x20, remote port for 20x20
if __name__ == "__main__":
import sys
x = sys.argv[1]
y = sys.argv[2]
local_ip = sys.argv[3]
if len(sys.argv) == 5:
taxi = Taxi(x,y,Address(local_ip, sys.argv[4]))
else:
remote_ip = sys.argv[5]
taxi = Taxi(x,y,Address(local_ip, sys.argv[4]),Address(remote_ip, sys.argv[6])) | [
"import sys\nimport json\nimport socket\nimport threading\nimport random\nimport time\nimport mutex\n\nfrom pythonchord.address import Address, inrange\nfrom pythonchord.remote import Remote\nfrom pythonchord.settings import *\nfrom network import *\nfrom pythonchord.chord import *\n\ndef generate_id(x, y, range):\n return int(int(x)/range*360/range+int(y)/range)\n\nclass Taxi(object):\n def __init__(self, x, y, local_address, remote_address = None):\n self.x = x\n self.y = y\n self.address = local_address\n if remote_address is None:\n self.local = Local(local_address)\n else:\n self.local = Local(local_address, remote_address) \n self.local.start()\n\n# x, y, local_ip , port for 1x1, port for 20x20, remote_ip_1x1, remote port for 1x1, remote_ip_20x20, remote port for 20x20\n\nif __name__ == \"__main__\":\n import sys\n x = sys.argv[1]\n y = sys.argv[2]\n local_ip = sys.argv[3]\n if len(sys.argv) == 5:\n taxi = Taxi(x,y,Address(local_ip, sys.argv[4]))\n else:\n remote_ip = sys.argv[5]\n taxi = Taxi(x,y,Address(local_ip, sys.argv[4]),Address(remote_ip, sys.argv[6]))",
"import sys\nimport json\nimport socket\nimport threading\nimport random\nimport time\nimport mutex\nfrom pythonchord.address import Address, inrange\nfrom pythonchord.remote import Remote\nfrom pythonchord.settings import *\nfrom network import *\nfrom pythonchord.chord import *\n\n\ndef generate_id(x, y, range):\n return int(int(x) / range * 360 / range + int(y) / range)\n\n\nclass Taxi(object):\n\n def __init__(self, x, y, local_address, remote_address=None):\n self.x = x\n self.y = y\n self.address = local_address\n if remote_address is None:\n self.local = Local(local_address)\n else:\n self.local = Local(local_address, remote_address)\n self.local.start()\n\n\nif __name__ == '__main__':\n import sys\n x = sys.argv[1]\n y = sys.argv[2]\n local_ip = sys.argv[3]\n if len(sys.argv) == 5:\n taxi = Taxi(x, y, Address(local_ip, sys.argv[4]))\n else:\n remote_ip = sys.argv[5]\n taxi = Taxi(x, y, Address(local_ip, sys.argv[4]), Address(remote_ip,\n sys.argv[6]))\n",
"<import token>\n\n\ndef generate_id(x, y, range):\n return int(int(x) / range * 360 / range + int(y) / range)\n\n\nclass Taxi(object):\n\n def __init__(self, x, y, local_address, remote_address=None):\n self.x = x\n self.y = y\n self.address = local_address\n if remote_address is None:\n self.local = Local(local_address)\n else:\n self.local = Local(local_address, remote_address)\n self.local.start()\n\n\nif __name__ == '__main__':\n import sys\n x = sys.argv[1]\n y = sys.argv[2]\n local_ip = sys.argv[3]\n if len(sys.argv) == 5:\n taxi = Taxi(x, y, Address(local_ip, sys.argv[4]))\n else:\n remote_ip = sys.argv[5]\n taxi = Taxi(x, y, Address(local_ip, sys.argv[4]), Address(remote_ip,\n sys.argv[6]))\n",
"<import token>\n\n\ndef generate_id(x, y, range):\n return int(int(x) / range * 360 / range + int(y) / range)\n\n\nclass Taxi(object):\n\n def __init__(self, x, y, local_address, remote_address=None):\n self.x = x\n self.y = y\n self.address = local_address\n if remote_address is None:\n self.local = Local(local_address)\n else:\n self.local = Local(local_address, remote_address)\n self.local.start()\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\nclass Taxi(object):\n\n def __init__(self, x, y, local_address, remote_address=None):\n self.x = x\n self.y = y\n self.address = local_address\n if remote_address is None:\n self.local = Local(local_address)\n else:\n self.local = Local(local_address, remote_address)\n self.local.start()\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\nclass Taxi(object):\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<code token>\n"
] | false |
99,736 | 5cca6bc7a414c6a8e7e1ac52d88e8ce28ff3520f | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import random
def IniciaMapa(dimensoes=[30, 30]):
"""
Carrega randomicamente um tabuleiro com valores aleatórios (por padrão, [30,30])
Entrada:
- Dimensões desejadas para o tabuleiro (lista)
Saída:
- Matriz x por y com valores aleatórios
"""
print('\n')
print(5*"*")
print("TRABALHO DE INTELIGÊNCIA ARTIFICIAL - IMPLEMENTAÇÃO A*")
print(5*"*")
print('\n')
print("Neste trabalho, um tabuleiro 2D representando um mapa é gerado e, com a entrada dos pontos de origem e destino, o problema busca encontrar o deslocamento ótimo com o algoritmo A*")
print('Seu mapa pode ser visualizado na janela em suspensão.')
print(2*'\n')
# tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))
tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))
return tabuleiro
if __name__ == '__main__':
tabuleiro = IniciaMapa()
print(tabuleiro[1, 2])
| [
"# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n\ndef IniciaMapa(dimensoes=[30, 30]):\n \"\"\"\n Carrega randomicamente um tabuleiro com valores aleatórios (por padrão, [30,30])\n\n Entrada:\n - Dimensões desejadas para o tabuleiro (lista)\n\n Saída:\n - Matriz x por y com valores aleatórios\n \"\"\"\n\n print('\\n')\n print(5*\"*\")\n print(\"TRABALHO DE INTELIGÊNCIA ARTIFICIAL - IMPLEMENTAÇÃO A*\")\n print(5*\"*\")\n print('\\n')\n print(\"Neste trabalho, um tabuleiro 2D representando um mapa é gerado e, com a entrada dos pontos de origem e destino, o problema busca encontrar o deslocamento ótimo com o algoritmo A*\")\n print('Seu mapa pode ser visualizado na janela em suspensão.')\n print(2*'\\n')\n\n # tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))\n tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))\n\n return tabuleiro\n\n\nif __name__ == '__main__':\n tabuleiro = IniciaMapa()\n print(tabuleiro[1, 2])\n",
"import matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n\ndef IniciaMapa(dimensoes=[30, 30]):\n \"\"\"\n Carrega randomicamente um tabuleiro com valores aleatórios (por padrão, [30,30])\n\n Entrada:\n - Dimensões desejadas para o tabuleiro (lista)\n\n Saída:\n - Matriz x por y com valores aleatórios\n \"\"\"\n print('\\n')\n print(5 * '*')\n print('TRABALHO DE INTELIGÊNCIA ARTIFICIAL - IMPLEMENTAÇÃO A*')\n print(5 * '*')\n print('\\n')\n print(\n 'Neste trabalho, um tabuleiro 2D representando um mapa é gerado e, com a entrada dos pontos de origem e destino, o problema busca encontrar o deslocamento ótimo com o algoritmo A*'\n )\n print('Seu mapa pode ser visualizado na janela em suspensão.')\n print(2 * '\\n')\n tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))\n return tabuleiro\n\n\nif __name__ == '__main__':\n tabuleiro = IniciaMapa()\n print(tabuleiro[1, 2])\n",
"<import token>\n\n\ndef IniciaMapa(dimensoes=[30, 30]):\n \"\"\"\n Carrega randomicamente um tabuleiro com valores aleatórios (por padrão, [30,30])\n\n Entrada:\n - Dimensões desejadas para o tabuleiro (lista)\n\n Saída:\n - Matriz x por y com valores aleatórios\n \"\"\"\n print('\\n')\n print(5 * '*')\n print('TRABALHO DE INTELIGÊNCIA ARTIFICIAL - IMPLEMENTAÇÃO A*')\n print(5 * '*')\n print('\\n')\n print(\n 'Neste trabalho, um tabuleiro 2D representando um mapa é gerado e, com a entrada dos pontos de origem e destino, o problema busca encontrar o deslocamento ótimo com o algoritmo A*'\n )\n print('Seu mapa pode ser visualizado na janela em suspensão.')\n print(2 * '\\n')\n tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))\n return tabuleiro\n\n\nif __name__ == '__main__':\n tabuleiro = IniciaMapa()\n print(tabuleiro[1, 2])\n",
"<import token>\n\n\ndef IniciaMapa(dimensoes=[30, 30]):\n \"\"\"\n Carrega randomicamente um tabuleiro com valores aleatórios (por padrão, [30,30])\n\n Entrada:\n - Dimensões desejadas para o tabuleiro (lista)\n\n Saída:\n - Matriz x por y com valores aleatórios\n \"\"\"\n print('\\n')\n print(5 * '*')\n print('TRABALHO DE INTELIGÊNCIA ARTIFICIAL - IMPLEMENTAÇÃO A*')\n print(5 * '*')\n print('\\n')\n print(\n 'Neste trabalho, um tabuleiro 2D representando um mapa é gerado e, com a entrada dos pontos de origem e destino, o problema busca encontrar o deslocamento ótimo com o algoritmo A*'\n )\n print('Seu mapa pode ser visualizado na janela em suspensão.')\n print(2 * '\\n')\n tabuleiro = np.random.randint(20, size=(dimensoes[0], dimensoes[1]))\n return tabuleiro\n\n\n<code token>\n",
"<import token>\n<function token>\n<code token>\n"
] | false |
99,737 | eba3aad5bc9b1e5d2efe9d8d36d6e5c56c213307 | # Generated by Django 3.1.3 on 2020-11-07 14:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('staffcatalog', '0003_auto_20201107_1358'),
]
operations = [
migrations.AlterField(
model_name='person',
name='job_end',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='person',
name='patronymic',
field=models.CharField(blank=True, max_length=30),
),
]
| [
"# Generated by Django 3.1.3 on 2020-11-07 14:01\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('staffcatalog', '0003_auto_20201107_1358'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='person',\n name='job_end',\n field=models.DateField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='person',\n name='patronymic',\n field=models.CharField(blank=True, max_length=30),\n ),\n ]\n",
"from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('staffcatalog', '0003_auto_20201107_1358')]\n operations = [migrations.AlterField(model_name='person', name='job_end',\n field=models.DateField(blank=True, null=True)), migrations.\n AlterField(model_name='person', name='patronymic', field=models.\n CharField(blank=True, max_length=30))]\n",
"<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('staffcatalog', '0003_auto_20201107_1358')]\n operations = [migrations.AlterField(model_name='person', name='job_end',\n field=models.DateField(blank=True, null=True)), migrations.\n AlterField(model_name='person', name='patronymic', field=models.\n CharField(blank=True, max_length=30))]\n",
"<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n",
"<import token>\n<class token>\n"
] | false |
99,738 | 08027d9b7a003aaf24a347c3b9fe8b4513b4d1a1 | from functools import wraps
from abc import abstractmethod
import time
import json
import random
import numpy as np
def timer(pre_str=None):
def timed(func):
@wraps(func)
def wrapped(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
print_srt = pre_str or func.__name__
print(f"| {print_srt} cost {time.time() - start_time:.3f} seconds.")
return res
return wrapped
return timed
class PMSConfig:
def __init__(self, path):
self.path = path
with open(path, "r") as f:
self.config = json.load(f)
for k, v in self.config.items():
setattr(self, k, v)
def clone(self):
return PMSConfig(self.path)
class PVector3f:
def __init__(self, x: float, y: float, z: float):
self.x = float(x)
self.y = float(y)
self.z = float(z)
def normalize(self):
sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
self.x /= sqf
self.y /= sqf
self.z /= sqf
return self
def __mul__(self, other):
if not isinstance(other, PVector3f):
raise TypeError(f"{type(self)} and {type(other)} could not multiply.")
return self.x * other.x + self.y * other.y + self.z * other.z
def __add__(self, other):
if not isinstance(other, PVector3f):
raise TypeError(f"{type(self)} and {type(other)} could not add.")
return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
if not isinstance(other, PVector3f):
raise TypeError(f"{type(self)} and {type(other)} could not sub.")
return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)
def __invert__(self):
return PVector3f(-self.x, -self.y, -self.z)
def __eq__(self, other):
if not isinstance(other, PVector3f):
raise TypeError(f"{type(self)} and {type(other)} could not compare.")
return self.x == other.x and self.y == other.y and self.z == other.z
class DisparityPlane:
def __init__(self, x: int = 0, y: int = 0, d: int = 0, n: PVector3f = None, p: PVector3f = None):
if p is None:
x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d) / n.z
self.p = PVector3f(x, y, z)
else:
self.p = PVector3f(p.x, p.y, p.z)
def to_disparity(self, x: int, y: int):
return self.p * PVector3f(x, y, 1)
def to_norm(self):
return PVector3f(self.p.x, self.p.y, -1).normalize()
def to_another_view(self, x: int, y: int):
d = self.to_disparity(x, y)
return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z - self.p.x * d))
def __eq__(self, other):
if not isinstance(other, DisparityPlane):
raise TypeError(f"{type(self)} and {type(other)} could not compare.")
return self.p == other.p
class CostComputer:
def __init__(self, image_left, image_right, width, height, patch_size, min_disparity, max_disparity):
self.image_left = image_left
self.image_right = image_right
self.width = width
self.height = height
self.patch_size = patch_size
self.min_disparity = min_disparity
self.max_disparity = max_disparity
@staticmethod
def fast_exp(v: float):
v = 1 + v / 1024
for _ in range(10):
v *= v
return v
@abstractmethod
def compute(self, x, y, d, *args, **kwargs):
raise NotImplementedError("Compute should be implement.")
class CostComputerPMS(CostComputer):
def __init__(self, image_left, image_right, grad_left, grad_right, width, height, patch_size, min_disparity,
max_disparity, gamma, alpha, tau_col, tau_grad):
super(CostComputerPMS, self).__init__(image_left=image_left, image_right=image_right,
width=width, height=height, patch_size=patch_size,
min_disparity=min_disparity, max_disparity=max_disparity)
self.grad_left = grad_left
self.grad_right = grad_right
self.gamma = gamma
self.alpha = alpha
self.tau_col = tau_col
self.tau_grad = tau_grad
def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):
xr = x - d
if xr < 0 or xr > self.width:
return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad
col_p = col_p if col_p is not None else self.get_color(self.image_left, x=x, y=y)
col_q = self.get_color(self.image_right, x=xr, y=y)
dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])
dc = min(dc, self.tau_col)
grad_p = grad_p if grad_p is not None else self.get_gradient(self.grad_left, x=x, y=y)
grad_q = self.get_gradient(self.grad_right, x=xr, y=y)
dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])
dg = min(dg, self.tau_grad)
return (1 - self.alpha) * dc + self.alpha * dg
def compute_agg(self, x, y, p: DisparityPlane):
pat = self.patch_size // 2
col_p = self.image_left[y, x, :]
cost = 0
for r in range(-pat, pat, 1):
y_ = y + r
for c in range(-pat, pat, 1):
x_ = x + c
if y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.width - 1:
continue
d = p.to_disparity(x=x, y=y)
if d < self.min_disparity or d > self.max_disparity:
cost += 120.0
continue
col_q = self.image_left[y_, x_, :]
dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])
# w = np.exp(-dc / self.gamma)
w = self.fast_exp(-dc / self.gamma)
grad_q = self.grad_left[y_, x_]
cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q, grad_p=grad_q)
return cost
def get_color(self, image, x: float, y: int):
x1 = int(np.floor(x))
x2 = int(np.ceil(x))
ofs = x - x1
color = list()
for i in range(3):
g1 = image[y, x1, i]
g2 = image[y, x2, i] if x2 < self.width else g1
color.append((1 - ofs) * g1 + ofs * g2)
return color
def get_gradient(self, gradient, x: float, y: int):
x1 = int(np.floor(x))
x2 = int(np.ceil(x))
ofs = x - x1
g1 = gradient[y, x1]
g2 = gradient[y, x2] if x2 < self.width else g1
x_ = (1 - ofs) * g1[0] + ofs * g2[0]
y_ = (1 - ofs) * g1[1] + ofs * g2[1]
return [x_, y_]
class PropagationPMS:
def __init__(self, image_left, image_right, width, height, grad_left, grad_right,
plane_left, plane_right, config, cost_left, cost_right, disparity_map):
self.image_left = image_left
self.image_right = image_right
self.width = width
self.height = height
self.grad_left = grad_left
self.grad_right = grad_right
self.plane_left = plane_left
self.plane_right = plane_right
self.config = config
self.cost_left = cost_left
self.cost_right = cost_right
self.disparity_map = disparity_map
self.cost_cpt_left = CostComputerPMS(image_left, image_right, grad_left, grad_right, width, height,
config.patch_size, config.min_disparity, config.max_disparity,
config.gamma, config.alpha, config.tau_col, config.tau_grad)
self.cost_cpt_right = CostComputerPMS(image_right, image_left, grad_right, grad_left, width, height,
config.patch_size, -config.max_disparity, -config.min_disparity,
config.gamma, config.alpha, config.tau_col, config.tau_grad)
self.compute_cost_data()
def do_propagation(self, curr_iter):
direction = 1 if curr_iter % 2 == 0 else -1
y = 0 if curr_iter % 2 == 0 else self.height - 1
count_ = 0
times_ = 0
print(f"\r| Propagation iter {curr_iter}: 0", end="")
for i in range(self.height):
x = 0 if curr_iter % 2 == 0 else self.width - 1
for j in range(self.width):
start_ = time.time()
self.spatial_propagation(x=x, y=y, direction=direction)
if not self.config.is_force_fpw:
self.plane_refine(x=x, y=y)
self.view_propagation(x=x, y=y)
x += direction
times_ += time.time() - start_
count_ += 1
print(f"\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_/times_:.3f} it/s", end="")
y += direction
print(f"\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.")
def compute_cost_data(self):
print(f"\r| Init cost {0} / {self.height * self.width}", end="")
count_ = 0
times_ = 0
for y in range(self.height):
for x in range(self.width):
start_ = time.time()
p = self.plane_left[y, x]
self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x, y=y, p=p)
times_ += time.time() - start_
count_ += 1
print(f"\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_/times_:.3f} it/s", end="")
print(f"\r| Initialize cost {times_:.3f} seconds.")
def spatial_propagation(self, x, y, direction):
plane_p = self.plane_left[y, x]
cost_p = self.cost_left[y, x]
xd = x - direction
if 0 <= xd < self.width:
plane = self.plane_left[y, xd]
if plane != plane_p:
cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)
if cost < cost_p:
plane_p = plane
cost_p = cost
yd = y - direction
if 0 <= yd < self.height:
plane = self.plane_left[yd, x]
if plane != plane_p:
cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)
if cost < cost_p:
plane_p = plane
cost_p = cost
self.plane_left[y, x] = plane_p
self.cost_left[y, x] = cost_p
def view_propagation(self, x, y):
plane_p = self.plane_left[y, x]
d_p = plane_p.to_disparity(x=x, y=y)
xr = int(x - d_p)
if xr < 0 or xr > self.width - 1:
return
plane_q = self.plane_right[y, xr]
cost_q = self.cost_right[y, xr]
plane_p2q = plane_p.to_another_view(x=x, y=y)
d_q = plane_p2q.to_disparity(x=xr, y=y)
cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)
if cost < cost_q:
plane_q = plane_p2q
cost_q = cost
self.plane_right[y, xr] = plane_q
self.cost_right[y, xr] = cost_q
def plane_refine(self, x, y):
min_disp = self.config.min_disparity
max_disp = self.config.max_disparity
plane_p = self.plane_left[y, x]
cost_p = self.cost_left[y, x]
d_p = plane_p.to_disparity(x=x, y=y)
norm_p = plane_p.to_norm()
disp_update = (max_disp - min_disp) / 2.0
norm_update = 1.0
stop_thres = 0.1
while disp_update > stop_thres:
disp_rd = np.random.uniform(-1.0, 1.0) * disp_update
if self.config.is_integer_disparity:
disp_rd = int(disp_rd)
d_p_new = d_p + disp_rd
if d_p_new < min_disp or d_p_new > max_disp:
disp_update /= 2
norm_update /= 2
continue
if not self.config.is_force_fpw:
norm_rd = PVector3f(
x=np.random.uniform(-1.0, 1.0) * norm_update,
y=np.random.uniform(-1.0, 1.0) * norm_update,
z=np.random.uniform(-1.0, 1.0) * norm_update,
)
while norm_rd.z == 0.0:
norm_rd.z = np.random.uniform(-1.0, 1.0)
else:
norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)
norm_p_new = norm_p + norm_rd
norm_p_new.normalize()
plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)
if plane_new != plane_p:
cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)
if cost < cost_p:
plane_p = plane_new
cost_p = cost
d_p = d_p_new
norm_p = norm_p_new
self.plane_left[y, x] = plane_p
self.cost_left[y, x] = cost_p
disp_update /= 2.0
norm_update /= 2.0
class PatchMatchStereo:
def __init__(self, width, height, config, random_seed=2021):
self.random_seed = random_seed
random.seed(random_seed)
np.random.seed(random_seed)
self.image_left = None
self.image_right = None
self.width = width
self.height = height
self.config = config
self.disparity_range = config.max_disparity - config.min_disparity
self.gray_left = None
self.gray_right = None
self.grad_left = None
self.grad_right = None
self.cost_left = None
self.cost_right = None
self.disparity_left = None
self.disparity_right = None
self.plane_left = None
self.plane_right = None
self.mistakes_left = None
self.mistakes_right = None
self.invalid_disparity = 1024.0
self.init(h=height, w=width)
@timer("Initialize memory")
def init(self, h, w):
self.width = w
self.height = h
self.disparity_range = self.config.max_disparity - self.config.min_disparity
self.gray_left = np.zeros([self.height, self.width], dtype=int)
self.gray_right = np.zeros([self.height, self.width], dtype=int)
self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)
self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)
self.cost_left = np.zeros([self.height, self.width], dtype=float)
self.cost_right = np.zeros([self.height, self.width], dtype=float)
self.disparity_left = np.zeros([self.height, self.width], dtype=float)
self.disparity_right = np.zeros([self.height, self.width], dtype=float)
self.plane_left = np.zeros([self.height, self.width], dtype=object)
self.plane_right = np.zeros([self.height, self.width], dtype=object)
self.mistakes_left = list()
self.mistakes_right = list()
@timer("Initialize parameters")
def random_init(self):
for y in range(self.height):
for x in range(self.width):
# random disparity
disp_l = np.random.uniform(float(self.config.min_disparity), float(self.config.max_disparity))
disp_r = np.random.uniform(float(self.config.min_disparity), float(self.config.max_disparity))
if self.config.is_integer_disparity:
disp_l, disp_r = int(disp_l), int(disp_r)
self.disparity_left[y, x], self.disparity_right[y, x] = disp_l, disp_r
# random normal vector
norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x=0.0, y=0.0, z=1.0)
if not self.config.is_force_fpw:
norm_l = PVector3f(
x=np.random.uniform(-1.0, 1.0),
y=np.random.uniform(-1.0, 1.0),
z=np.random.uniform(-1.0, 1.0),
)
norm_r = PVector3f(
x=np.random.uniform(-1.0, 1.0),
y=np.random.uniform(-1.0, 1.0),
z=np.random.uniform(-1.0, 1.0),
)
while norm_l.z == 0.0:
norm_l.z = np.random.uniform(-1.0, 1.0)
while norm_r.z == 0.0:
norm_r.z = np.random.uniform(-1.0, 1.0)
norm_l, norm_r = norm_l.normalize(), norm_r.normalize()
# random disparity plane
self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l, n=norm_l)
self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r, n=norm_r)
@timer("Plane to disparity")
def plane_to_disparity(self):
for y in range(self.height):
for x in range(self.width):
self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(x=x, y=y)
self.disparity_right[y, x] = self.plane_right[y, x].to_disparity(x=x, y=y)
@timer("Total match")
def match(self, image_left, image_right):
self.image_left, self.image_right = image_left, image_right
self.random_init()
self.compute_gray()
self.compute_gradient()
self.propagation()
self.plane_to_disparity()
if self.config.is_check_lr:
self.lr_check()
if self.config.is_fill_holes:
self.fill_holes_in_disparity_map()
@timer("Propagation")
def propagation(self):
config_left = self.config.clone()
config_right = self.config.clone()
config_right.min_disparity = -config_left.max_disparity
config_right.max_disparity = -config_left.min_disparity
propa_left = PropagationPMS(self.image_left, self.image_right, self.width, self.height,
self.grad_left, self.grad_right, self.plane_left, self.plane_right,
config_left, self.cost_left, self.cost_right, self.disparity_left)
propa_right = PropagationPMS(self.image_right, self.image_left, self.width, self.height,
self.grad_right, self.grad_left, self.plane_right, self.plane_left,
config_right, self.cost_right, self.cost_left, self.disparity_right)
for it in range(self.config.n_iter):
propa_left.do_propagation(curr_iter=it)
propa_right.do_propagation(curr_iter=it)
@timer("Initialize gray")
def compute_gray(self):
for y in range(self.height):
for x in range(self.width):
b, g, r = self.image_left[y, x]
self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)
b, g, r = self.image_right[y, x]
self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)
@timer("Initialize gradient")
def compute_gradient(self):
for y in range(1, self.height - 1, 1):
for x in range(1, self.width - 1, 1):
grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - 1, x - 1] \
+ 2 * self.gray_left[y, x + 1] - 2 * self.gray_left[y, x - 1] \
+ self.gray_left[y + 1, x + 1] - self.gray_left[y + 1, x - 1]
grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - 1, x - 1] \
+ 2 * self.gray_left[y + 1, x] - 2 * self.gray_left[y - 1, x] \
+ self.gray_left[y + 1, x + 1] - self.gray_left[y - 1, x + 1]
grad_y, grad_x = grad_y / 8, grad_x / 8
self.grad_left[y, x, 0] = grad_x
self.grad_left[y, x, 1] = grad_y
grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y - 1, x - 1] \
+ 2 * self.gray_right[y, x + 1] - 2 * self.gray_right[y, x - 1] \
+ self.gray_right[y + 1, x + 1] - self.gray_right[y + 1, x - 1]
grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y - 1, x - 1] \
+ 2 * self.gray_right[y + 1, x] - 2 * self.gray_right[y - 1, x] \
+ self.gray_right[y + 1, x + 1] - self.gray_right[y - 1, x + 1]
grad_y, grad_x = grad_y / 8, grad_x / 8
self.grad_right[y, x, 0] = grad_x
self.grad_right[y, x, 1] = grad_y
@timer("LR check")
def lr_check(self):
for y in range(self.height):
for x in range(self.width):
disp = self.disparity_left[y, x]
if disp == self.invalid_disparity:
self.mistakes_left.append([x, y])
continue
col_right = round(x - disp)
if 0 <= col_right < self.width:
disp_r = self.disparity_right[y, col_right]
if abs(disp + disp_r) > self.config.lr_check_threshold:
self.disparity_left[y, x] = self.invalid_disparity
self.mistakes_left.append([x, y])
else:
self.disparity_left[y, x] = self.invalid_disparity
self.mistakes_left.append([x, y])
for y in range(self.height):
for x in range(self.width):
disp = self.disparity_right[y, x]
if disp == self.invalid_disparity:
self.mistakes_right.append([x, y])
continue
col_right = round(x - disp)
if 0 <= col_right < self.width:
disp_r = self.disparity_left[y, col_right]
if abs(disp + disp_r) > self.config.lr_check_threshold:
self.disparity_right[y, x] = self.invalid_disparity
self.mistakes_right.append([x, y])
else:
self.disparity_right[y, x] = self.invalid_disparity
self.mistakes_right.append([x, y])
@timer("Fill holes")
def fill_holes_in_disparity_map(self):
for i in range(len(self.mistakes_left)):
left_planes = list()
x, y = self.mistakes_left[i]
xs = x + 1
while xs < self.width:
if self.disparity_left[y, xs] != self.invalid_disparity:
left_planes.append(self.plane_left[y, xs])
break
xs += 1
xs = x - 1
while xs >= 0:
if self.disparity_left[y, xs] != self.invalid_disparity:
left_planes.append(self.plane_left[y, xs])
break
xs -= 1
if len(left_planes) == 1:
self.disparity_left[y, x] = left_planes[0].to_disparity(x=x, y=y)
elif len(left_planes) > 1:
d0 = left_planes[0].to_disparity(x=x, y=y)
d1 = left_planes[1].to_disparity(x=x, y=y)
self.disparity_left[y, x] = min(abs(d0), abs(d1))
for i in range(len(self.mistakes_right)):
right_planes = list()
x, y = self.mistakes_right[i]
xs = x + 1
while xs < self.width:
if self.disparity_right[y, xs] != self.invalid_disparity:
right_planes.append(self.plane_right[y, xs])
break
xs += 1
xs = x - 1
while xs >= 0:
if self.disparity_right[y, xs] != self.invalid_disparity:
right_planes.append(self.plane_right[y, xs])
break
xs -= 1
if len(right_planes) == 1:
self.disparity_right[y, x] = right_planes[0].to_disparity(x=x, y=y)
elif len(right_planes) > 1:
d0 = right_planes[0].to_disparity(x=x, y=y)
d1 = right_planes[1].to_disparity(x=x, y=y)
self.disparity_right[y, x] = min(abs(d0), abs(d1))
@timer("Get disparity map")
def get_disparity_map(self, view=0, norm=False):
return self._get_disparity_map(view=view, norm=norm)
def _get_disparity_map(self, view=0, norm=False):
if view == 0:
disparity = self.disparity_left.copy()
else:
disparity = self.disparity_right.copy()
if norm:
disparity = np.clip(disparity, self.config.min_disparity, self.config.max_disparity)
disparity = disparity / (self.config.max_disparity - self.config.min_disparity) * 255
return disparity
@timer("Get disparity cloud")
def get_disparity_cloud(self, baseline, focal_length, principal_point_left, principal_point_right):
b = baseline
f = focal_length
l_x, l_y = principal_point_left
r_x, r_y = principal_point_right
cloud = list()
for y in range(self.height):
for x in range(self.width):
disp = np.abs(self._get_disparity_map(view=0)[y, x])
z_ = b * f / (disp + (r_x - l_x))
x_ = z_ * (x - l_x) / f
y_ = z_ * (y - l_y) / f
cloud.append([x_, y_, z_])
return cloud
if __name__ == "__main__":
import cv2
left = cv2.imread("images/pms_0_left.png")
right = cv2.imread("images/pms_0_right.png")
config_ = PMSConfig("config.json")
height_, width_ = left.shape[0], left.shape[1]
p = PatchMatchStereo(height=height_, width=width_, config=config_)
p.match(image_left=left, image_right=right)
disparity_ = p.get_disparity_map(view=0, norm=True)
cv2.imwrite("./images/pms_0_disparity.png", disparity_)
cloud = p.get_disparity_cloud(
baseline=193.001,
focal_length=999.421,
principal_point_left=(294.182, 252.932),
principal_point_right=(326.95975, 252.932)
)
with open("./images/pms_0_clouds.txt", "w") as f:
for c in cloud:
f.write(" ".join([str(i) for i in c]) + "\n")
| [
"from functools import wraps\nfrom abc import abstractmethod\nimport time\nimport json\nimport random\nimport numpy as np\n\n\ndef timer(pre_str=None):\n def timed(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n start_time = time.time()\n res = func(*args, **kwargs)\n print_srt = pre_str or func.__name__\n print(f\"| {print_srt} cost {time.time() - start_time:.3f} seconds.\")\n return res\n\n return wrapped\n\n return timed\n\n\nclass PMSConfig:\n def __init__(self, path):\n self.path = path\n with open(path, \"r\") as f:\n self.config = json.load(f)\n for k, v in self.config.items():\n setattr(self, k, v)\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f\"{type(self)} and {type(other)} could not multiply.\")\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f\"{type(self)} and {type(other)} could not add.\")\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f\"{type(self)} and {type(other)} could not sub.\")\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f\"{type(self)} and {type(other)} could not compare.\")\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n def __init__(self, x: int = 0, y: int = 0, d: int = 0, n: PVector3f = None, p: PVector3f = None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z - self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(f\"{type(self)} and {type(other)} could not compare.\")\n return self.p == other.p\n\n\nclass CostComputer:\n def __init__(self, image_left, image_right, width, height, patch_size, min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError(\"Compute should be implement.\")\n\n\nclass CostComputerPMS(CostComputer):\n def __init__(self, image_left, image_right, grad_left, grad_right, width, height, patch_size, min_disparity,\n max_disparity, gamma, alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left, image_right=image_right,\n width=width, height=height, patch_size=patch_size,\n min_disparity=min_disparity, max_disparity=max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n\n col_p = col_p if col_p is not None else self.get_color(self.image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.width - 1:\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n # w = np.exp(-dc / self.gamma)\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q, grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n def __init__(self, image_left, image_right, width, height, grad_left, grad_right,\n plane_left, plane_right, config, cost_left, cost_right, disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right, grad_left, grad_right, width, height,\n config.patch_size, config.min_disparity, config.max_disparity,\n config.gamma, config.alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left, grad_right, grad_left, width, height,\n config.patch_size, -config.max_disparity, -config.min_disparity,\n config.gamma, config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f\"\\r| Propagation iter {curr_iter}: 0\", end=\"\")\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(f\"\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_/times_:.3f} it/s\", end=\"\")\n y += direction\n print(f\"\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.\")\n\n def compute_cost_data(self):\n print(f\"\\r| Init cost {0} / {self.height * self.width}\", end=\"\")\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x, y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(f\"\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_/times_:.3f} it/s\", end=\"\")\n print(f\"\\r| Initialize cost {times_:.3f} seconds.\")\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(\n x=np.random.uniform(-1.0, 1.0) * norm_update,\n y=np.random.uniform(-1.0, 1.0) * norm_update,\n z=np.random.uniform(-1.0, 1.0) * norm_update,\n )\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer(\"Initialize memory\")\n def init(self, h, w):\n self.width = w\n self.height = h\n\n self.disparity_range = self.config.max_disparity - self.config.min_disparity\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer(\"Initialize parameters\")\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n # random disparity\n disp_l = np.random.uniform(float(self.config.min_disparity), float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity), float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x] = disp_l, disp_r\n\n # random normal vector\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x=0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(\n x=np.random.uniform(-1.0, 1.0),\n y=np.random.uniform(-1.0, 1.0),\n z=np.random.uniform(-1.0, 1.0),\n )\n norm_r = PVector3f(\n x=np.random.uniform(-1.0, 1.0),\n y=np.random.uniform(-1.0, 1.0),\n z=np.random.uniform(-1.0, 1.0),\n )\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n\n # random disparity plane\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l, n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r, n=norm_r)\n\n @timer(\"Plane to disparity\")\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x].to_disparity(x=x, y=y)\n\n @timer(\"Total match\")\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer(\"Propagation\")\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self.width, self.height,\n self.grad_left, self.grad_right, self.plane_left, self.plane_right,\n config_left, self.cost_left, self.cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left, self.width, self.height,\n self.grad_right, self.grad_left, self.plane_right, self.plane_left,\n config_right, self.cost_right, self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer(\"Initialize gray\")\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer(\"Initialize gradient\")\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - 1, x - 1] \\\n + 2 * self.gray_left[y, x + 1] - 2 * self.gray_left[y, x - 1] \\\n + self.gray_left[y + 1, x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - 1, x - 1] \\\n + 2 * self.gray_left[y + 1, x] - 2 * self.gray_left[y - 1, x] \\\n + self.gray_left[y + 1, x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y - 1, x - 1] \\\n + 2 * self.gray_right[y, x + 1] - 2 * self.gray_right[y, x - 1] \\\n + self.gray_right[y + 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y - 1, x - 1] \\\n + 2 * self.gray_right[y + 1, x] - 2 * self.gray_right[y - 1, x] \\\n + self.gray_right[y + 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer(\"LR check\")\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer(\"Fill holes\")\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x, y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x=x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer(\"Get disparity map\")\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.config.min_disparity) * 255\n return disparity\n\n @timer(\"Get disparity cloud\")\n def get_disparity_cloud(self, baseline, focal_length, principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\nif __name__ == \"__main__\":\n import cv2\n\n left = cv2.imread(\"images/pms_0_left.png\")\n right = cv2.imread(\"images/pms_0_right.png\")\n config_ = PMSConfig(\"config.json\")\n\n height_, width_ = left.shape[0], left.shape[1]\n p = PatchMatchStereo(height=height_, width=width_, config=config_)\n p.match(image_left=left, image_right=right)\n disparity_ = p.get_disparity_map(view=0, norm=True)\n cv2.imwrite(\"./images/pms_0_disparity.png\", disparity_)\n\n cloud = p.get_disparity_cloud(\n baseline=193.001,\n focal_length=999.421,\n principal_point_left=(294.182, 252.932),\n principal_point_right=(326.95975, 252.932)\n )\n with open(\"./images/pms_0_clouds.txt\", \"w\") as f:\n for c in cloud:\n f.write(\" \".join([str(i) for i in c]) + \"\\n\")\n",
"from functools import wraps\nfrom abc import abstractmethod\nimport time\nimport json\nimport random\nimport numpy as np\n\n\ndef timer(pre_str=None):\n\n def timed(func):\n\n @wraps(func)\n def wrapped(*args, **kwargs):\n start_time = time.time()\n res = func(*args, **kwargs)\n print_srt = pre_str or func.__name__\n print(f'| {print_srt} cost {time.time() - start_time:.3f} seconds.'\n )\n return res\n return wrapped\n return timed\n\n\nclass PMSConfig:\n\n def __init__(self, path):\n self.path = path\n with open(path, 'r') as f:\n self.config = json.load(f)\n for k, v in self.config.items():\n setattr(self, k, v)\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\nif __name__ == '__main__':\n import cv2\n left = cv2.imread('images/pms_0_left.png')\n right = cv2.imread('images/pms_0_right.png')\n config_ = PMSConfig('config.json')\n height_, width_ = left.shape[0], left.shape[1]\n p = PatchMatchStereo(height=height_, width=width_, config=config_)\n p.match(image_left=left, image_right=right)\n disparity_ = p.get_disparity_map(view=0, norm=True)\n cv2.imwrite('./images/pms_0_disparity.png', disparity_)\n cloud = p.get_disparity_cloud(baseline=193.001, focal_length=999.421,\n principal_point_left=(294.182, 252.932), principal_point_right=(\n 326.95975, 252.932))\n with open('./images/pms_0_clouds.txt', 'w') as f:\n for c in cloud:\n f.write(' '.join([str(i) for i in c]) + '\\n')\n",
"<import token>\n\n\ndef timer(pre_str=None):\n\n def timed(func):\n\n @wraps(func)\n def wrapped(*args, **kwargs):\n start_time = time.time()\n res = func(*args, **kwargs)\n print_srt = pre_str or func.__name__\n print(f'| {print_srt} cost {time.time() - start_time:.3f} seconds.'\n )\n return res\n return wrapped\n return timed\n\n\nclass PMSConfig:\n\n def __init__(self, path):\n self.path = path\n with open(path, 'r') as f:\n self.config = json.load(f)\n for k, v in self.config.items():\n setattr(self, k, v)\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\nif __name__ == '__main__':\n import cv2\n left = cv2.imread('images/pms_0_left.png')\n right = cv2.imread('images/pms_0_right.png')\n config_ = PMSConfig('config.json')\n height_, width_ = left.shape[0], left.shape[1]\n p = PatchMatchStereo(height=height_, width=width_, config=config_)\n p.match(image_left=left, image_right=right)\n disparity_ = p.get_disparity_map(view=0, norm=True)\n cv2.imwrite('./images/pms_0_disparity.png', disparity_)\n cloud = p.get_disparity_cloud(baseline=193.001, focal_length=999.421,\n principal_point_left=(294.182, 252.932), principal_point_right=(\n 326.95975, 252.932))\n with open('./images/pms_0_clouds.txt', 'w') as f:\n for c in cloud:\n f.write(' '.join([str(i) for i in c]) + '\\n')\n",
"<import token>\n\n\ndef timer(pre_str=None):\n\n def timed(func):\n\n @wraps(func)\n def wrapped(*args, **kwargs):\n start_time = time.time()\n res = func(*args, **kwargs)\n print_srt = pre_str or func.__name__\n print(f'| {print_srt} cost {time.time() - start_time:.3f} seconds.'\n )\n return res\n return wrapped\n return timed\n\n\nclass PMSConfig:\n\n def __init__(self, path):\n self.path = path\n with open(path, 'r') as f:\n self.config = json.load(f)\n for k, v in self.config.items():\n setattr(self, k, v)\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\nclass PMSConfig:\n\n def __init__(self, path):\n self.path = path\n with open(path, 'r') as f:\n self.config = json.load(f)\n for k, v in self.config.items():\n setattr(self, k, v)\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\nclass PMSConfig:\n <function token>\n\n def clone(self):\n return PMSConfig(self.path)\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\nclass PMSConfig:\n <function token>\n <function token>\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n\n def __mul__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not multiply.')\n return self.x * other.x + self.y * other.y + self.z * other.z\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n\n def __eq__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.x == other.x and self.y == other.y and self.z == other.z\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n\n def __init__(self, x: float, y: float, z: float):\n self.x = float(x)\n self.y = float(y)\n self.z = float(z)\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n <function token>\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n\n def __sub__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not sub.')\n return PVector3f(self.x - other.x, self.y - other.y, self.z - other.z)\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n <function token>\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n\n def __add__(self, other):\n if not isinstance(other, PVector3f):\n raise TypeError(f'{type(self)} and {type(other)} could not add.')\n return PVector3f(self.x + other.x, self.y + other.y, self.z + other.z)\n <function token>\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n <function token>\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n <function token>\n <function token>\n\n def __invert__(self):\n return PVector3f(-self.x, -self.y, -self.z)\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n <function token>\n\n def normalize(self):\n sqf = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5\n self.x /= sqf\n self.y /= sqf\n self.z /= sqf\n return self\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n\n\nclass PVector3f:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n\n def __init__(self, x: int=0, y: int=0, d: int=0, n: PVector3f=None, p:\n PVector3f=None):\n if p is None:\n x, y, z = -n.x / n.z, -n.y / n.z, (n.x * x + n.y * y + n.z * d\n ) / n.z\n self.p = PVector3f(x, y, z)\n else:\n self.p = PVector3f(p.x, p.y, p.z)\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n <function token>\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n\n def to_another_view(self, x: int, y: int):\n d = self.to_disparity(x, y)\n return DisparityPlane(p=PVector3f(-self.p.x, -self.p.y, -self.p.z -\n self.p.x * d))\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n <function token>\n\n def to_disparity(self, x: int, y: int):\n return self.p * PVector3f(x, y, 1)\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n <function token>\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n <function token>\n <function token>\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n <function token>\n\n def __eq__(self, other):\n if not isinstance(other, DisparityPlane):\n raise TypeError(\n f'{type(self)} and {type(other)} could not compare.')\n return self.p == other.p\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n <function token>\n <function token>\n\n def to_norm(self):\n return PVector3f(self.p.x, self.p.y, -1).normalize()\n <function token>\n <function token>\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n\n\nclass DisparityPlane:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputer:\n\n def __init__(self, image_left, image_right, width, height, patch_size,\n min_disparity, max_disparity):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.patch_size = patch_size\n self.min_disparity = min_disparity\n self.max_disparity = max_disparity\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputer:\n <function token>\n\n @staticmethod\n def fast_exp(v: float):\n v = 1 + v / 1024\n for _ in range(10):\n v *= v\n return v\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputer:\n <function token>\n <function token>\n\n @abstractmethod\n def compute(self, x, y, d, *args, **kwargs):\n raise NotImplementedError('Compute should be implement.')\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputer:\n <function token>\n <function token>\n <function token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n\n def get_gradient(self, gradient, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n g1 = gradient[y, x1]\n g2 = gradient[y, x2] if x2 < self.width else g1\n x_ = (1 - ofs) * g1[0] + ofs * g2[0]\n y_ = (1 - ofs) * g1[1] + ofs * g2[1]\n return [x_, y_]\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n\n def compute_agg(self, x, y, p: DisparityPlane):\n pat = self.patch_size // 2\n col_p = self.image_left[y, x, :]\n cost = 0\n for r in range(-pat, pat, 1):\n y_ = y + r\n for c in range(-pat, pat, 1):\n x_ = x + c\n if (y_ < 0 or y_ > self.height - 1 or x_ < 0 or x_ > self.\n width - 1):\n continue\n d = p.to_disparity(x=x, y=y)\n if d < self.min_disparity or d > self.max_disparity:\n cost += 120.0\n continue\n col_q = self.image_left[y_, x_, :]\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in\n range(3)])\n w = self.fast_exp(-dc / self.gamma)\n grad_q = self.grad_left[y_, x_]\n cost += w * self.compute(x=x_, y=y_, d=d, col_p=col_q,\n grad_p=grad_q)\n return cost\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n <function token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n\n def compute(self, x=0.0, y=0, d=0.0, col_p=None, grad_p=None):\n xr = x - d\n if xr < 0 or xr > self.width:\n return (1 - self.alpha) * self.tau_col + self.alpha * self.tau_grad\n col_p = col_p if col_p is not None else self.get_color(self.\n image_left, x=x, y=y)\n col_q = self.get_color(self.image_right, x=xr, y=y)\n dc = sum([abs(float(col_p[i]) - float(col_q[i])) for i in range(3)])\n dc = min(dc, self.tau_col)\n grad_p = grad_p if grad_p is not None else self.get_gradient(self.\n grad_left, x=x, y=y)\n grad_q = self.get_gradient(self.grad_right, x=xr, y=y)\n dg = abs(grad_p[0] - grad_q[0]) + abs(grad_p[1] - grad_q[1])\n dg = min(dg, self.tau_grad)\n return (1 - self.alpha) * dc + self.alpha * dg\n <function token>\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n <function token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n <function token>\n <function token>\n\n def get_color(self, image, x: float, y: int):\n x1 = int(np.floor(x))\n x2 = int(np.ceil(x))\n ofs = x - x1\n color = list()\n for i in range(3):\n g1 = image[y, x1, i]\n g2 = image[y, x2, i] if x2 < self.width else g1\n color.append((1 - ofs) * g1 + ofs * g2)\n return color\n <function token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n\n def __init__(self, image_left, image_right, grad_left, grad_right,\n width, height, patch_size, min_disparity, max_disparity, gamma,\n alpha, tau_col, tau_grad):\n super(CostComputerPMS, self).__init__(image_left=image_left,\n image_right=image_right, width=width, height=height, patch_size\n =patch_size, min_disparity=min_disparity, max_disparity=\n max_disparity)\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.gamma = gamma\n self.alpha = alpha\n self.tau_col = tau_col\n self.tau_grad = tau_grad\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostComputerPMS(CostComputer):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n\n def plane_refine(self, x, y):\n min_disp = self.config.min_disparity\n max_disp = self.config.max_disparity\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n norm_p = plane_p.to_norm()\n disp_update = (max_disp - min_disp) / 2.0\n norm_update = 1.0\n stop_thres = 0.1\n while disp_update > stop_thres:\n disp_rd = np.random.uniform(-1.0, 1.0) * disp_update\n if self.config.is_integer_disparity:\n disp_rd = int(disp_rd)\n d_p_new = d_p + disp_rd\n if d_p_new < min_disp or d_p_new > max_disp:\n disp_update /= 2\n norm_update /= 2\n continue\n if not self.config.is_force_fpw:\n norm_rd = PVector3f(x=np.random.uniform(-1.0, 1.0) *\n norm_update, y=np.random.uniform(-1.0, 1.0) *\n norm_update, z=np.random.uniform(-1.0, 1.0) * norm_update)\n while norm_rd.z == 0.0:\n norm_rd.z = np.random.uniform(-1.0, 1.0)\n else:\n norm_rd = PVector3f(x=0.0, y=0.0, z=0.0)\n norm_p_new = norm_p + norm_rd\n norm_p_new.normalize()\n plane_new = DisparityPlane(x=x, y=y, d=d_p_new, n=norm_p_new)\n if plane_new != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane_new)\n if cost < cost_p:\n plane_p = plane_new\n cost_p = cost\n d_p = d_p_new\n norm_p = norm_p_new\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n disp_update /= 2.0\n norm_update /= 2.0\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n\n def view_propagation(self, x, y):\n plane_p = self.plane_left[y, x]\n d_p = plane_p.to_disparity(x=x, y=y)\n xr = int(x - d_p)\n if xr < 0 or xr > self.width - 1:\n return\n plane_q = self.plane_right[y, xr]\n cost_q = self.cost_right[y, xr]\n plane_p2q = plane_p.to_another_view(x=x, y=y)\n d_q = plane_p2q.to_disparity(x=xr, y=y)\n cost = self.cost_cpt_right.compute_agg(x=xr, y=y, p=plane_p2q)\n if cost < cost_q:\n plane_q = plane_p2q\n cost_q = cost\n self.plane_right[y, xr] = plane_q\n self.cost_right[y, xr] = cost_q\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n\n def compute_cost_data(self):\n print(f'\\r| Init cost {0} / {self.height * self.width}', end='')\n count_ = 0\n times_ = 0\n for y in range(self.height):\n for x in range(self.width):\n start_ = time.time()\n p = self.plane_left[y, x]\n self.cost_left[y, x] = self.cost_cpt_left.compute_agg(x=x,\n y=y, p=p)\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Initialize cost [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n print(f'\\r| Initialize cost {times_:.3f} seconds.')\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n <function token>\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n\n def do_propagation(self, curr_iter):\n direction = 1 if curr_iter % 2 == 0 else -1\n y = 0 if curr_iter % 2 == 0 else self.height - 1\n count_ = 0\n times_ = 0\n print(f'\\r| Propagation iter {curr_iter}: 0', end='')\n for i in range(self.height):\n x = 0 if curr_iter % 2 == 0 else self.width - 1\n for j in range(self.width):\n start_ = time.time()\n self.spatial_propagation(x=x, y=y, direction=direction)\n if not self.config.is_force_fpw:\n self.plane_refine(x=x, y=y)\n self.view_propagation(x=x, y=y)\n x += direction\n times_ += time.time() - start_\n count_ += 1\n print(\n f'\\r| Propagation iter {curr_iter}: [{y * self.width + x + 1} / {self.height * self.width}] {times_:.0f}s/{times_ / count_ * (self.width * self.height - count_):.0f}s, {count_ / times_:.3f} it/s'\n , end='')\n y += direction\n print(f'\\r| Propagation iter {curr_iter} cost {times_:.3f} seconds.')\n <function token>\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n <function token>\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n <function token>\n <function token>\n\n def spatial_propagation(self, x, y, direction):\n plane_p = self.plane_left[y, x]\n cost_p = self.cost_left[y, x]\n xd = x - direction\n if 0 <= xd < self.width:\n plane = self.plane_left[y, xd]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n yd = y - direction\n if 0 <= yd < self.height:\n plane = self.plane_left[yd, x]\n if plane != plane_p:\n cost = self.cost_cpt_left.compute_agg(x=x, y=y, p=plane)\n if cost < cost_p:\n plane_p = plane\n cost_p = cost\n self.plane_left[y, x] = plane_p\n self.cost_left[y, x] = cost_p\n <function token>\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n\n def __init__(self, image_left, image_right, width, height, grad_left,\n grad_right, plane_left, plane_right, config, cost_left, cost_right,\n disparity_map):\n self.image_left = image_left\n self.image_right = image_right\n self.width = width\n self.height = height\n self.grad_left = grad_left\n self.grad_right = grad_right\n self.plane_left = plane_left\n self.plane_right = plane_right\n self.config = config\n self.cost_left = cost_left\n self.cost_right = cost_right\n self.disparity_map = disparity_map\n self.cost_cpt_left = CostComputerPMS(image_left, image_right,\n grad_left, grad_right, width, height, config.patch_size, config\n .min_disparity, config.max_disparity, config.gamma, config.\n alpha, config.tau_col, config.tau_grad)\n self.cost_cpt_right = CostComputerPMS(image_right, image_left,\n grad_right, grad_left, width, height, config.patch_size, -\n config.max_disparity, -config.min_disparity, config.gamma,\n config.alpha, config.tau_col, config.tau_grad)\n self.compute_cost_data()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PropagationPMS:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n\n @timer('Get disparity cloud')\n def get_disparity_cloud(self, baseline, focal_length,\n principal_point_left, principal_point_right):\n b = baseline\n f = focal_length\n l_x, l_y = principal_point_left\n r_x, r_y = principal_point_right\n cloud = list()\n for y in range(self.height):\n for x in range(self.width):\n disp = np.abs(self._get_disparity_map(view=0)[y, x])\n z_ = b * f / (disp + (r_x - l_x))\n x_ = z_ * (x - l_x) / f\n y_ = z_ * (y - l_y) / f\n cloud.append([x_, y_, z_])\n return cloud\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n\n @timer('Fill holes')\n def fill_holes_in_disparity_map(self):\n for i in range(len(self.mistakes_left)):\n left_planes = list()\n x, y = self.mistakes_left[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_left[y, xs] != self.invalid_disparity:\n left_planes.append(self.plane_left[y, xs])\n break\n xs -= 1\n if len(left_planes) == 1:\n self.disparity_left[y, x] = left_planes[0].to_disparity(x=x,\n y=y)\n elif len(left_planes) > 1:\n d0 = left_planes[0].to_disparity(x=x, y=y)\n d1 = left_planes[1].to_disparity(x=x, y=y)\n self.disparity_left[y, x] = min(abs(d0), abs(d1))\n for i in range(len(self.mistakes_right)):\n right_planes = list()\n x, y = self.mistakes_right[i]\n xs = x + 1\n while xs < self.width:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs += 1\n xs = x - 1\n while xs >= 0:\n if self.disparity_right[y, xs] != self.invalid_disparity:\n right_planes.append(self.plane_right[y, xs])\n break\n xs -= 1\n if len(right_planes) == 1:\n self.disparity_right[y, x] = right_planes[0].to_disparity(x\n =x, y=y)\n elif len(right_planes) > 1:\n d0 = right_planes[0].to_disparity(x=x, y=y)\n d1 = right_planes[1].to_disparity(x=x, y=y)\n self.disparity_right[y, x] = min(abs(d0), abs(d1))\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n\n @timer('Total match')\n def match(self, image_left, image_right):\n self.image_left, self.image_right = image_left, image_right\n self.random_init()\n self.compute_gray()\n self.compute_gradient()\n self.propagation()\n self.plane_to_disparity()\n if self.config.is_check_lr:\n self.lr_check()\n if self.config.is_fill_holes:\n self.fill_holes_in_disparity_map()\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n <function token>\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n\n @timer('Initialize gradient')\n def compute_gradient(self):\n for y in range(1, self.height - 1, 1):\n for x in range(1, self.width - 1, 1):\n grad_x = self.gray_left[y - 1, x + 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y, x + 1\n ] - 2 * self.gray_left[y, x - 1] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y + 1, x - 1]\n grad_y = self.gray_left[y + 1, x - 1] - self.gray_left[y - \n 1, x - 1] + 2 * self.gray_left[y + 1, x\n ] - 2 * self.gray_left[y - 1, x] + self.gray_left[y + 1,\n x + 1] - self.gray_left[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_left[y, x, 0] = grad_x\n self.grad_left[y, x, 1] = grad_y\n grad_x = self.gray_right[y - 1, x + 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y, x + 1\n ] - 2 * self.gray_right[y, x - 1] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y + 1, x - 1]\n grad_y = self.gray_right[y + 1, x - 1] - self.gray_right[y -\n 1, x - 1] + 2 * self.gray_right[y + 1, x\n ] - 2 * self.gray_right[y - 1, x] + self.gray_right[y +\n 1, x + 1] - self.gray_right[y - 1, x + 1]\n grad_y, grad_x = grad_y / 8, grad_x / 8\n self.grad_right[y, x, 0] = grad_x\n self.grad_right[y, x, 1] = grad_y\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n <function token>\n\n @timer('Propagation')\n def propagation(self):\n config_left = self.config.clone()\n config_right = self.config.clone()\n config_right.min_disparity = -config_left.max_disparity\n config_right.max_disparity = -config_left.min_disparity\n propa_left = PropagationPMS(self.image_left, self.image_right, self\n .width, self.height, self.grad_left, self.grad_right, self.\n plane_left, self.plane_right, config_left, self.cost_left, self\n .cost_right, self.disparity_left)\n propa_right = PropagationPMS(self.image_right, self.image_left,\n self.width, self.height, self.grad_right, self.grad_left, self.\n plane_right, self.plane_left, config_right, self.cost_right,\n self.cost_left, self.disparity_right)\n for it in range(self.config.n_iter):\n propa_left.do_propagation(curr_iter=it)\n propa_right.do_propagation(curr_iter=it)\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n <function token>\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n <function token>\n <function token>\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n <function token>\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n\n @timer('Get disparity map')\n def get_disparity_map(self, view=0, norm=False):\n return self._get_disparity_map(view=view, norm=norm)\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n\n @timer('Plane to disparity')\n def plane_to_disparity(self):\n for y in range(self.height):\n for x in range(self.width):\n self.disparity_left[y, x] = self.plane_left[y, x].to_disparity(\n x=x, y=y)\n self.disparity_right[y, x] = self.plane_right[y, x\n ].to_disparity(x=x, y=y)\n <function token>\n <function token>\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n <function token>\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n <function token>\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n <function token>\n <function token>\n <function token>\n\n @timer('Initialize gray')\n def compute_gray(self):\n for y in range(self.height):\n for x in range(self.width):\n b, g, r = self.image_left[y, x]\n self.gray_left[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n b, g, r = self.image_right[y, x]\n self.gray_right[y, x] = int(r * 0.299 + g * 0.587 + b * 0.114)\n <function token>\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n <function token>\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @timer('LR check')\n def lr_check(self):\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_left[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_left.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_right[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n else:\n self.disparity_left[y, x] = self.invalid_disparity\n self.mistakes_left.append([x, y])\n for y in range(self.height):\n for x in range(self.width):\n disp = self.disparity_right[y, x]\n if disp == self.invalid_disparity:\n self.mistakes_right.append([x, y])\n continue\n col_right = round(x - disp)\n if 0 <= col_right < self.width:\n disp_r = self.disparity_left[y, col_right]\n if abs(disp + disp_r) > self.config.lr_check_threshold:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n else:\n self.disparity_right[y, x] = self.invalid_disparity\n self.mistakes_right.append([x, y])\n <function token>\n <function token>\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def _get_disparity_map(self, view=0, norm=False):\n if view == 0:\n disparity = self.disparity_left.copy()\n else:\n disparity = self.disparity_right.copy()\n if norm:\n disparity = np.clip(disparity, self.config.min_disparity, self.\n config.max_disparity)\n disparity = disparity / (self.config.max_disparity - self.\n config.min_disparity) * 255\n return disparity\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n\n @timer('Initialize parameters')\n def random_init(self):\n for y in range(self.height):\n for x in range(self.width):\n disp_l = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n disp_r = np.random.uniform(float(self.config.min_disparity),\n float(self.config.max_disparity))\n if self.config.is_integer_disparity:\n disp_l, disp_r = int(disp_l), int(disp_r)\n self.disparity_left[y, x], self.disparity_right[y, x\n ] = disp_l, disp_r\n norm_l, norm_r = PVector3f(x=0.0, y=0.0, z=1.0), PVector3f(x\n =0.0, y=0.0, z=1.0)\n if not self.config.is_force_fpw:\n norm_l = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n norm_r = PVector3f(x=np.random.uniform(-1.0, 1.0), y=np\n .random.uniform(-1.0, 1.0), z=np.random.uniform(-\n 1.0, 1.0))\n while norm_l.z == 0.0:\n norm_l.z = np.random.uniform(-1.0, 1.0)\n while norm_r.z == 0.0:\n norm_r.z = np.random.uniform(-1.0, 1.0)\n norm_l, norm_r = norm_l.normalize(), norm_r.normalize()\n self.plane_left[y, x] = DisparityPlane(x=x, y=y, d=disp_l,\n n=norm_l)\n self.plane_right[y, x] = DisparityPlane(x=x, y=y, d=disp_r,\n n=norm_r)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n\n def __init__(self, width, height, config, random_seed=2021):\n self.random_seed = random_seed\n random.seed(random_seed)\n np.random.seed(random_seed)\n self.image_left = None\n self.image_right = None\n self.width = width\n self.height = height\n self.config = config\n self.disparity_range = config.max_disparity - config.min_disparity\n self.gray_left = None\n self.gray_right = None\n self.grad_left = None\n self.grad_right = None\n self.cost_left = None\n self.cost_right = None\n self.disparity_left = None\n self.disparity_right = None\n self.plane_left = None\n self.plane_right = None\n self.mistakes_left = None\n self.mistakes_right = None\n self.invalid_disparity = 1024.0\n self.init(h=height, w=width)\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n <function token>\n\n @timer('Initialize memory')\n def init(self, h, w):\n self.width = w\n self.height = h\n self.disparity_range = (self.config.max_disparity - self.config.\n min_disparity)\n self.gray_left = np.zeros([self.height, self.width], dtype=int)\n self.gray_right = np.zeros([self.height, self.width], dtype=int)\n self.grad_left = np.zeros([self.height, self.width, 2], dtype=float)\n self.grad_right = np.zeros([self.height, self.width, 2], dtype=float)\n self.cost_left = np.zeros([self.height, self.width], dtype=float)\n self.cost_right = np.zeros([self.height, self.width], dtype=float)\n self.disparity_left = np.zeros([self.height, self.width], dtype=float)\n self.disparity_right = np.zeros([self.height, self.width], dtype=float)\n self.plane_left = np.zeros([self.height, self.width], dtype=object)\n self.plane_right = np.zeros([self.height, self.width], dtype=object)\n self.mistakes_left = list()\n self.mistakes_right = list()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass PatchMatchStereo:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<code token>\n"
] | false |
99,739 | 4afac9fd26c7d4007f76736656a1fc9708f537a6 | def find_anagrams(word, candidates):
ret_list = []
word_list = list(word.lower())
word_list.sort()
for i in candidates:
comp_list = list(i.lower())
comp_list.sort()
if word_list == comp_list:
if word.lower() != i.lower():
ret_list.append(i)
return ret_list
| [
"def find_anagrams(word, candidates):\n ret_list = []\n word_list = list(word.lower())\n word_list.sort()\n for i in candidates:\n comp_list = list(i.lower())\n comp_list.sort()\n if word_list == comp_list:\n if word.lower() != i.lower():\n ret_list.append(i)\n return ret_list\n",
"<function token>\n"
] | false |
99,740 | ed1d7e8b6bc01b8ad20904764341eaf63bba450a | /usr/lib/python3.9/heapq.py | [
"/usr/lib/python3.9/heapq.py"
] | true |
99,741 | 778f170f678fbf09592eb5e78520e4fec2f1398e | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
size = len(arr)
first = 0
second = 0
f=[]
s=[]
for i in range(size):
for j in range(size):
if i == j:
first += arr[i][j]
f.append(arr[i][j])
second += arr[-i-1][j]
s.append(arr[-i-1][j])
print(f)
print(s)
print('{} + {}'.format(str(first), str(second)))
result = abs(first-second)
print(str(result))
return result
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
#fptr.write(str(result) + '\n')
#fptr.close()
| [
"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'diagonalDifference' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts 2D_INTEGER_ARRAY arr as parameter.\n#\n\ndef diagonalDifference(arr):\n size = len(arr)\n first = 0\n second = 0\n f=[]\n s=[]\n for i in range(size):\n for j in range(size): \n if i == j:\n first += arr[i][j]\n f.append(arr[i][j])\n second += arr[-i-1][j] \n s.append(arr[-i-1][j])\n print(f)\n print(s)\n print('{} + {}'.format(str(first), str(second)))\n result = abs(first-second)\n print(str(result))\n return result\n\nif __name__ == '__main__':\n #fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n arr = []\n\n for _ in range(n):\n arr.append(list(map(int, input().rstrip().split())))\n\n result = diagonalDifference(arr)\n\n #fptr.write(str(result) + '\\n')\n\n #fptr.close()\n",
"import math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef diagonalDifference(arr):\n size = len(arr)\n first = 0\n second = 0\n f = []\n s = []\n for i in range(size):\n for j in range(size):\n if i == j:\n first += arr[i][j]\n f.append(arr[i][j])\n second += arr[-i - 1][j]\n s.append(arr[-i - 1][j])\n print(f)\n print(s)\n print('{} + {}'.format(str(first), str(second)))\n result = abs(first - second)\n print(str(result))\n return result\n\n\nif __name__ == '__main__':\n n = int(input().strip())\n arr = []\n for _ in range(n):\n arr.append(list(map(int, input().rstrip().split())))\n result = diagonalDifference(arr)\n",
"<import token>\n\n\ndef diagonalDifference(arr):\n size = len(arr)\n first = 0\n second = 0\n f = []\n s = []\n for i in range(size):\n for j in range(size):\n if i == j:\n first += arr[i][j]\n f.append(arr[i][j])\n second += arr[-i - 1][j]\n s.append(arr[-i - 1][j])\n print(f)\n print(s)\n print('{} + {}'.format(str(first), str(second)))\n result = abs(first - second)\n print(str(result))\n return result\n\n\nif __name__ == '__main__':\n n = int(input().strip())\n arr = []\n for _ in range(n):\n arr.append(list(map(int, input().rstrip().split())))\n result = diagonalDifference(arr)\n",
"<import token>\n\n\ndef diagonalDifference(arr):\n size = len(arr)\n first = 0\n second = 0\n f = []\n s = []\n for i in range(size):\n for j in range(size):\n if i == j:\n first += arr[i][j]\n f.append(arr[i][j])\n second += arr[-i - 1][j]\n s.append(arr[-i - 1][j])\n print(f)\n print(s)\n print('{} + {}'.format(str(first), str(second)))\n result = abs(first - second)\n print(str(result))\n return result\n\n\n<code token>\n",
"<import token>\n<function token>\n<code token>\n"
] | false |
99,742 | 2c09aa16f3f12c13f778e83187b391f5c2e21f1f | # Import Dependecies
from bs4 import BeautifulSoup as bs
from splinter import Browser
import pandas as pd
import requests
import time
# Initialize browser
def init_browser():
# Replace the path with your actual path to the chromedriver
# Windows Users
# executable_path = {'executable_path': '/Users/cantu/Desktop/Mission-to-Mars'}
# return Browser('chrome', **executable_path, headless=False)
exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}
return Browser('chrome', headless=True, **exec_path)
# Create Mission to Mars global dictionary that can be imported into Mongo
mars_info = {}
# NASA MARS NEWS
def scrape_mars_news():
try:
# Initialize browser
browser = init_browser()
#browser.is_element_present_by_css("div.content_title", wait_time=1)
# Visit Nasa news url through splinter module
url = 'https://mars.nasa.gov/news/'
browser.visit(url)
# HTML Object
html = browser.html
# Parse HTML with Beautiful Soup
soup = bs(html, 'html.parser')
# Retrieve the latest element that contains news title and news_paragraph
news_title = soup.find('div', class_='content_title').find('a').text
news_paragraph = soup.find('div', class_='article_teaser_body').text
# Dictionary entry from MARS NEWS
mars_info['news_title'] = news_title
mars_info['news_paragraph'] = news_paragraph
return mars_info
finally:
browser.quit()
# Featured images
def scrape_mars_image():
try:
# Initialize browser
browser = init_browser()
# Visit Mars Space Images through splinter module
image_url_featured = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
# Visit Mars Space Images through splinter module
browser.visit(image_url_featured)
# HTML Object
html_image = browser.html
# Parse HTML with Beautiful Soup
soup = bs(html_image, 'html.parser')
# Retrieve background-image url from style tag
featured_image_url = soup.find('article')['style'].replace(
'background-image: url(', '').replace(');', '')[1:-1]
# Website Url
main_url = 'https://www.jpl.nasa.gov'
# Concatenate website url with scrapped route
featured_image_url = main_url + featured_image_url
# Display full link to featured image
featured_image_url
# Dictionary entry from FEATURED IMAGE
mars_info['featured_image_url'] = featured_image_url
return mars_info
finally:
browser.quit()
# Mars Weather
def scrape_mars_weather():
try:
# Initialize browser
browser = init_browser()
#browser.is_element_present_by_css("div", wait_time=1)
# Visit Mars Weather Twitter through splinter module
weather_url = 'https://twitter.com/marswxreport?lang=en'
browser.visit(weather_url)
# HTML Object
html_weather = browser.html
# Parse HTML with Beautiful Soup
soup = bs(html_weather, 'html.parser')
# Find all elements that contain tweets
tweets = soup.find("ol", class_="stream-items")
# Find the src for the sloth image
mars_weather = tweets.find('p', class_="tweet-text").text
# Dictionary entry from WEATHER TWEET
mars_info['mars_weather'] = mars_weather
return mars_info
finally:
browser.quit()
# Mars Facts
def scrape_mars_facts():
try:
# Initialize browser
browser = init_browser()
# Visit Mars facts url
facts_url = 'http://space-facts.com/mars/'
# Use Panda's `read_html` to parse the url
mars_facts = pd.read_html(facts_url)
# Find the mars facts DataFrame in the list of DataFrames as assign it to `mars_df`
mars_df = mars_facts[0]
# Assign the columns `['Description', 'Value']`
mars_df.columns = ['Description', 'Value']
# Set the index to the `Description` column without row indexing
mars_df.set_index('Description', inplace=True)
# Save html code to folder Assets
data = mars_df.to_html()
# Dictionary entry from MARS FACTS
mars_info['mars_facts'] = data
return mars_info
finally:
browser.quit()
# def scrape_mars_hemisphere():
# try:
# browser = init_browser()
# hemispheres_url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
# browser.visit(hemispheres_url)
# html = browser.html
# soup = bs(html, "html.parser")
# mars_hemisphere = []
# products = soup.find("div", class_="result-list")
# hemispheres = products.find_all("div", class_="item")
# for hemisphere in hemispheres:
# title = hemisphere.find("h3").text
# title = title.replace("Enhanced", "")
# end_link = hemisphere.find("a")["href"]
# image_link = "https://astrogeology.usgs.gov/" + end_link
# browser.visit(image_link)
# html = browser.html
# soup = bs(html, "html.parser")
# downloads = soup.find("div", class_="downloads")
# image_url = downloads.find("a")["href"]
# mars_hemisphere.append({"title": title, "img_url": image_url})
# return mars_hemisphere
# finally:
# browser.quit()
print(scrape_mars_news())
print(scrape_mars_image())
print(scrape_mars_weather())
print(scrape_mars_facts())
#print(scrape_mars_hemisphere())
def return_scrape():
scrape_mars_news()
scrape_mars_image()
scrape_mars_weather()
scrape_mars_facts()
#scrape_mars_hemisphere()
return mars_info
# In[ ]:
| [
"# Import Dependecies\nfrom bs4 import BeautifulSoup as bs\nfrom splinter import Browser\nimport pandas as pd\nimport requests\nimport time\n# Initialize browser\n\ndef init_browser():\n # Replace the path with your actual path to the chromedriver\n\n # Windows Users\n # executable_path = {'executable_path': '/Users/cantu/Desktop/Mission-to-Mars'}\n # return Browser('chrome', **executable_path, headless=False)\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\n# Create Mission to Mars global dictionary that can be imported into Mongo\nmars_info = {}\n\n# NASA MARS NEWS\n\n\ndef scrape_mars_news():\n try:\n\n # Initialize browser\n browser = init_browser()\n\n #browser.is_element_present_by_css(\"div.content_title\", wait_time=1)\n\n # Visit Nasa news url through splinter module\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n\n # HTML Object\n html = browser.html\n\n # Parse HTML with Beautiful Soup\n soup = bs(html, 'html.parser')\n\n # Retrieve the latest element that contains news title and news_paragraph\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n\n # Dictionary entry from MARS NEWS\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n\n return mars_info\n\n finally:\n browser.quit()\n\n\n# Featured images\n\n\ndef scrape_mars_image():\n\n try:\n\n # Initialize browser\n browser = init_browser()\n\n # Visit Mars Space Images through splinter module\n image_url_featured = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n # Visit Mars Space Images through splinter module\n browser.visit(image_url_featured)\n\n # HTML Object\n html_image = browser.html\n\n # Parse HTML with Beautiful Soup\n soup = bs(html_image, 'html.parser')\n\n # Retrieve background-image url from style tag\n featured_image_url = soup.find('article')['style'].replace(\n 'background-image: url(', '').replace(');', '')[1:-1]\n\n # Website Url\n main_url = 'https://www.jpl.nasa.gov'\n\n # Concatenate website url with scrapped route\n featured_image_url = main_url + featured_image_url\n\n # Display full link to featured image\n featured_image_url\n\n # Dictionary entry from FEATURED IMAGE\n mars_info['featured_image_url'] = featured_image_url\n\n return mars_info\n finally:\n\n browser.quit()\n\n# Mars Weather\n\n\ndef scrape_mars_weather():\n\n try:\n\n # Initialize browser\n browser = init_browser()\n\n #browser.is_element_present_by_css(\"div\", wait_time=1)\n\n # Visit Mars Weather Twitter through splinter module\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n\n # HTML Object\n html_weather = browser.html\n\n # Parse HTML with Beautiful Soup\n soup = bs(html_weather, 'html.parser')\n\n # Find all elements that contain tweets\n tweets = soup.find(\"ol\", class_=\"stream-items\")\n# Find the src for the sloth image\n mars_weather = tweets.find('p', class_=\"tweet-text\").text\n\n # Dictionary entry from WEATHER TWEET\n mars_info['mars_weather'] = mars_weather\n\n return mars_info\n finally:\n browser.quit()\n\n\n# Mars Facts\ndef scrape_mars_facts():\n try:\n # Initialize browser\n browser = init_browser()\n # Visit Mars facts url\n facts_url = 'http://space-facts.com/mars/'\n\n# Use Panda's `read_html` to parse the url\n mars_facts = pd.read_html(facts_url)\n\n# Find the mars facts DataFrame in the list of DataFrames as assign it to `mars_df`\n mars_df = mars_facts[0]\n\n# Assign the columns `['Description', 'Value']`\n mars_df.columns = ['Description', 'Value']\n\n# Set the index to the `Description` column without row indexing\n mars_df.set_index('Description', inplace=True)\n\n# Save html code to folder Assets\n data = mars_df.to_html()\n\n# Dictionary entry from MARS FACTS\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n# def scrape_mars_hemisphere():\n\n# try:\n\n# browser = init_browser()\n# hemispheres_url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n# browser.visit(hemispheres_url)\n# html = browser.html\n# soup = bs(html, \"html.parser\")\n# mars_hemisphere = []\n\n# products = soup.find(\"div\", class_=\"result-list\")\n# hemispheres = products.find_all(\"div\", class_=\"item\")\n# for hemisphere in hemispheres:\n# title = hemisphere.find(\"h3\").text\n# title = title.replace(\"Enhanced\", \"\")\n# end_link = hemisphere.find(\"a\")[\"href\"]\n# image_link = \"https://astrogeology.usgs.gov/\" + end_link\n# browser.visit(image_link)\n# html = browser.html\n# soup = bs(html, \"html.parser\")\n# downloads = soup.find(\"div\", class_=\"downloads\")\n# image_url = downloads.find(\"a\")[\"href\"]\n# mars_hemisphere.append({\"title\": title, \"img_url\": image_url})\n# return mars_hemisphere\n# finally:\n# browser.quit()\n\nprint(scrape_mars_news())\nprint(scrape_mars_image())\nprint(scrape_mars_weather())\nprint(scrape_mars_facts())\n#print(scrape_mars_hemisphere())\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n #scrape_mars_hemisphere()\n return mars_info\n# In[ ]:\n",
"from bs4 import BeautifulSoup as bs\nfrom splinter import Browser\nimport pandas as pd\nimport requests\nimport time\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\nmars_info = {}\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_image():\n try:\n browser = init_browser()\n image_url_featured = (\n 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars')\n browser.visit(image_url_featured)\n html_image = browser.html\n soup = bs(html_image, 'html.parser')\n featured_image_url = soup.find('article')['style'].replace(\n 'background-image: url(', '').replace(');', '')[1:-1]\n main_url = 'https://www.jpl.nasa.gov'\n featured_image_url = main_url + featured_image_url\n featured_image_url\n mars_info['featured_image_url'] = featured_image_url\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_facts():\n try:\n browser = init_browser()\n facts_url = 'http://space-facts.com/mars/'\n mars_facts = pd.read_html(facts_url)\n mars_df = mars_facts[0]\n mars_df.columns = ['Description', 'Value']\n mars_df.set_index('Description', inplace=True)\n data = mars_df.to_html()\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n\nprint(scrape_mars_news())\nprint(scrape_mars_image())\nprint(scrape_mars_weather())\nprint(scrape_mars_facts())\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\nmars_info = {}\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_image():\n try:\n browser = init_browser()\n image_url_featured = (\n 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars')\n browser.visit(image_url_featured)\n html_image = browser.html\n soup = bs(html_image, 'html.parser')\n featured_image_url = soup.find('article')['style'].replace(\n 'background-image: url(', '').replace(');', '')[1:-1]\n main_url = 'https://www.jpl.nasa.gov'\n featured_image_url = main_url + featured_image_url\n featured_image_url\n mars_info['featured_image_url'] = featured_image_url\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_facts():\n try:\n browser = init_browser()\n facts_url = 'http://space-facts.com/mars/'\n mars_facts = pd.read_html(facts_url)\n mars_df = mars_facts[0]\n mars_df.columns = ['Description', 'Value']\n mars_df.set_index('Description', inplace=True)\n data = mars_df.to_html()\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n\nprint(scrape_mars_news())\nprint(scrape_mars_image())\nprint(scrape_mars_weather())\nprint(scrape_mars_facts())\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_image():\n try:\n browser = init_browser()\n image_url_featured = (\n 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars')\n browser.visit(image_url_featured)\n html_image = browser.html\n soup = bs(html_image, 'html.parser')\n featured_image_url = soup.find('article')['style'].replace(\n 'background-image: url(', '').replace(');', '')[1:-1]\n main_url = 'https://www.jpl.nasa.gov'\n featured_image_url = main_url + featured_image_url\n featured_image_url\n mars_info['featured_image_url'] = featured_image_url\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_facts():\n try:\n browser = init_browser()\n facts_url = 'http://space-facts.com/mars/'\n mars_facts = pd.read_html(facts_url)\n mars_df = mars_facts[0]\n mars_df.columns = ['Description', 'Value']\n mars_df.set_index('Description', inplace=True)\n data = mars_df.to_html()\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n\nprint(scrape_mars_news())\nprint(scrape_mars_image())\nprint(scrape_mars_weather())\nprint(scrape_mars_facts())\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_image():\n try:\n browser = init_browser()\n image_url_featured = (\n 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars')\n browser.visit(image_url_featured)\n html_image = browser.html\n soup = bs(html_image, 'html.parser')\n featured_image_url = soup.find('article')['style'].replace(\n 'background-image: url(', '').replace(');', '')[1:-1]\n main_url = 'https://www.jpl.nasa.gov'\n featured_image_url = main_url + featured_image_url\n featured_image_url\n mars_info['featured_image_url'] = featured_image_url\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_facts():\n try:\n browser = init_browser()\n facts_url = 'http://space-facts.com/mars/'\n mars_facts = pd.read_html(facts_url)\n mars_df = mars_facts[0]\n mars_df.columns = ['Description', 'Value']\n mars_df.set_index('Description', inplace=True)\n data = mars_df.to_html()\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\ndef scrape_mars_facts():\n try:\n browser = init_browser()\n facts_url = 'http://space-facts.com/mars/'\n mars_facts = pd.read_html(facts_url)\n mars_df = mars_facts[0]\n mars_df.columns = ['Description', 'Value']\n mars_df.set_index('Description', inplace=True)\n data = mars_df.to_html()\n mars_info['mars_facts'] = data\n return mars_info\n finally:\n browser.quit()\n\n\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n\n\ndef init_browser():\n exec_path = {'executable_path': 'C:/chromedriver/chromedriver.exe'}\n return Browser('chrome', headless=True, **exec_path)\n\n\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n<function token>\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n\n\ndef scrape_mars_weather():\n try:\n browser = init_browser()\n weather_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(weather_url)\n html_weather = browser.html\n soup = bs(html_weather, 'html.parser')\n tweets = soup.find('ol', class_='stream-items')\n mars_weather = tweets.find('p', class_='tweet-text').text\n mars_info['mars_weather'] = mars_weather\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n<function token>\n<assignment token>\n\n\ndef scrape_mars_news():\n try:\n browser = init_browser()\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n news_title = soup.find('div', class_='content_title').find('a').text\n news_paragraph = soup.find('div', class_='article_teaser_body').text\n mars_info['news_title'] = news_title\n mars_info['news_paragraph'] = news_paragraph\n return mars_info\n finally:\n browser.quit()\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n\n\ndef return_scrape():\n scrape_mars_news()\n scrape_mars_image()\n scrape_mars_weather()\n scrape_mars_facts()\n return mars_info\n",
"<import token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n<function token>\n"
] | false |
99,743 | 507a863f52ee53e991baab4eb93a1ef0a3b071fe | # -*- coding: utf-8 -*-
"""
汇总需要用到的一些常见函数
"""
import config # 导入config,在同一级目录下,直接import
import pandas as pd # 导入pandas,我们一般为pandas取一个别名叫做pd
# 导入数据
def import_stock_data(stock_code):
"""
只导入如下字段:'交易日期', '股票代码', '开盘价', '最高价', '最低价', '收盘价', '涨跌幅'
最终输出结果按照日期排序
:param stock_code:
:return:
"""
df = pd.read_csv(config.input_data_path + '/stock_data/' + stock_code + '.csv', encoding='gbk')
df.columns = [i.encode('utf8') for i in df.columns]
df = df[['交易日期', '股票代码', '开盘价', '最高价', '最低价', '收盘价', '涨跌幅']]
df.sort_values(by=['交易日期'], inplace=True)
df['交易日期'] = pd.to_datetime(df['交易日期'])
df.reset_index(inplace=True, drop=True)
return df
# 计算复权价
def cal_fuquan_price(input_stock_data, fuquan_type='后复权'):
"""
计算复权价
:param input_stock_data:
:param fuquan_type:复权类型,可以是'后复权'或者'前复权'
:return:
"""
# 创建空的df
df = pd.DataFrame()
# 计算复权收盘价
num = {'后复权': 0, '前复权': -1}
price1 = input_stock_data['收盘价'].iloc[num[fuquan_type]]
df['复权因子'] = (1.0 + input_stock_data['涨跌幅']).cumprod()
price2 = df['复权因子'].iloc[num[fuquan_type]]
df['收盘价_' + fuquan_type] = df['复权因子'] * (price1 / price2)
# 计算复权的开盘价、最高价、最低价
df['开盘价_' + fuquan_type] = input_stock_data['开盘价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]
df['最高价_' + fuquan_type] = input_stock_data['最高价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]
df['最低价_' + fuquan_type] = input_stock_data['最低价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]
return df[[i + '_' + fuquan_type for i in '开盘价', '最高价', '最低价', '收盘价']]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\n汇总需要用到的一些常见函数\n\"\"\"\nimport config # 导入config,在同一级目录下,直接import\nimport pandas as pd # 导入pandas,我们一般为pandas取一个别名叫做pd\n\n\n# 导入数据\ndef import_stock_data(stock_code):\n \"\"\"\n 只导入如下字段:'交易日期', '股票代码', '开盘价', '最高价', '最低价', '收盘价', '涨跌幅'\n 最终输出结果按照日期排序\n :param stock_code:\n :return:\n \"\"\"\n df = pd.read_csv(config.input_data_path + '/stock_data/' + stock_code + '.csv', encoding='gbk')\n df.columns = [i.encode('utf8') for i in df.columns]\n df = df[['交易日期', '股票代码', '开盘价', '最高价', '最低价', '收盘价', '涨跌幅']]\n df.sort_values(by=['交易日期'], inplace=True)\n df['交易日期'] = pd.to_datetime(df['交易日期'])\n df.reset_index(inplace=True, drop=True)\n\n return df\n\n\n# 计算复权价\ndef cal_fuquan_price(input_stock_data, fuquan_type='后复权'):\n \"\"\"\n 计算复权价\n :param input_stock_data:\n :param fuquan_type:复权类型,可以是'后复权'或者'前复权'\n :return:\n \"\"\"\n # 创建空的df\n df = pd.DataFrame()\n\n # 计算复权收盘价\n num = {'后复权': 0, '前复权': -1}\n price1 = input_stock_data['收盘价'].iloc[num[fuquan_type]]\n df['复权因子'] = (1.0 + input_stock_data['涨跌幅']).cumprod()\n price2 = df['复权因子'].iloc[num[fuquan_type]]\n df['收盘价_' + fuquan_type] = df['复权因子'] * (price1 / price2)\n\n # 计算复权的开盘价、最高价、最低价\n df['开盘价_' + fuquan_type] = input_stock_data['开盘价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]\n df['最高价_' + fuquan_type] = input_stock_data['最高价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]\n df['最低价_' + fuquan_type] = input_stock_data['最低价'] / input_stock_data['收盘价'] * df['收盘价_' + fuquan_type]\n\n return df[[i + '_' + fuquan_type for i in '开盘价', '最高价', '最低价', '收盘价']]\n"
] | true |
99,744 | df9c1fa3a452aae12969af33fa32c1b07ad124b1 | import requests
from django.db import models
from common.models import BaseDevice, BaseButton, Room
class Device(BaseDevice):
name = models.CharField(max_length=255, unique=True)
room = models.ForeignKey(Room, null=True, blank=True, related_name='api', on_delete=models.CASCADE)
parent = models.OneToOneField(BaseDevice, related_name="api", parent_link=True, on_delete=models.CASCADE)
def __str__(self):
return '{name}{room}'.format(name=self.name, room=', ' + self.room.name if self.room else '')
class Button(BaseButton):
device = models.ForeignKey(Device, related_name='buttons', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
color = models.CharField(max_length=255, choices=(
("default", "White"),
("primary", "Blue"),
("success", "Green"),
("info", "Light blue"),
("warning", "Orange"),
("danger", "Red"),
), default="btn-default")
url = models.CharField(max_length=511)
post_body = models.TextField(blank=True, null=True)
content_type = models.CharField(default="application/json", max_length=255, blank=True, null=True)
method = models.CharField(max_length=10, choices=(
("post", "POST"),
("get", "GET"),))
user = models.CharField(max_length=255, blank=True, null=True)
password = models.CharField(max_length=255, blank=True, null=True)
parent = models.OneToOneField(BaseButton, related_name="api", parent_link=True, on_delete=models.CASCADE)
active = models.BooleanField(default=False)
manually_active = models.BooleanField(default=False)
class Meta:
unique_together = (('name', 'device'),)
def __str__(self):
return '{name}'.format(name=self.name)
def perform_action_internal(self, manually=False):
self.active = True
self.manually_active = manually
for b in self.device.buttons.all():
if b.pk != self.pk:
b.active = False
b.manually_active = False
b.save()
self.save()
if self.method == 'post':
auth = None
headers = {
'cache-control': "no-cache",
}
if self.user:
auth = (self.user, self.password)
if self.content_type:
headers['content-type'] = self.content_type
requests.post(
self.url,
data=self.post_body,
headers=headers,
auth=auth
)
elif self.method == 'get':
auth = None
if self.user:
auth = (self.user, self.password)
requests.get(
self.url,
headers={
'cache-control': "no-cache",
},
auth=auth
)
def perform_action(self):
for s in self.schedule_off.all():
s.disable_until = s.get_state()['end']
s.save()
for s in self.schedule_on.all():
s.disable_until = s.get_state()['end']
s.save()
self.perform_action_internal(manually=True)
| [
"import requests\nfrom django.db import models\n\nfrom common.models import BaseDevice, BaseButton, Room\n\n\nclass Device(BaseDevice):\n name = models.CharField(max_length=255, unique=True)\n room = models.ForeignKey(Room, null=True, blank=True, related_name='api', on_delete=models.CASCADE)\n parent = models.OneToOneField(BaseDevice, related_name=\"api\", parent_link=True, on_delete=models.CASCADE)\n\n def __str__(self):\n return '{name}{room}'.format(name=self.name, room=', ' + self.room.name if self.room else '')\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(\n (\"default\", \"White\"),\n (\"primary\", \"Blue\"),\n (\"success\", \"Green\"),\n (\"info\", \"Light blue\"),\n (\"warning\", \"Orange\"),\n (\"danger\", \"Red\"),\n ), default=\"btn-default\")\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default=\"application/json\", max_length=255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(\n (\"post\", \"POST\"),\n (\"get\", \"GET\"),))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name=\"api\", parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n class Meta:\n unique_together = (('name', 'device'),)\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {\n 'cache-control': \"no-cache\",\n }\n if self.user:\n auth = (self.user, self.password)\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(\n self.url,\n data=self.post_body,\n headers=headers,\n auth=auth\n )\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = (self.user, self.password)\n requests.get(\n self.url,\n headers={\n 'cache-control': \"no-cache\",\n },\n auth=auth\n )\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"import requests\nfrom django.db import models\nfrom common.models import BaseDevice, BaseButton, Room\n\n\nclass Device(BaseDevice):\n name = models.CharField(max_length=255, unique=True)\n room = models.ForeignKey(Room, null=True, blank=True, related_name=\n 'api', on_delete=models.CASCADE)\n parent = models.OneToOneField(BaseDevice, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n\n def __str__(self):\n return '{name}{room}'.format(name=self.name, room=', ' + self.room.\n name if self.room else '')\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=\n models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(('default', 'White'),\n ('primary', 'Blue'), ('success', 'Green'), ('info', 'Light blue'),\n ('warning', 'Orange'), ('danger', 'Red')), default='btn-default')\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default='application/json', max_length=\n 255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(('post', 'POST'), (\n 'get', 'GET')))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n\n\nclass Device(BaseDevice):\n name = models.CharField(max_length=255, unique=True)\n room = models.ForeignKey(Room, null=True, blank=True, related_name=\n 'api', on_delete=models.CASCADE)\n parent = models.OneToOneField(BaseDevice, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n\n def __str__(self):\n return '{name}{room}'.format(name=self.name, room=', ' + self.room.\n name if self.room else '')\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=\n models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(('default', 'White'),\n ('primary', 'Blue'), ('success', 'Green'), ('info', 'Light blue'),\n ('warning', 'Orange'), ('danger', 'Red')), default='btn-default')\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default='application/json', max_length=\n 255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(('post', 'POST'), (\n 'get', 'GET')))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n\n\nclass Device(BaseDevice):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return '{name}{room}'.format(name=self.name, room=', ' + self.room.\n name if self.room else '')\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=\n models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(('default', 'White'),\n ('primary', 'Blue'), ('success', 'Green'), ('info', 'Light blue'),\n ('warning', 'Orange'), ('danger', 'Red')), default='btn-default')\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default='application/json', max_length=\n 255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(('post', 'POST'), (\n 'get', 'GET')))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n\n\nclass Device(BaseDevice):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=\n models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(('default', 'White'),\n ('primary', 'Blue'), ('success', 'Green'), ('info', 'Light blue'),\n ('warning', 'Orange'), ('danger', 'Red')), default='btn-default')\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default='application/json', max_length=\n 255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(('post', 'POST'), (\n 'get', 'GET')))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n<class token>\n\n\nclass Button(BaseButton):\n device = models.ForeignKey(Device, related_name='buttons', on_delete=\n models.CASCADE)\n name = models.CharField(max_length=255)\n color = models.CharField(max_length=255, choices=(('default', 'White'),\n ('primary', 'Blue'), ('success', 'Green'), ('info', 'Light blue'),\n ('warning', 'Orange'), ('danger', 'Red')), default='btn-default')\n url = models.CharField(max_length=511)\n post_body = models.TextField(blank=True, null=True)\n content_type = models.CharField(default='application/json', max_length=\n 255, blank=True, null=True)\n method = models.CharField(max_length=10, choices=(('post', 'POST'), (\n 'get', 'GET')))\n user = models.CharField(max_length=255, blank=True, null=True)\n password = models.CharField(max_length=255, blank=True, null=True)\n parent = models.OneToOneField(BaseButton, related_name='api',\n parent_link=True, on_delete=models.CASCADE)\n active = models.BooleanField(default=False)\n manually_active = models.BooleanField(default=False)\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n<class token>\n\n\nclass Button(BaseButton):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n class Meta:\n unique_together = ('name', 'device'),\n\n def __str__(self):\n return '{name}'.format(name=self.name)\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n<class token>\n\n\nclass Button(BaseButton):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n class Meta:\n unique_together = ('name', 'device'),\n <function token>\n\n def perform_action_internal(self, manually=False):\n self.active = True\n self.manually_active = manually\n for b in self.device.buttons.all():\n if b.pk != self.pk:\n b.active = False\n b.manually_active = False\n b.save()\n self.save()\n if self.method == 'post':\n auth = None\n headers = {'cache-control': 'no-cache'}\n if self.user:\n auth = self.user, self.password\n if self.content_type:\n headers['content-type'] = self.content_type\n requests.post(self.url, data=self.post_body, headers=headers,\n auth=auth)\n elif self.method == 'get':\n auth = None\n if self.user:\n auth = self.user, self.password\n requests.get(self.url, headers={'cache-control': 'no-cache'},\n auth=auth)\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n<class token>\n\n\nclass Button(BaseButton):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n class Meta:\n unique_together = ('name', 'device'),\n <function token>\n <function token>\n\n def perform_action(self):\n for s in self.schedule_off.all():\n s.disable_until = s.get_state()['end']\n s.save()\n for s in self.schedule_on.all():\n s.disable_until = s.get_state()['end']\n s.save()\n self.perform_action_internal(manually=True)\n",
"<import token>\n<class token>\n\n\nclass Button(BaseButton):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n class Meta:\n unique_together = ('name', 'device'),\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n<class token>\n"
] | false |
99,745 | 9230e5bae6270a8dc21f39b14b619fd7bd4dc003 | """
CAR CONFIG
This file is read by your car application's manage.py script to change the car
performance.
EXMAPLE
-----------
import dk
cfg = dk.load_config(config_path='~/mycar/config.py')
print(cfg.CAMERA_RESOLUTION)
"""
import os
#PATHS
CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(CAR_PATH, 'data')
MODELS_PATH = os.path.join(CAR_PATH, 'models')
#VEHICLE
DRIVE_LOOP_HZ = 20 # the vehicle loop will pause if faster than this speed.
MAX_LOOPS = None # the vehicle loop can abort after this many iterations, when given a positive integer.
#CAMERA
CAMERA_TYPE = "MOCK" # (PICAM|WEBCAM|CVCAM|CSIC|V4L|D435|MOCK|IMAGE_LIST)
IMAGE_W = 160
IMAGE_H = 120
IMAGE_DEPTH = 3 # default RGB=3, make 1 for mono
CAMERA_FRAMERATE = DRIVE_LOOP_HZ
CAMERA_VFLIP = False
CAMERA_HFLIP = False
# For CSIC camera - If the camera is mounted in a rotated position, changing the below parameter will correct the output frame orientation
CSIC_CAM_GSTREAMER_FLIP_PARM = 0 # (0 => none , 4 => Flip horizontally, 6 => Flip vertically)
# For IMAGE_LIST camera
# PATH_MASK = "~/mycar/data/tub_1_20-03-12/*.jpg"
#9865, over rides only if needed, ie. TX2..
PCA9685_I2C_ADDR = 0x40 #I2C address, use i2cdetect to validate this number
PCA9685_I2C_BUSNUM = None #None will auto detect, which is fine on the pi. But other platforms should specify the bus num.
#SSD1306_128_32
USE_SSD1306_128_32 = False # Enable the SSD_1306 OLED Display
SSD1306_128_32_I2C_BUSNUM = 1 # I2C bus number
#DRIVETRAIN
#These options specify which chasis and motor setup you are using. Most are using SERVO_ESC.
#DC_STEER_THROTTLE uses HBridge pwm to control one steering dc motor, and one drive wheel motor
#DC_TWO_WHEEL uses HBridge pwm to control two drive motors, one on the left, and one on the right.
#SERVO_HBRIDGE_PWM use ServoBlaster to output pwm control from the PiZero directly to control steering, and HBridge for a drive motor.
#PIGPIO_PWM uses Raspberrys internal PWM
DRIVE_TRAIN_TYPE = "MOCK" # I2C_SERVO|DC_STEER_THROTTLE|DC_TWO_WHEEL|DC_TWO_WHEEL_L298N|SERVO_HBRIDGE_PWM|PIGPIO_PWM|MM1|MOCK
#STEERING
STEERING_CHANNEL = 1 #channel on the 9685 pwm board 0-15
STEERING_LEFT_PWM = 460 #pwm value for full left steering
STEERING_RIGHT_PWM = 290 #pwm value for full right steering
#STEERING FOR PIGPIO_PWM
STEERING_PWM_PIN = 13 #Pin numbering according to Broadcom numbers
STEERING_PWM_FREQ = 50 #Frequency for PWM
STEERING_PWM_INVERTED = False #If PWM needs to be inverted
#THROTTLE
THROTTLE_CHANNEL = 0 #channel on the 9685 pwm board 0-15
THROTTLE_FORWARD_PWM = 500 #pwm value for max forward throttle
THROTTLE_STOPPED_PWM = 370 #pwm value for no movement
THROTTLE_REVERSE_PWM = 220 #pwm value for max reverse throttle
#THROTTLE FOR PIGPIO_PWM
THROTTLE_PWM_PIN = 18 #Pin numbering according to Broadcom numbers
THROTTLE_PWM_FREQ = 50 #Frequency for PWM
THROTTLE_PWM_INVERTED = False #If PWM needs to be inverted
#DC_STEER_THROTTLE with one motor as steering, one as drive
#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_STEER_THROTTLE
HBRIDGE_PIN_LEFT = 18
HBRIDGE_PIN_RIGHT = 16
HBRIDGE_PIN_FWD = 15
HBRIDGE_PIN_BWD = 13
#DC_TWO_WHEEL - with two wheels as drive, left and right.
#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_TWO_WHEEL
HBRIDGE_PIN_LEFT_FWD = 18
HBRIDGE_PIN_LEFT_BWD = 16
HBRIDGE_PIN_RIGHT_FWD = 15
HBRIDGE_PIN_RIGHT_BWD = 13
#TRAINING
#The DEFAULT_MODEL_TYPE will choose which model will be created at training time. This chooses
#between different neural network designs. You can override this setting by passing the command
#line parameter --type to the python manage.py train and drive commands.
DEFAULT_MODEL_TYPE = 'linear' #(linear|categorical|tflite_linear|tensorrt_linear)
BATCH_SIZE = 128 #how many records to use when doing one pass of gradient decent. Use a smaller number if your gpu is running out of memory.
TRAIN_TEST_SPLIT = 0.8 #what percent of records to use for training. the remaining used for validation.
MAX_EPOCHS = 100 #how many times to visit all records of your data
SHOW_PLOT = True #would you like to see a pop up display of final loss?
VERBOSE_TRAIN = True #would you like to see a progress bar with text during training?
USE_EARLY_STOP = True #would you like to stop the training if we see it's not improving fit?
EARLY_STOP_PATIENCE = 5 #how many epochs to wait before no improvement
MIN_DELTA = .0005 #early stop will want this much loss change before calling it improved.
PRINT_MODEL_SUMMARY = True #print layers and weights to stdout
OPTIMIZER = None #adam, sgd, rmsprop, etc.. None accepts default
LEARNING_RATE = 0.001 #only used when OPTIMIZER specified
LEARNING_RATE_DECAY = 0.0 #only used when OPTIMIZER specified
SEND_BEST_MODEL_TO_PI = False #change to true to automatically send best model during training
PRUNE_CNN = False #This will remove weights from your model. The primary goal is to increase performance.
PRUNE_PERCENT_TARGET = 75 # The desired percentage of pruning.
PRUNE_PERCENT_PER_ITERATION = 20 # Percenge of pruning that is perform per iteration.
PRUNE_VAL_LOSS_DEGRADATION_LIMIT = 0.2 # The max amout of validation loss that is permitted during pruning.
PRUNE_EVAL_PERCENT_OF_DATASET = .05 # percent of dataset used to perform evaluation of model.
#Model transfer options
#When copying weights during a model transfer operation, should we freeze a certain number of layers
#to the incoming weights and not allow them to change during training?
FREEZE_LAYERS = False #default False will allow all layers to be modified by training
NUM_LAST_LAYERS_TO_TRAIN = 7 #when freezing layers, how many layers from the last should be allowed to train?
#WEB CONTROL
WEB_CONTROL_PORT = 8887 # which port to listen on when making a web controller
WEB_INIT_MODE = "user" # which control mode to start in. one of user|local_angle|local. Setting local will start in ai mode.
#JOYSTICK
USE_JOYSTICK_AS_DEFAULT = False #when starting the manage.py, when True, will not require a --js option to use the joystick
JOYSTICK_MAX_THROTTLE = 0.5 #this scalar is multiplied with the -1 to 1 throttle value to limit the maximum throttle. This can help if you drop the controller or just don't need the full speed available.
JOYSTICK_STEERING_SCALE = 1.0 #some people want a steering that is less sensitve. This scalar is multiplied with the steering -1 to 1. It can be negative to reverse dir.
AUTO_RECORD_ON_THROTTLE = True #if true, we will record whenever throttle is not zero. if false, you must manually toggle recording with some other trigger. Usually circle button on joystick.
CONTROLLER_TYPE = 'xbox' #(ps3|ps4|xbox|nimbus|wiiu|F710|rc3|MM1|custom) custom will run the my_joystick.py controller written by the `donkey createjs` command
USE_NETWORKED_JS = False #should we listen for remote joystick control over the network?
NETWORK_JS_SERVER_IP = None #when listening for network joystick control, which ip is serving this information
JOYSTICK_DEADZONE = 0.01 # when non zero, this is the smallest throttle before recording triggered.
JOYSTICK_THROTTLE_DIR = 1.0 # use -1.0 to flip forward/backward, use 1.0 to use joystick's natural forward/backward
USE_FPV = False # send camera data to FPV webserver
JOYSTICK_DEVICE_FILE = "/dev/input/js0" # this is the unix file use to access the joystick.
#For the categorical model, this limits the upper bound of the learned throttle
#it's very IMPORTANT that this value is matched from the training PC config.py and the robot.py
#and ideally wouldn't change once set.
MODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8
#RNN or 3D
SEQUENCE_LENGTH = 3 #some models use a number of images over time. This controls how many.
#IMU
HAVE_IMU = False #when true, this add a Mpu6050 part and records the data. Can be used with a
IMU_SENSOR = 'mpu6050' # (mpu6050|mpu9250)
IMU_DLP_CONFIG = 0 # Digital Lowpass Filter setting (0:250Hz, 1:184Hz, 2:92Hz, 3:41Hz, 4:20Hz, 5:10Hz, 6:5Hz)
#SOMBRERO
HAVE_SOMBRERO = False #set to true when using the sombrero hat from the Donkeycar store. This will enable pwm on the hat.
#ROBOHAT MM1
HAVE_ROBOHAT = False # set to true when using the Robo HAT MM1 from Robotics Masters. This will change to RC Control.
MM1_STEERING_MID = 1500 # Adjust this value if your car cannot run in a straight line
MM1_MAX_FORWARD = 2000 # Max throttle to go fowrward. The bigger the faster
MM1_STOPPED_PWM = 1500
MM1_MAX_REVERSE = 1000 # Max throttle to go reverse. The smaller the faster
MM1_SHOW_STEERING_VALUE = False
# Serial port
# -- Default Pi: '/dev/ttyS0'
# -- Jetson Nano: '/dev/ttyTHS1'
# -- Google coral: '/dev/ttymxc0'
# -- Windows: 'COM3', Arduino: '/dev/ttyACM0'
# -- MacOS/Linux:please use 'ls /dev/tty.*' to find the correct serial port for mm1
# eg.'/dev/tty.usbmodemXXXXXX' and replace the port accordingly
MM1_SERIAL_PORT = '/dev/ttyS0' # Serial Port for reading and sending MM1 data.
#RECORD OPTIONS
RECORD_DURING_AI = False #normally we do not record during ai mode. Set this to true to get image and steering records for your Ai. Be careful not to use them to train.
AUTO_CREATE_NEW_TUB = False #create a new tub (tub_YY_MM_DD) directory when recording or append records to data directory directly
#LED
HAVE_RGB_LED = False #do you have an RGB LED like https://www.amazon.com/dp/B07BNRZWNF
LED_INVERT = False #COMMON ANODE? Some RGB LED use common anode. like https://www.amazon.com/Xia-Fly-Tri-Color-Emitting-Diffused/dp/B07MYJQP8B
#LED board pin number for pwm outputs
#These are physical pinouts. See: https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/
LED_PIN_R = 12
LED_PIN_G = 10
LED_PIN_B = 16
#LED status color, 0-100
LED_R = 0
LED_G = 0
LED_B = 1
#LED Color for record count indicator
REC_COUNT_ALERT = 1000 #how many records before blinking alert
REC_COUNT_ALERT_CYC = 15 #how many cycles of 1/20 of a second to blink per REC_COUNT_ALERT records
REC_COUNT_ALERT_BLINK_RATE = 0.4 #how fast to blink the led in seconds on/off
#first number is record count, second tuple is color ( r, g, b) (0-100)
#when record count exceeds that number, the color will be used
RECORD_ALERT_COLOR_ARR = [ (0, (1, 1, 1)),
(3000, (5, 5, 5)),
(5000, (5, 2, 0)),
(10000, (0, 5, 0)),
(15000, (0, 5, 5)),
(20000, (0, 0, 5)), ]
#LED status color, 0-100, for model reloaded alert
MODEL_RELOADED_LED_R = 100
MODEL_RELOADED_LED_G = 0
MODEL_RELOADED_LED_B = 0
#BEHAVIORS
#When training the Behavioral Neural Network model, make a list of the behaviors,
#Set the TRAIN_BEHAVIORS = True, and use the BEHAVIOR_LED_COLORS to give each behavior a color
TRAIN_BEHAVIORS = False
BEHAVIOR_LIST = ['Left_Lane', "Right_Lane"]
BEHAVIOR_LED_COLORS =[ (0, 10, 0), (10, 0, 0) ] #RGB tuples 0-100 per chanel
#Localizer
#The localizer is a neural network that can learn to predice it's location on the track.
#This is an experimental feature that needs more developement. But it can currently be used
#to predict the segement of the course, where the course is divided into NUM_LOCATIONS segments.
TRAIN_LOCALIZER = False
NUM_LOCATIONS = 10
BUTTON_PRESS_NEW_TUB = False #when enabled, makes it easier to divide our data into one tub per track length if we make a new tub on each X button press.
#DonkeyGym
#Only on Ubuntu linux, you can use the simulator as a virtual donkey and
#issue the same python manage.py drive command as usual, but have them control a virtual car.
#This enables that, and sets the path to the simualator and the environment.
#You will want to download the simulator binary from: https://github.com/tawnkramer/donkey_gym/releases/download/v18.9/DonkeySimLinux.zip
#then extract that and modify DONKEY_SIM_PATH.
DONKEY_GYM = True
DONKEY_SIM_PATH = "path to sim" #"/home/tkramer/projects/sdsandbox/sdsim/build/DonkeySimLinux/donkey_sim.x86_64" when racing on virtual-race-league use "remote", or user "remote" when you want to start the sim manually first.
DONKEY_GYM_ENV_NAME = "donkey-generated-track-v0" # ("donkey-generated-track-v0"|"donkey-generated-roads-v0"|"donkey-warehouse-v0"|"donkey-avc-sparkfun-v0")
GYM_CONF = { "img_h" : IMAGE_H, "img_w" : IMAGE_W, "body_style" : "donkey", "body_rgb" : (128, 128, 128), "car_name" : "car", "font_size" : 100 } # body style(donkey|bare|car01) body rgb 0-255
GYM_CONF["racer_name"] = "Your Name"
GYM_CONF["country"] = "Place"
GYM_CONF["bio"] = "I race robots."
SIM_HOST = "127.0.0.1" # when racing on virtual-race-league use host "trainmydonkey.com"
SIM_ARTIFICIAL_LATENCY = 0 # this is the millisecond latency in controls. Can use useful in emulating the delay when useing a remote server. values of 100 to 400 probably reasonable.
#publish camera over network
#This is used to create a tcp service to pushlish the camera feed
PUB_CAMERA_IMAGES = False
#When racing, to give the ai a boost, configure these values.
AI_LAUNCH_DURATION = 0.0 # the ai will output throttle for this many seconds
AI_LAUNCH_THROTTLE = 0.0 # the ai will output this throttle value
AI_LAUNCH_ENABLE_BUTTON = 'R2' # this keypress will enable this boost. It must be enabled before each use to prevent accidental trigger.
AI_LAUNCH_KEEP_ENABLED = False # when False ( default) you will need to hit the AI_LAUNCH_ENABLE_BUTTON for each use. This is safest. When this True, is active on each trip into "local" ai mode.
#Scale the output of the throttle of the ai pilot for all model types.
AI_THROTTLE_MULT = 1.0 # this multiplier will scale every throttle value for all output from NN models
#Path following
PATH_FILENAME = "donkey_path.pkl" # the path will be saved to this filename
PATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page
PATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed.
PATH_MIN_DIST = 0.3 # after travelling this distance (m), save a path point
PID_P = -10.0 # proportional mult for PID path follower
PID_I = 0.000 # integral mult for PID path follower
PID_D = -0.2 # differential mult for PID path follower
PID_THROTTLE = 0.2 # constant throttle value during path following
USE_CONSTANT_THROTTLE = False # whether or not to use the constant throttle or variable throttle captured during path recording
SAVE_PATH_BTN = "cross" # joystick button to save path
RESET_ORIGIN_BTN = "triangle" # joystick button to press to move car back to origin
# Intel Realsense D435 and D435i depth sensing camera
REALSENSE_D435_RGB = True # True to capture RGB image
REALSENSE_D435_DEPTH = True # True to capture depth as image array
REALSENSE_D435_IMU = False # True to capture IMU data (D435i only)
REALSENSE_D435_ID = None # serial number of camera or None if you only have one camera (it will autodetect)
# Stop Sign Detector
STOP_SIGN_DETECTOR = False
STOP_SIGN_MIN_SCORE = 0.2
STOP_SIGN_SHOW_BOUNDING_BOX = True
| [
"\"\"\"\nCAR CONFIG\n\nThis file is read by your car application's manage.py script to change the car\nperformance.\n\nEXMAPLE\n-----------\nimport dk\ncfg = dk.load_config(config_path='~/mycar/config.py')\nprint(cfg.CAMERA_RESOLUTION)\n\n\"\"\"\n\n\nimport os\n\n#PATHS\nCAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(CAR_PATH, 'data')\nMODELS_PATH = os.path.join(CAR_PATH, 'models')\n\n#VEHICLE\nDRIVE_LOOP_HZ = 20 # the vehicle loop will pause if faster than this speed.\nMAX_LOOPS = None # the vehicle loop can abort after this many iterations, when given a positive integer.\n\n#CAMERA\nCAMERA_TYPE = \"MOCK\" # (PICAM|WEBCAM|CVCAM|CSIC|V4L|D435|MOCK|IMAGE_LIST)\nIMAGE_W = 160\nIMAGE_H = 120\nIMAGE_DEPTH = 3 # default RGB=3, make 1 for mono\nCAMERA_FRAMERATE = DRIVE_LOOP_HZ\nCAMERA_VFLIP = False\nCAMERA_HFLIP = False\n# For CSIC camera - If the camera is mounted in a rotated position, changing the below parameter will correct the output frame orientation\nCSIC_CAM_GSTREAMER_FLIP_PARM = 0 # (0 => none , 4 => Flip horizontally, 6 => Flip vertically)\n\n# For IMAGE_LIST camera\n# PATH_MASK = \"~/mycar/data/tub_1_20-03-12/*.jpg\"\n\n#9865, over rides only if needed, ie. TX2..\nPCA9685_I2C_ADDR = 0x40 #I2C address, use i2cdetect to validate this number\nPCA9685_I2C_BUSNUM = None #None will auto detect, which is fine on the pi. But other platforms should specify the bus num.\n\n#SSD1306_128_32\nUSE_SSD1306_128_32 = False # Enable the SSD_1306 OLED Display\nSSD1306_128_32_I2C_BUSNUM = 1 # I2C bus number\n\n#DRIVETRAIN\n#These options specify which chasis and motor setup you are using. Most are using SERVO_ESC.\n#DC_STEER_THROTTLE uses HBridge pwm to control one steering dc motor, and one drive wheel motor\n#DC_TWO_WHEEL uses HBridge pwm to control two drive motors, one on the left, and one on the right.\n#SERVO_HBRIDGE_PWM use ServoBlaster to output pwm control from the PiZero directly to control steering, and HBridge for a drive motor.\n#PIGPIO_PWM uses Raspberrys internal PWM\nDRIVE_TRAIN_TYPE = \"MOCK\" # I2C_SERVO|DC_STEER_THROTTLE|DC_TWO_WHEEL|DC_TWO_WHEEL_L298N|SERVO_HBRIDGE_PWM|PIGPIO_PWM|MM1|MOCK\n\n#STEERING\nSTEERING_CHANNEL = 1 #channel on the 9685 pwm board 0-15\nSTEERING_LEFT_PWM = 460 #pwm value for full left steering\nSTEERING_RIGHT_PWM = 290 #pwm value for full right steering\n\n#STEERING FOR PIGPIO_PWM\nSTEERING_PWM_PIN = 13 #Pin numbering according to Broadcom numbers\nSTEERING_PWM_FREQ = 50 #Frequency for PWM\nSTEERING_PWM_INVERTED = False #If PWM needs to be inverted\n\n#THROTTLE\nTHROTTLE_CHANNEL = 0 #channel on the 9685 pwm board 0-15\nTHROTTLE_FORWARD_PWM = 500 #pwm value for max forward throttle\nTHROTTLE_STOPPED_PWM = 370 #pwm value for no movement\nTHROTTLE_REVERSE_PWM = 220 #pwm value for max reverse throttle\n\n#THROTTLE FOR PIGPIO_PWM\nTHROTTLE_PWM_PIN = 18 #Pin numbering according to Broadcom numbers\nTHROTTLE_PWM_FREQ = 50 #Frequency for PWM\nTHROTTLE_PWM_INVERTED = False #If PWM needs to be inverted\n\n#DC_STEER_THROTTLE with one motor as steering, one as drive\n#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_STEER_THROTTLE\nHBRIDGE_PIN_LEFT = 18\nHBRIDGE_PIN_RIGHT = 16\nHBRIDGE_PIN_FWD = 15\nHBRIDGE_PIN_BWD = 13\n\n#DC_TWO_WHEEL - with two wheels as drive, left and right.\n#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_TWO_WHEEL\nHBRIDGE_PIN_LEFT_FWD = 18\nHBRIDGE_PIN_LEFT_BWD = 16\nHBRIDGE_PIN_RIGHT_FWD = 15\nHBRIDGE_PIN_RIGHT_BWD = 13\n\n\n#TRAINING\n#The DEFAULT_MODEL_TYPE will choose which model will be created at training time. This chooses\n#between different neural network designs. You can override this setting by passing the command\n#line parameter --type to the python manage.py train and drive commands.\nDEFAULT_MODEL_TYPE = 'linear' #(linear|categorical|tflite_linear|tensorrt_linear)\nBATCH_SIZE = 128 #how many records to use when doing one pass of gradient decent. Use a smaller number if your gpu is running out of memory.\nTRAIN_TEST_SPLIT = 0.8 #what percent of records to use for training. the remaining used for validation.\nMAX_EPOCHS = 100 #how many times to visit all records of your data\nSHOW_PLOT = True #would you like to see a pop up display of final loss?\nVERBOSE_TRAIN = True #would you like to see a progress bar with text during training?\nUSE_EARLY_STOP = True #would you like to stop the training if we see it's not improving fit?\nEARLY_STOP_PATIENCE = 5 #how many epochs to wait before no improvement\nMIN_DELTA = .0005 #early stop will want this much loss change before calling it improved.\nPRINT_MODEL_SUMMARY = True #print layers and weights to stdout\nOPTIMIZER = None #adam, sgd, rmsprop, etc.. None accepts default\nLEARNING_RATE = 0.001 #only used when OPTIMIZER specified\nLEARNING_RATE_DECAY = 0.0 #only used when OPTIMIZER specified\nSEND_BEST_MODEL_TO_PI = False #change to true to automatically send best model during training\n\nPRUNE_CNN = False #This will remove weights from your model. The primary goal is to increase performance.\nPRUNE_PERCENT_TARGET = 75 # The desired percentage of pruning.\nPRUNE_PERCENT_PER_ITERATION = 20 # Percenge of pruning that is perform per iteration.\nPRUNE_VAL_LOSS_DEGRADATION_LIMIT = 0.2 # The max amout of validation loss that is permitted during pruning.\nPRUNE_EVAL_PERCENT_OF_DATASET = .05 # percent of dataset used to perform evaluation of model.\n\n#Model transfer options\n#When copying weights during a model transfer operation, should we freeze a certain number of layers\n#to the incoming weights and not allow them to change during training?\nFREEZE_LAYERS = False #default False will allow all layers to be modified by training\nNUM_LAST_LAYERS_TO_TRAIN = 7 #when freezing layers, how many layers from the last should be allowed to train?\n\n#WEB CONTROL\nWEB_CONTROL_PORT = 8887 # which port to listen on when making a web controller\nWEB_INIT_MODE = \"user\" # which control mode to start in. one of user|local_angle|local. Setting local will start in ai mode.\n\n#JOYSTICK\nUSE_JOYSTICK_AS_DEFAULT = False #when starting the manage.py, when True, will not require a --js option to use the joystick\nJOYSTICK_MAX_THROTTLE = 0.5 #this scalar is multiplied with the -1 to 1 throttle value to limit the maximum throttle. This can help if you drop the controller or just don't need the full speed available.\nJOYSTICK_STEERING_SCALE = 1.0 #some people want a steering that is less sensitve. This scalar is multiplied with the steering -1 to 1. It can be negative to reverse dir.\nAUTO_RECORD_ON_THROTTLE = True #if true, we will record whenever throttle is not zero. if false, you must manually toggle recording with some other trigger. Usually circle button on joystick.\nCONTROLLER_TYPE = 'xbox' #(ps3|ps4|xbox|nimbus|wiiu|F710|rc3|MM1|custom) custom will run the my_joystick.py controller written by the `donkey createjs` command\nUSE_NETWORKED_JS = False #should we listen for remote joystick control over the network?\nNETWORK_JS_SERVER_IP = None #when listening for network joystick control, which ip is serving this information\nJOYSTICK_DEADZONE = 0.01 # when non zero, this is the smallest throttle before recording triggered.\nJOYSTICK_THROTTLE_DIR = 1.0 # use -1.0 to flip forward/backward, use 1.0 to use joystick's natural forward/backward\nUSE_FPV = False # send camera data to FPV webserver\nJOYSTICK_DEVICE_FILE = \"/dev/input/js0\" # this is the unix file use to access the joystick.\n\n#For the categorical model, this limits the upper bound of the learned throttle\n#it's very IMPORTANT that this value is matched from the training PC config.py and the robot.py\n#and ideally wouldn't change once set.\nMODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8\n\n#RNN or 3D\nSEQUENCE_LENGTH = 3 #some models use a number of images over time. This controls how many.\n\n#IMU\nHAVE_IMU = False #when true, this add a Mpu6050 part and records the data. Can be used with a\nIMU_SENSOR = 'mpu6050' # (mpu6050|mpu9250)\nIMU_DLP_CONFIG = 0 # Digital Lowpass Filter setting (0:250Hz, 1:184Hz, 2:92Hz, 3:41Hz, 4:20Hz, 5:10Hz, 6:5Hz)\n\n#SOMBRERO\nHAVE_SOMBRERO = False #set to true when using the sombrero hat from the Donkeycar store. This will enable pwm on the hat.\n\n#ROBOHAT MM1\nHAVE_ROBOHAT = False # set to true when using the Robo HAT MM1 from Robotics Masters. This will change to RC Control.\nMM1_STEERING_MID = 1500 # Adjust this value if your car cannot run in a straight line\nMM1_MAX_FORWARD = 2000 # Max throttle to go fowrward. The bigger the faster\nMM1_STOPPED_PWM = 1500\nMM1_MAX_REVERSE = 1000 # Max throttle to go reverse. The smaller the faster\nMM1_SHOW_STEERING_VALUE = False\n# Serial port \n# -- Default Pi: '/dev/ttyS0'\n# -- Jetson Nano: '/dev/ttyTHS1'\n# -- Google coral: '/dev/ttymxc0'\n# -- Windows: 'COM3', Arduino: '/dev/ttyACM0'\n# -- MacOS/Linux:please use 'ls /dev/tty.*' to find the correct serial port for mm1 \n# eg.'/dev/tty.usbmodemXXXXXX' and replace the port accordingly\nMM1_SERIAL_PORT = '/dev/ttyS0' # Serial Port for reading and sending MM1 data.\n\n#RECORD OPTIONS\nRECORD_DURING_AI = False #normally we do not record during ai mode. Set this to true to get image and steering records for your Ai. Be careful not to use them to train.\nAUTO_CREATE_NEW_TUB = False #create a new tub (tub_YY_MM_DD) directory when recording or append records to data directory directly\n\n#LED\nHAVE_RGB_LED = False #do you have an RGB LED like https://www.amazon.com/dp/B07BNRZWNF\nLED_INVERT = False #COMMON ANODE? Some RGB LED use common anode. like https://www.amazon.com/Xia-Fly-Tri-Color-Emitting-Diffused/dp/B07MYJQP8B\n\n#LED board pin number for pwm outputs\n#These are physical pinouts. See: https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/\nLED_PIN_R = 12\nLED_PIN_G = 10\nLED_PIN_B = 16\n\n#LED status color, 0-100\nLED_R = 0\nLED_G = 0\nLED_B = 1\n\n#LED Color for record count indicator\nREC_COUNT_ALERT = 1000 #how many records before blinking alert\nREC_COUNT_ALERT_CYC = 15 #how many cycles of 1/20 of a second to blink per REC_COUNT_ALERT records\nREC_COUNT_ALERT_BLINK_RATE = 0.4 #how fast to blink the led in seconds on/off\n\n#first number is record count, second tuple is color ( r, g, b) (0-100)\n#when record count exceeds that number, the color will be used\nRECORD_ALERT_COLOR_ARR = [ (0, (1, 1, 1)),\n (3000, (5, 5, 5)),\n (5000, (5, 2, 0)),\n (10000, (0, 5, 0)),\n (15000, (0, 5, 5)),\n (20000, (0, 0, 5)), ]\n\n\n#LED status color, 0-100, for model reloaded alert\nMODEL_RELOADED_LED_R = 100\nMODEL_RELOADED_LED_G = 0\nMODEL_RELOADED_LED_B = 0\n\n\n#BEHAVIORS\n#When training the Behavioral Neural Network model, make a list of the behaviors,\n#Set the TRAIN_BEHAVIORS = True, and use the BEHAVIOR_LED_COLORS to give each behavior a color\nTRAIN_BEHAVIORS = False\nBEHAVIOR_LIST = ['Left_Lane', \"Right_Lane\"]\nBEHAVIOR_LED_COLORS =[ (0, 10, 0), (10, 0, 0) ] #RGB tuples 0-100 per chanel\n\n#Localizer\n#The localizer is a neural network that can learn to predice it's location on the track.\n#This is an experimental feature that needs more developement. But it can currently be used\n#to predict the segement of the course, where the course is divided into NUM_LOCATIONS segments.\nTRAIN_LOCALIZER = False\nNUM_LOCATIONS = 10\nBUTTON_PRESS_NEW_TUB = False #when enabled, makes it easier to divide our data into one tub per track length if we make a new tub on each X button press.\n\n#DonkeyGym\n#Only on Ubuntu linux, you can use the simulator as a virtual donkey and\n#issue the same python manage.py drive command as usual, but have them control a virtual car.\n#This enables that, and sets the path to the simualator and the environment.\n#You will want to download the simulator binary from: https://github.com/tawnkramer/donkey_gym/releases/download/v18.9/DonkeySimLinux.zip\n#then extract that and modify DONKEY_SIM_PATH.\nDONKEY_GYM = True\nDONKEY_SIM_PATH = \"path to sim\" #\"/home/tkramer/projects/sdsandbox/sdsim/build/DonkeySimLinux/donkey_sim.x86_64\" when racing on virtual-race-league use \"remote\", or user \"remote\" when you want to start the sim manually first.\nDONKEY_GYM_ENV_NAME = \"donkey-generated-track-v0\" # (\"donkey-generated-track-v0\"|\"donkey-generated-roads-v0\"|\"donkey-warehouse-v0\"|\"donkey-avc-sparkfun-v0\")\nGYM_CONF = { \"img_h\" : IMAGE_H, \"img_w\" : IMAGE_W, \"body_style\" : \"donkey\", \"body_rgb\" : (128, 128, 128), \"car_name\" : \"car\", \"font_size\" : 100 } # body style(donkey|bare|car01) body rgb 0-255\nGYM_CONF[\"racer_name\"] = \"Your Name\"\nGYM_CONF[\"country\"] = \"Place\"\nGYM_CONF[\"bio\"] = \"I race robots.\"\n\nSIM_HOST = \"127.0.0.1\" # when racing on virtual-race-league use host \"trainmydonkey.com\"\nSIM_ARTIFICIAL_LATENCY = 0 # this is the millisecond latency in controls. Can use useful in emulating the delay when useing a remote server. values of 100 to 400 probably reasonable.\n\n#publish camera over network\n#This is used to create a tcp service to pushlish the camera feed\nPUB_CAMERA_IMAGES = False\n\n#When racing, to give the ai a boost, configure these values.\nAI_LAUNCH_DURATION = 0.0 # the ai will output throttle for this many seconds\nAI_LAUNCH_THROTTLE = 0.0 # the ai will output this throttle value\nAI_LAUNCH_ENABLE_BUTTON = 'R2' # this keypress will enable this boost. It must be enabled before each use to prevent accidental trigger.\nAI_LAUNCH_KEEP_ENABLED = False # when False ( default) you will need to hit the AI_LAUNCH_ENABLE_BUTTON for each use. This is safest. When this True, is active on each trip into \"local\" ai mode.\n\n#Scale the output of the throttle of the ai pilot for all model types.\nAI_THROTTLE_MULT = 1.0 # this multiplier will scale every throttle value for all output from NN models\n\n#Path following\nPATH_FILENAME = \"donkey_path.pkl\" # the path will be saved to this filename\nPATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page\nPATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed.\nPATH_MIN_DIST = 0.3 # after travelling this distance (m), save a path point\nPID_P = -10.0 # proportional mult for PID path follower\nPID_I = 0.000 # integral mult for PID path follower\nPID_D = -0.2 # differential mult for PID path follower\nPID_THROTTLE = 0.2 # constant throttle value during path following\nUSE_CONSTANT_THROTTLE = False # whether or not to use the constant throttle or variable throttle captured during path recording\nSAVE_PATH_BTN = \"cross\" # joystick button to save path\nRESET_ORIGIN_BTN = \"triangle\" # joystick button to press to move car back to origin\n\n# Intel Realsense D435 and D435i depth sensing camera\nREALSENSE_D435_RGB = True # True to capture RGB image\nREALSENSE_D435_DEPTH = True # True to capture depth as image array\nREALSENSE_D435_IMU = False # True to capture IMU data (D435i only)\nREALSENSE_D435_ID = None # serial number of camera or None if you only have one camera (it will autodetect)\n\n# Stop Sign Detector\nSTOP_SIGN_DETECTOR = False\nSTOP_SIGN_MIN_SCORE = 0.2\nSTOP_SIGN_SHOW_BOUNDING_BOX = True\n",
"<docstring token>\nimport os\nCAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(CAR_PATH, 'data')\nMODELS_PATH = os.path.join(CAR_PATH, 'models')\nDRIVE_LOOP_HZ = 20\nMAX_LOOPS = None\nCAMERA_TYPE = 'MOCK'\nIMAGE_W = 160\nIMAGE_H = 120\nIMAGE_DEPTH = 3\nCAMERA_FRAMERATE = DRIVE_LOOP_HZ\nCAMERA_VFLIP = False\nCAMERA_HFLIP = False\nCSIC_CAM_GSTREAMER_FLIP_PARM = 0\nPCA9685_I2C_ADDR = 64\nPCA9685_I2C_BUSNUM = None\nUSE_SSD1306_128_32 = False\nSSD1306_128_32_I2C_BUSNUM = 1\nDRIVE_TRAIN_TYPE = 'MOCK'\nSTEERING_CHANNEL = 1\nSTEERING_LEFT_PWM = 460\nSTEERING_RIGHT_PWM = 290\nSTEERING_PWM_PIN = 13\nSTEERING_PWM_FREQ = 50\nSTEERING_PWM_INVERTED = False\nTHROTTLE_CHANNEL = 0\nTHROTTLE_FORWARD_PWM = 500\nTHROTTLE_STOPPED_PWM = 370\nTHROTTLE_REVERSE_PWM = 220\nTHROTTLE_PWM_PIN = 18\nTHROTTLE_PWM_FREQ = 50\nTHROTTLE_PWM_INVERTED = False\nHBRIDGE_PIN_LEFT = 18\nHBRIDGE_PIN_RIGHT = 16\nHBRIDGE_PIN_FWD = 15\nHBRIDGE_PIN_BWD = 13\nHBRIDGE_PIN_LEFT_FWD = 18\nHBRIDGE_PIN_LEFT_BWD = 16\nHBRIDGE_PIN_RIGHT_FWD = 15\nHBRIDGE_PIN_RIGHT_BWD = 13\nDEFAULT_MODEL_TYPE = 'linear'\nBATCH_SIZE = 128\nTRAIN_TEST_SPLIT = 0.8\nMAX_EPOCHS = 100\nSHOW_PLOT = True\nVERBOSE_TRAIN = True\nUSE_EARLY_STOP = True\nEARLY_STOP_PATIENCE = 5\nMIN_DELTA = 0.0005\nPRINT_MODEL_SUMMARY = True\nOPTIMIZER = None\nLEARNING_RATE = 0.001\nLEARNING_RATE_DECAY = 0.0\nSEND_BEST_MODEL_TO_PI = False\nPRUNE_CNN = False\nPRUNE_PERCENT_TARGET = 75\nPRUNE_PERCENT_PER_ITERATION = 20\nPRUNE_VAL_LOSS_DEGRADATION_LIMIT = 0.2\nPRUNE_EVAL_PERCENT_OF_DATASET = 0.05\nFREEZE_LAYERS = False\nNUM_LAST_LAYERS_TO_TRAIN = 7\nWEB_CONTROL_PORT = 8887\nWEB_INIT_MODE = 'user'\nUSE_JOYSTICK_AS_DEFAULT = False\nJOYSTICK_MAX_THROTTLE = 0.5\nJOYSTICK_STEERING_SCALE = 1.0\nAUTO_RECORD_ON_THROTTLE = True\nCONTROLLER_TYPE = 'xbox'\nUSE_NETWORKED_JS = False\nNETWORK_JS_SERVER_IP = None\nJOYSTICK_DEADZONE = 0.01\nJOYSTICK_THROTTLE_DIR = 1.0\nUSE_FPV = False\nJOYSTICK_DEVICE_FILE = '/dev/input/js0'\nMODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8\nSEQUENCE_LENGTH = 3\nHAVE_IMU = False\nIMU_SENSOR = 'mpu6050'\nIMU_DLP_CONFIG = 0\nHAVE_SOMBRERO = False\nHAVE_ROBOHAT = False\nMM1_STEERING_MID = 1500\nMM1_MAX_FORWARD = 2000\nMM1_STOPPED_PWM = 1500\nMM1_MAX_REVERSE = 1000\nMM1_SHOW_STEERING_VALUE = False\nMM1_SERIAL_PORT = '/dev/ttyS0'\nRECORD_DURING_AI = False\nAUTO_CREATE_NEW_TUB = False\nHAVE_RGB_LED = False\nLED_INVERT = False\nLED_PIN_R = 12\nLED_PIN_G = 10\nLED_PIN_B = 16\nLED_R = 0\nLED_G = 0\nLED_B = 1\nREC_COUNT_ALERT = 1000\nREC_COUNT_ALERT_CYC = 15\nREC_COUNT_ALERT_BLINK_RATE = 0.4\nRECORD_ALERT_COLOR_ARR = [(0, (1, 1, 1)), (3000, (5, 5, 5)), (5000, (5, 2, \n 0)), (10000, (0, 5, 0)), (15000, (0, 5, 5)), (20000, (0, 0, 5))]\nMODEL_RELOADED_LED_R = 100\nMODEL_RELOADED_LED_G = 0\nMODEL_RELOADED_LED_B = 0\nTRAIN_BEHAVIORS = False\nBEHAVIOR_LIST = ['Left_Lane', 'Right_Lane']\nBEHAVIOR_LED_COLORS = [(0, 10, 0), (10, 0, 0)]\nTRAIN_LOCALIZER = False\nNUM_LOCATIONS = 10\nBUTTON_PRESS_NEW_TUB = False\nDONKEY_GYM = True\nDONKEY_SIM_PATH = 'path to sim'\nDONKEY_GYM_ENV_NAME = 'donkey-generated-track-v0'\nGYM_CONF = {'img_h': IMAGE_H, 'img_w': IMAGE_W, 'body_style': 'donkey',\n 'body_rgb': (128, 128, 128), 'car_name': 'car', 'font_size': 100}\nGYM_CONF['racer_name'] = 'Your Name'\nGYM_CONF['country'] = 'Place'\nGYM_CONF['bio'] = 'I race robots.'\nSIM_HOST = '127.0.0.1'\nSIM_ARTIFICIAL_LATENCY = 0\nPUB_CAMERA_IMAGES = False\nAI_LAUNCH_DURATION = 0.0\nAI_LAUNCH_THROTTLE = 0.0\nAI_LAUNCH_ENABLE_BUTTON = 'R2'\nAI_LAUNCH_KEEP_ENABLED = False\nAI_THROTTLE_MULT = 1.0\nPATH_FILENAME = 'donkey_path.pkl'\nPATH_SCALE = 5.0\nPATH_OFFSET = 0, 0\nPATH_MIN_DIST = 0.3\nPID_P = -10.0\nPID_I = 0.0\nPID_D = -0.2\nPID_THROTTLE = 0.2\nUSE_CONSTANT_THROTTLE = False\nSAVE_PATH_BTN = 'cross'\nRESET_ORIGIN_BTN = 'triangle'\nREALSENSE_D435_RGB = True\nREALSENSE_D435_DEPTH = True\nREALSENSE_D435_IMU = False\nREALSENSE_D435_ID = None\nSTOP_SIGN_DETECTOR = False\nSTOP_SIGN_MIN_SCORE = 0.2\nSTOP_SIGN_SHOW_BOUNDING_BOX = True\n",
"<docstring token>\n<import token>\nCAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(CAR_PATH, 'data')\nMODELS_PATH = os.path.join(CAR_PATH, 'models')\nDRIVE_LOOP_HZ = 20\nMAX_LOOPS = None\nCAMERA_TYPE = 'MOCK'\nIMAGE_W = 160\nIMAGE_H = 120\nIMAGE_DEPTH = 3\nCAMERA_FRAMERATE = DRIVE_LOOP_HZ\nCAMERA_VFLIP = False\nCAMERA_HFLIP = False\nCSIC_CAM_GSTREAMER_FLIP_PARM = 0\nPCA9685_I2C_ADDR = 64\nPCA9685_I2C_BUSNUM = None\nUSE_SSD1306_128_32 = False\nSSD1306_128_32_I2C_BUSNUM = 1\nDRIVE_TRAIN_TYPE = 'MOCK'\nSTEERING_CHANNEL = 1\nSTEERING_LEFT_PWM = 460\nSTEERING_RIGHT_PWM = 290\nSTEERING_PWM_PIN = 13\nSTEERING_PWM_FREQ = 50\nSTEERING_PWM_INVERTED = False\nTHROTTLE_CHANNEL = 0\nTHROTTLE_FORWARD_PWM = 500\nTHROTTLE_STOPPED_PWM = 370\nTHROTTLE_REVERSE_PWM = 220\nTHROTTLE_PWM_PIN = 18\nTHROTTLE_PWM_FREQ = 50\nTHROTTLE_PWM_INVERTED = False\nHBRIDGE_PIN_LEFT = 18\nHBRIDGE_PIN_RIGHT = 16\nHBRIDGE_PIN_FWD = 15\nHBRIDGE_PIN_BWD = 13\nHBRIDGE_PIN_LEFT_FWD = 18\nHBRIDGE_PIN_LEFT_BWD = 16\nHBRIDGE_PIN_RIGHT_FWD = 15\nHBRIDGE_PIN_RIGHT_BWD = 13\nDEFAULT_MODEL_TYPE = 'linear'\nBATCH_SIZE = 128\nTRAIN_TEST_SPLIT = 0.8\nMAX_EPOCHS = 100\nSHOW_PLOT = True\nVERBOSE_TRAIN = True\nUSE_EARLY_STOP = True\nEARLY_STOP_PATIENCE = 5\nMIN_DELTA = 0.0005\nPRINT_MODEL_SUMMARY = True\nOPTIMIZER = None\nLEARNING_RATE = 0.001\nLEARNING_RATE_DECAY = 0.0\nSEND_BEST_MODEL_TO_PI = False\nPRUNE_CNN = False\nPRUNE_PERCENT_TARGET = 75\nPRUNE_PERCENT_PER_ITERATION = 20\nPRUNE_VAL_LOSS_DEGRADATION_LIMIT = 0.2\nPRUNE_EVAL_PERCENT_OF_DATASET = 0.05\nFREEZE_LAYERS = False\nNUM_LAST_LAYERS_TO_TRAIN = 7\nWEB_CONTROL_PORT = 8887\nWEB_INIT_MODE = 'user'\nUSE_JOYSTICK_AS_DEFAULT = False\nJOYSTICK_MAX_THROTTLE = 0.5\nJOYSTICK_STEERING_SCALE = 1.0\nAUTO_RECORD_ON_THROTTLE = True\nCONTROLLER_TYPE = 'xbox'\nUSE_NETWORKED_JS = False\nNETWORK_JS_SERVER_IP = None\nJOYSTICK_DEADZONE = 0.01\nJOYSTICK_THROTTLE_DIR = 1.0\nUSE_FPV = False\nJOYSTICK_DEVICE_FILE = '/dev/input/js0'\nMODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8\nSEQUENCE_LENGTH = 3\nHAVE_IMU = False\nIMU_SENSOR = 'mpu6050'\nIMU_DLP_CONFIG = 0\nHAVE_SOMBRERO = False\nHAVE_ROBOHAT = False\nMM1_STEERING_MID = 1500\nMM1_MAX_FORWARD = 2000\nMM1_STOPPED_PWM = 1500\nMM1_MAX_REVERSE = 1000\nMM1_SHOW_STEERING_VALUE = False\nMM1_SERIAL_PORT = '/dev/ttyS0'\nRECORD_DURING_AI = False\nAUTO_CREATE_NEW_TUB = False\nHAVE_RGB_LED = False\nLED_INVERT = False\nLED_PIN_R = 12\nLED_PIN_G = 10\nLED_PIN_B = 16\nLED_R = 0\nLED_G = 0\nLED_B = 1\nREC_COUNT_ALERT = 1000\nREC_COUNT_ALERT_CYC = 15\nREC_COUNT_ALERT_BLINK_RATE = 0.4\nRECORD_ALERT_COLOR_ARR = [(0, (1, 1, 1)), (3000, (5, 5, 5)), (5000, (5, 2, \n 0)), (10000, (0, 5, 0)), (15000, (0, 5, 5)), (20000, (0, 0, 5))]\nMODEL_RELOADED_LED_R = 100\nMODEL_RELOADED_LED_G = 0\nMODEL_RELOADED_LED_B = 0\nTRAIN_BEHAVIORS = False\nBEHAVIOR_LIST = ['Left_Lane', 'Right_Lane']\nBEHAVIOR_LED_COLORS = [(0, 10, 0), (10, 0, 0)]\nTRAIN_LOCALIZER = False\nNUM_LOCATIONS = 10\nBUTTON_PRESS_NEW_TUB = False\nDONKEY_GYM = True\nDONKEY_SIM_PATH = 'path to sim'\nDONKEY_GYM_ENV_NAME = 'donkey-generated-track-v0'\nGYM_CONF = {'img_h': IMAGE_H, 'img_w': IMAGE_W, 'body_style': 'donkey',\n 'body_rgb': (128, 128, 128), 'car_name': 'car', 'font_size': 100}\nGYM_CONF['racer_name'] = 'Your Name'\nGYM_CONF['country'] = 'Place'\nGYM_CONF['bio'] = 'I race robots.'\nSIM_HOST = '127.0.0.1'\nSIM_ARTIFICIAL_LATENCY = 0\nPUB_CAMERA_IMAGES = False\nAI_LAUNCH_DURATION = 0.0\nAI_LAUNCH_THROTTLE = 0.0\nAI_LAUNCH_ENABLE_BUTTON = 'R2'\nAI_LAUNCH_KEEP_ENABLED = False\nAI_THROTTLE_MULT = 1.0\nPATH_FILENAME = 'donkey_path.pkl'\nPATH_SCALE = 5.0\nPATH_OFFSET = 0, 0\nPATH_MIN_DIST = 0.3\nPID_P = -10.0\nPID_I = 0.0\nPID_D = -0.2\nPID_THROTTLE = 0.2\nUSE_CONSTANT_THROTTLE = False\nSAVE_PATH_BTN = 'cross'\nRESET_ORIGIN_BTN = 'triangle'\nREALSENSE_D435_RGB = True\nREALSENSE_D435_DEPTH = True\nREALSENSE_D435_IMU = False\nREALSENSE_D435_ID = None\nSTOP_SIGN_DETECTOR = False\nSTOP_SIGN_MIN_SCORE = 0.2\nSTOP_SIGN_SHOW_BOUNDING_BOX = True\n",
"<docstring token>\n<import token>\n<assignment token>\n"
] | false |
99,746 | 2f0c17fe6385591ee653c0a069e9923d07d22e8a | from iso.control.config import Config
from iso.gfx.sprite import Sprite
from iso.gfx.map import TileSet, TileMap
import json
from collections import defaultdict
class Scenario(Config):
def __init__(self, path):
super().__init__(path)
self.map = TileMap(self.get("map"))
self.entities = defaultdict(list)
self.gui = self.get("gui")
self._load_entities(self.get("entities", []))
def _load_entities(self, entity_list):
for spec in entity_list:
with open(spec['id']) as fh:
templ = json.load(fh)
# for now entity = sprite
e = Sprite(pos=spec['pos'], tile_set=TileSet(templ['tile_set']))
layer = spec.get('layer', 1)
self.entities[layer].append(e)
| [
"from iso.control.config import Config\nfrom iso.gfx.sprite import Sprite\nfrom iso.gfx.map import TileSet, TileMap\nimport json\nfrom collections import defaultdict\n\nclass Scenario(Config):\n def __init__(self, path):\n super().__init__(path)\n self.map = TileMap(self.get(\"map\"))\n self.entities = defaultdict(list)\n self.gui = self.get(\"gui\")\n\n self._load_entities(self.get(\"entities\", []))\n\n def _load_entities(self, entity_list):\n for spec in entity_list:\n with open(spec['id']) as fh:\n templ = json.load(fh)\n # for now entity = sprite\n e = Sprite(pos=spec['pos'], tile_set=TileSet(templ['tile_set']))\n layer = spec.get('layer', 1)\n self.entities[layer].append(e)\n",
"from iso.control.config import Config\nfrom iso.gfx.sprite import Sprite\nfrom iso.gfx.map import TileSet, TileMap\nimport json\nfrom collections import defaultdict\n\n\nclass Scenario(Config):\n\n def __init__(self, path):\n super().__init__(path)\n self.map = TileMap(self.get('map'))\n self.entities = defaultdict(list)\n self.gui = self.get('gui')\n self._load_entities(self.get('entities', []))\n\n def _load_entities(self, entity_list):\n for spec in entity_list:\n with open(spec['id']) as fh:\n templ = json.load(fh)\n e = Sprite(pos=spec['pos'], tile_set=TileSet(templ['tile_set']))\n layer = spec.get('layer', 1)\n self.entities[layer].append(e)\n",
"<import token>\n\n\nclass Scenario(Config):\n\n def __init__(self, path):\n super().__init__(path)\n self.map = TileMap(self.get('map'))\n self.entities = defaultdict(list)\n self.gui = self.get('gui')\n self._load_entities(self.get('entities', []))\n\n def _load_entities(self, entity_list):\n for spec in entity_list:\n with open(spec['id']) as fh:\n templ = json.load(fh)\n e = Sprite(pos=spec['pos'], tile_set=TileSet(templ['tile_set']))\n layer = spec.get('layer', 1)\n self.entities[layer].append(e)\n",
"<import token>\n\n\nclass Scenario(Config):\n\n def __init__(self, path):\n super().__init__(path)\n self.map = TileMap(self.get('map'))\n self.entities = defaultdict(list)\n self.gui = self.get('gui')\n self._load_entities(self.get('entities', []))\n <function token>\n",
"<import token>\n\n\nclass Scenario(Config):\n <function token>\n <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,747 | 6e29a72cfc927179706fedc7e6b09f1deeec59e5 | import sys
sys.path.append('target/release')
import libpy_prime_number_checker as py_prime_checker
class PyPrime:
@staticmethod
def is_prime_by_rust(num):
return py_prime_checker.is_prime(num)
@staticmethod
def is_prime_unoptimized_by_rust(num):
return py_prime_checker.is_prime_unoptimized(num)
@staticmethod
def is_prime_by_python(num):
"""
Same algo in python
"""
if num == 2:
return True
elif num % 2 == 0 or num <= 1:
# even or smaller then one
return False
else:
res = True
partial_num_range = int(num / 4) + 1
for i in range(1, partial_num_range):
if num % (2 * i + 1) == 0:
res = False
break
return res
@staticmethod
def is_prime_unoptimized_by_python(num):
if num <= 1:
return False
else:
res = True
for i in range(2, num):
if num % i == 0:
res = False
break
return res
| [
"import sys\nsys.path.append('target/release')\nimport libpy_prime_number_checker as py_prime_checker\n\nclass PyPrime:\n\n @staticmethod\n def is_prime_by_rust(num):\n return py_prime_checker.is_prime(num)\n\n @staticmethod\n def is_prime_unoptimized_by_rust(num):\n return py_prime_checker.is_prime_unoptimized(num)\n \n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n # even or smaller then one\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n\n",
"import sys\nsys.path.append('target/release')\nimport libpy_prime_number_checker as py_prime_checker\n\n\nclass PyPrime:\n\n @staticmethod\n def is_prime_by_rust(num):\n return py_prime_checker.is_prime(num)\n\n @staticmethod\n def is_prime_unoptimized_by_rust(num):\n return py_prime_checker.is_prime_unoptimized(num)\n\n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\nsys.path.append('target/release')\n<import token>\n\n\nclass PyPrime:\n\n @staticmethod\n def is_prime_by_rust(num):\n return py_prime_checker.is_prime(num)\n\n @staticmethod\n def is_prime_unoptimized_by_rust(num):\n return py_prime_checker.is_prime_unoptimized(num)\n\n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\n<code token>\n<import token>\n\n\nclass PyPrime:\n\n @staticmethod\n def is_prime_by_rust(num):\n return py_prime_checker.is_prime(num)\n\n @staticmethod\n def is_prime_unoptimized_by_rust(num):\n return py_prime_checker.is_prime_unoptimized(num)\n\n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\n<code token>\n<import token>\n\n\nclass PyPrime:\n <function token>\n\n @staticmethod\n def is_prime_unoptimized_by_rust(num):\n return py_prime_checker.is_prime_unoptimized(num)\n\n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\n<code token>\n<import token>\n\n\nclass PyPrime:\n <function token>\n <function token>\n\n @staticmethod\n def is_prime_by_python(num):\n \"\"\"\n Same algo in python\n \"\"\"\n if num == 2:\n return True\n elif num % 2 == 0 or num <= 1:\n return False\n else:\n res = True\n partial_num_range = int(num / 4) + 1\n for i in range(1, partial_num_range):\n if num % (2 * i + 1) == 0:\n res = False\n break\n return res\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\n<code token>\n<import token>\n\n\nclass PyPrime:\n <function token>\n <function token>\n <function token>\n\n @staticmethod\n def is_prime_unoptimized_by_python(num):\n if num <= 1:\n return False\n else:\n res = True\n for i in range(2, num):\n if num % i == 0:\n res = False\n break\n return res\n",
"<import token>\n<code token>\n<import token>\n\n\nclass PyPrime:\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n"
] | false |
99,748 | 4c04b7ab2ee0a970a04c06be1513dd3d22425c60 | # ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
# pylint: disable=protected-access
from typing import Any, Iterable
from azure.ai.ml._restclient.v2023_04_01_preview import AzureMachineLearningWorkspaces as ServiceClient042023Preview
from azure.ai.ml._scope_dependent_operations import (
OperationConfig,
OperationsContainer,
OperationScope,
_ScopeDependentOperations,
)
from azure.ai.ml._telemetry import ActivityType, monitor_with_activity, monitor_with_telemetry_mixin
from azure.ai.ml._utils._logger_utils import OpsLogger
from azure.ai.ml.entities import Job, JobSchedule, Schedule
from azure.ai.ml.entities._monitoring.schedule import MonitorSchedule
from azure.core.credentials import TokenCredential
from azure.core.polling import LROPoller
from azure.core.tracing.decorator import distributed_trace
from .._restclient.v2022_10_01.models import ScheduleListViewType
from .._utils._arm_id_utils import is_ARM_id_for_parented_resource
from .._utils.utils import snake_to_camel
from .._utils._azureml_polling import AzureMLPolling
from ..constants._common import (
ARM_ID_PREFIX,
AzureMLResourceType,
LROConfigurations,
NAMED_RESOURCE_ID_FORMAT_WITH_PARENT,
AZUREML_RESOURCE_PROVIDER,
)
from ..constants._monitoring import MonitorSignalType
from . import JobOperations
from ._job_ops_helper import stream_logs_until_completion
from ._operation_orchestrator import OperationOrchestrator
ops_logger = OpsLogger(__name__)
logger, module_logger = ops_logger.package_logger, ops_logger.module_logger
class ScheduleOperations(_ScopeDependentOperations):
# pylint: disable=too-many-instance-attributes
"""
ScheduleOperations
You should not instantiate this class directly.
Instead, you should create an MLClient instance that instantiates it for you and attaches it as an attribute.
"""
def __init__(
self,
operation_scope: OperationScope,
operation_config: OperationConfig,
service_client_04_2023_preview: ServiceClient042023Preview,
all_operations: OperationsContainer,
credential: TokenCredential,
**kwargs: Any,
):
super(ScheduleOperations, self).__init__(operation_scope, operation_config)
ops_logger.update_info(kwargs)
self.service_client = service_client_04_2023_preview.schedules
self._all_operations = all_operations
self._stream_logs_until_completion = stream_logs_until_completion
# Dataplane service clients are lazily created as they are needed
self._runs_operations_client = None
self._dataset_dataplane_operations_client = None
self._model_dataplane_operations_client = None
# Kwargs to propagate to dataplane service clients
self._service_client_kwargs = kwargs.pop("_service_client_kwargs", {})
self._api_base_url = None
self._container = "azureml"
self._credential = credential
self._orchestrators = OperationOrchestrator(self._all_operations, self._operation_scope, self._operation_config)
self._kwargs = kwargs
@property
def _job_operations(self) -> JobOperations:
return self._all_operations.get_operation(AzureMLResourceType.JOB, lambda x: isinstance(x, JobOperations))
@distributed_trace
@monitor_with_activity(logger, "Schedule.List", ActivityType.PUBLICAPI)
def list(
self,
*,
list_view_type: ScheduleListViewType = ScheduleListViewType.ENABLED_ONLY, # pylint: disable=unused-argument
**kwargs,
) -> Iterable[Schedule]:
"""List schedules in specified workspace.
:param list_view_type: View type for including/excluding (for example)
archived schedules. Default: ENABLED_ONLY.
:type list_view_type: Optional[ScheduleListViewType]
:return: An iterator to list Schedule.
:rtype: Iterable[Schedule]
"""
def safe_from_rest_object(objs):
result = []
for obj in objs:
try:
result.append(Schedule._from_rest_object(obj))
except Exception as e: # pylint: disable=broad-except
print(f"Translate {obj.name} to Schedule failed with: {e}")
return result
return self.service_client.list(
resource_group_name=self._operation_scope.resource_group_name,
workspace_name=self._workspace_name,
list_view_type=list_view_type,
cls=safe_from_rest_object,
**self._kwargs,
**kwargs,
)
def _get_polling(self, name):
"""Return the polling with custom poll interval."""
path_format_arguments = {
"scheduleName": name,
"resourceGroupName": self._resource_group_name,
"workspaceName": self._workspace_name,
}
return AzureMLPolling(
LROConfigurations.POLL_INTERVAL,
path_format_arguments=path_format_arguments,
)
@distributed_trace
@monitor_with_activity(logger, "Schedule.Delete", ActivityType.PUBLICAPI)
def begin_delete(
self,
name: str,
**kwargs,
) -> LROPoller[None]:
"""Delete schedule.
:param name: Schedule name.
:type name: str
"""
poller = self.service_client.begin_delete(
resource_group_name=self._operation_scope.resource_group_name,
workspace_name=self._workspace_name,
name=name,
polling=self._get_polling(name),
**self._kwargs,
**kwargs,
)
return poller
@distributed_trace
@monitor_with_telemetry_mixin(logger, "Schedule.Get", ActivityType.PUBLICAPI)
def get(
self,
name: str,
**kwargs,
) -> Schedule:
"""Get a schedule.
:param name: Schedule name.
:type name: str
:return: The schedule object.
:rtype: Schedule
"""
return self.service_client.get(
resource_group_name=self._operation_scope.resource_group_name,
workspace_name=self._workspace_name,
name=name,
cls=lambda _, obj, __: Schedule._from_rest_object(obj),
**self._kwargs,
**kwargs,
)
@distributed_trace
@monitor_with_telemetry_mixin(logger, "Schedule.CreateOrUpdate", ActivityType.PUBLICAPI)
def begin_create_or_update(
self,
schedule: Schedule,
**kwargs,
) -> LROPoller[Schedule]:
"""Create or update schedule.
:param schedule: Schedule definition.
:type schedule: Schedule
:return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False
:rtype: Union[LROPoller, Schedule]
:rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]
"""
if isinstance(schedule, JobSchedule):
schedule._validate(raise_error=True)
if isinstance(schedule.create_job, Job):
# Create all dependent resources for job inside schedule
self._job_operations._resolve_arm_id_or_upload_dependencies(schedule.create_job)
elif isinstance(schedule, MonitorSchedule):
# resolve ARM id for target, compute, and input datasets for each signal
self._resolve_monitor_schedule_arm_id(schedule)
# Create schedule
schedule_data = schedule._to_rest_object()
poller = self.service_client.begin_create_or_update(
resource_group_name=self._operation_scope.resource_group_name,
workspace_name=self._workspace_name,
name=schedule.name,
cls=lambda _, obj, __: Schedule._from_rest_object(obj),
body=schedule_data,
polling=self._get_polling(schedule.name),
**self._kwargs,
**kwargs,
)
return poller
@distributed_trace
@monitor_with_activity(logger, "Schedule.Enable", ActivityType.PUBLICAPI)
def begin_enable(
self,
name: str,
**kwargs,
) -> LROPoller[Schedule]:
"""Enable a schedule.
:param name: Schedule name.
:type name: str
:return: An instance of LROPoller that returns Schedule
:rtype: LROPoller
"""
schedule = self.get(name=name)
schedule._is_enabled = True
return self.begin_create_or_update(schedule, **kwargs)
@distributed_trace
@monitor_with_activity(logger, "Schedule.Disable", ActivityType.PUBLICAPI)
def begin_disable(
self,
name: str,
**kwargs,
) -> LROPoller[Schedule]:
"""Disable a schedule.
:param name: Schedule name.
:type name: str
:return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False
:rtype: LROPoller
"""
schedule = self.get(name=name)
schedule._is_enabled = False
return self.begin_create_or_update(schedule, **kwargs)
def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule) -> None:
# resolve compute ID
schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(
schedule.create_monitor.compute, AzureMLResourceType.COMPUTE, register_asset=False
)
# resolve target ARM ID
target = schedule.create_monitor.monitoring_target
if target and target.endpoint_deployment_id:
target.endpoint_deployment_id = (
target.endpoint_deployment_id[len(ARM_ID_PREFIX) :]
if target.endpoint_deployment_id.startswith(ARM_ID_PREFIX)
else target.endpoint_deployment_id
)
# if it is an ARM ID, don't process it
if not is_ARM_id_for_parented_resource(
target.endpoint_deployment_id,
snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),
AzureMLResourceType.DEPLOYMENT,
):
endpoint_name, deployment_name = target.endpoint_deployment_id.split(":")
target.endpoint_deployment_id = NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(
self._subscription_id,
self._resource_group_name,
AZUREML_RESOURCE_PROVIDER,
self._workspace_name,
snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),
endpoint_name,
AzureMLResourceType.DEPLOYMENT,
deployment_name,
)
elif target and target.model_id:
target.model_id = self._orchestrators.get_asset_arm_id(
target.model_id,
AzureMLResourceType.MODEL,
register_asset=False,
)
# resolve input paths and preprocessing component ids
for signal in schedule.create_monitor.monitoring_signals.values():
if signal.type == MonitorSignalType.CUSTOM:
for input_value in signal.input_datasets.values():
self._job_operations._resolve_job_input(input_value.input_dataset, schedule._base_path)
input_value.pre_processing_component = self._orchestrators.get_asset_arm_id(
asset=input_value.pre_processing_component, azureml_type=AzureMLResourceType.COMPONENT
)
else:
self._job_operations._resolve_job_inputs(
[signal.target_dataset.dataset.input_dataset, signal.baseline_dataset.input_dataset],
schedule._base_path,
)
signal.target_dataset.dataset.pre_processing_component = self._orchestrators.get_asset_arm_id(
asset=signal.target_dataset.dataset.pre_processing_component,
azureml_type=AzureMLResourceType.COMPONENT,
)
signal.baseline_dataset.pre_processing_component = self._orchestrators.get_asset_arm_id(
asset=signal.baseline_dataset.pre_processing_component, azureml_type=AzureMLResourceType.COMPONENT
)
| [
"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n# pylint: disable=protected-access\nfrom typing import Any, Iterable\n\nfrom azure.ai.ml._restclient.v2023_04_01_preview import AzureMachineLearningWorkspaces as ServiceClient042023Preview\nfrom azure.ai.ml._scope_dependent_operations import (\n OperationConfig,\n OperationsContainer,\n OperationScope,\n _ScopeDependentOperations,\n)\n\nfrom azure.ai.ml._telemetry import ActivityType, monitor_with_activity, monitor_with_telemetry_mixin\nfrom azure.ai.ml._utils._logger_utils import OpsLogger\nfrom azure.ai.ml.entities import Job, JobSchedule, Schedule\nfrom azure.ai.ml.entities._monitoring.schedule import MonitorSchedule\nfrom azure.core.credentials import TokenCredential\nfrom azure.core.polling import LROPoller\nfrom azure.core.tracing.decorator import distributed_trace\n\nfrom .._restclient.v2022_10_01.models import ScheduleListViewType\nfrom .._utils._arm_id_utils import is_ARM_id_for_parented_resource\nfrom .._utils.utils import snake_to_camel\nfrom .._utils._azureml_polling import AzureMLPolling\nfrom ..constants._common import (\n ARM_ID_PREFIX,\n AzureMLResourceType,\n LROConfigurations,\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT,\n AZUREML_RESOURCE_PROVIDER,\n)\nfrom ..constants._monitoring import MonitorSignalType\nfrom . import JobOperations\nfrom ._job_ops_helper import stream_logs_until_completion\nfrom ._operation_orchestrator import OperationOrchestrator\n\nops_logger = OpsLogger(__name__)\nlogger, module_logger = ops_logger.package_logger, ops_logger.module_logger\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n # pylint: disable=too-many-instance-attributes\n \"\"\"\n ScheduleOperations\n\n You should not instantiate this class directly.\n Instead, you should create an MLClient instance that instantiates it for you and attaches it as an attribute.\n \"\"\"\n\n def __init__(\n self,\n operation_scope: OperationScope,\n operation_config: OperationConfig,\n service_client_04_2023_preview: ServiceClient042023Preview,\n all_operations: OperationsContainer,\n credential: TokenCredential,\n **kwargs: Any,\n ):\n super(ScheduleOperations, self).__init__(operation_scope, operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n # Dataplane service clients are lazily created as they are needed\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n # Kwargs to propagate to dataplane service clients\n self._service_client_kwargs = kwargs.pop(\"_service_client_kwargs\", {})\n self._api_base_url = None\n self._container = \"azureml\"\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations, self._operation_scope, self._operation_config)\n\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) -> JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, \"Schedule.List\", ActivityType.PUBLICAPI)\n def list(\n self,\n *,\n list_view_type: ScheduleListViewType = ScheduleListViewType.ENABLED_ONLY, # pylint: disable=unused-argument\n **kwargs,\n ) -> Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e: # pylint: disable=broad-except\n print(f\"Translate {obj.name} to Schedule failed with: {e}\")\n return result\n\n return self.service_client.list(\n resource_group_name=self._operation_scope.resource_group_name,\n workspace_name=self._workspace_name,\n list_view_type=list_view_type,\n cls=safe_from_rest_object,\n **self._kwargs,\n **kwargs,\n )\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {\n \"scheduleName\": name,\n \"resourceGroupName\": self._resource_group_name,\n \"workspaceName\": self._workspace_name,\n }\n return AzureMLPolling(\n LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments,\n )\n\n @distributed_trace\n @monitor_with_activity(logger, \"Schedule.Delete\", ActivityType.PUBLICAPI)\n def begin_delete(\n self,\n name: str,\n **kwargs,\n ) -> LROPoller[None]:\n \"\"\"Delete schedule.\n\n :param name: Schedule name.\n :type name: str\n \"\"\"\n poller = self.service_client.begin_delete(\n resource_group_name=self._operation_scope.resource_group_name,\n workspace_name=self._workspace_name,\n name=name,\n polling=self._get_polling(name),\n **self._kwargs,\n **kwargs,\n )\n return poller\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, \"Schedule.Get\", ActivityType.PUBLICAPI)\n def get(\n self,\n name: str,\n **kwargs,\n ) -> Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(\n resource_group_name=self._operation_scope.resource_group_name,\n workspace_name=self._workspace_name,\n name=name,\n cls=lambda _, obj, __: Schedule._from_rest_object(obj),\n **self._kwargs,\n **kwargs,\n )\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, \"Schedule.CreateOrUpdate\", ActivityType.PUBLICAPI)\n def begin_create_or_update(\n self,\n schedule: Schedule,\n **kwargs,\n ) -> LROPoller[Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n # Create all dependent resources for job inside schedule\n self._job_operations._resolve_arm_id_or_upload_dependencies(schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n # resolve ARM id for target, compute, and input datasets for each signal\n self._resolve_monitor_schedule_arm_id(schedule)\n # Create schedule\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(\n resource_group_name=self._operation_scope.resource_group_name,\n workspace_name=self._workspace_name,\n name=schedule.name,\n cls=lambda _, obj, __: Schedule._from_rest_object(obj),\n body=schedule_data,\n polling=self._get_polling(schedule.name),\n **self._kwargs,\n **kwargs,\n )\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, \"Schedule.Enable\", ActivityType.PUBLICAPI)\n def begin_enable(\n self,\n name: str,\n **kwargs,\n ) -> LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, \"Schedule.Disable\", ActivityType.PUBLICAPI)\n def begin_disable(\n self,\n name: str,\n **kwargs,\n ) -> LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule) -> None:\n # resolve compute ID\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE, register_asset=False\n )\n\n # resolve target ARM ID\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = (\n target.endpoint_deployment_id[len(ARM_ID_PREFIX) :]\n if target.endpoint_deployment_id.startswith(ARM_ID_PREFIX)\n else target.endpoint_deployment_id\n )\n\n # if it is an ARM ID, don't process it\n if not is_ARM_id_for_parented_resource(\n target.endpoint_deployment_id,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n AzureMLResourceType.DEPLOYMENT,\n ):\n endpoint_name, deployment_name = target.endpoint_deployment_id.split(\":\")\n target.endpoint_deployment_id = NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(\n self._subscription_id,\n self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER,\n self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name,\n AzureMLResourceType.DEPLOYMENT,\n deployment_name,\n )\n\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(\n target.model_id,\n AzureMLResourceType.MODEL,\n register_asset=False,\n )\n\n # resolve input paths and preprocessing component ids\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.input_dataset, schedule._base_path)\n input_value.pre_processing_component = self._orchestrators.get_asset_arm_id(\n asset=input_value.pre_processing_component, azureml_type=AzureMLResourceType.COMPONENT\n )\n else:\n self._job_operations._resolve_job_inputs(\n [signal.target_dataset.dataset.input_dataset, signal.baseline_dataset.input_dataset],\n schedule._base_path,\n )\n signal.target_dataset.dataset.pre_processing_component = self._orchestrators.get_asset_arm_id(\n asset=signal.target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT,\n )\n signal.baseline_dataset.pre_processing_component = self._orchestrators.get_asset_arm_id(\n asset=signal.baseline_dataset.pre_processing_component, azureml_type=AzureMLResourceType.COMPONENT\n )\n",
"from typing import Any, Iterable\nfrom azure.ai.ml._restclient.v2023_04_01_preview import AzureMachineLearningWorkspaces as ServiceClient042023Preview\nfrom azure.ai.ml._scope_dependent_operations import OperationConfig, OperationsContainer, OperationScope, _ScopeDependentOperations\nfrom azure.ai.ml._telemetry import ActivityType, monitor_with_activity, monitor_with_telemetry_mixin\nfrom azure.ai.ml._utils._logger_utils import OpsLogger\nfrom azure.ai.ml.entities import Job, JobSchedule, Schedule\nfrom azure.ai.ml.entities._monitoring.schedule import MonitorSchedule\nfrom azure.core.credentials import TokenCredential\nfrom azure.core.polling import LROPoller\nfrom azure.core.tracing.decorator import distributed_trace\nfrom .._restclient.v2022_10_01.models import ScheduleListViewType\nfrom .._utils._arm_id_utils import is_ARM_id_for_parented_resource\nfrom .._utils.utils import snake_to_camel\nfrom .._utils._azureml_polling import AzureMLPolling\nfrom ..constants._common import ARM_ID_PREFIX, AzureMLResourceType, LROConfigurations, NAMED_RESOURCE_ID_FORMAT_WITH_PARENT, AZUREML_RESOURCE_PROVIDER\nfrom ..constants._monitoring import MonitorSignalType\nfrom . import JobOperations\nfrom ._job_ops_helper import stream_logs_until_completion\nfrom ._operation_orchestrator import OperationOrchestrator\nops_logger = OpsLogger(__name__)\nlogger, module_logger = ops_logger.package_logger, ops_logger.module_logger\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n \"\"\"\n ScheduleOperations\n\n You should not instantiate this class directly.\n Instead, you should create an MLClient instance that instantiates it for you and attaches it as an attribute.\n \"\"\"\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Delete', ActivityType.PUBLICAPI)\n def begin_delete(self, name: str, **kwargs) ->LROPoller[None]:\n \"\"\"Delete schedule.\n\n :param name: Schedule name.\n :type name: str\n \"\"\"\n poller = self.service_client.begin_delete(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, polling=self._get_polling(name), **\n self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.Get', ActivityType.\n PUBLICAPI)\n def get(self, name: str, **kwargs) ->Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, cls=lambda _, obj, __: Schedule.\n _from_rest_object(obj), **self._kwargs, **kwargs)\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\nops_logger = OpsLogger(__name__)\nlogger, module_logger = ops_logger.package_logger, ops_logger.module_logger\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n \"\"\"\n ScheduleOperations\n\n You should not instantiate this class directly.\n Instead, you should create an MLClient instance that instantiates it for you and attaches it as an attribute.\n \"\"\"\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Delete', ActivityType.PUBLICAPI)\n def begin_delete(self, name: str, **kwargs) ->LROPoller[None]:\n \"\"\"Delete schedule.\n\n :param name: Schedule name.\n :type name: str\n \"\"\"\n poller = self.service_client.begin_delete(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, polling=self._get_polling(name), **\n self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.Get', ActivityType.\n PUBLICAPI)\n def get(self, name: str, **kwargs) ->Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, cls=lambda _, obj, __: Schedule.\n _from_rest_object(obj), **self._kwargs, **kwargs)\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n \"\"\"\n ScheduleOperations\n\n You should not instantiate this class directly.\n Instead, you should create an MLClient instance that instantiates it for you and attaches it as an attribute.\n \"\"\"\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Delete', ActivityType.PUBLICAPI)\n def begin_delete(self, name: str, **kwargs) ->LROPoller[None]:\n \"\"\"Delete schedule.\n\n :param name: Schedule name.\n :type name: str\n \"\"\"\n poller = self.service_client.begin_delete(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, polling=self._get_polling(name), **\n self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.Get', ActivityType.\n PUBLICAPI)\n def get(self, name: str, **kwargs) ->Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, cls=lambda _, obj, __: Schedule.\n _from_rest_object(obj), **self._kwargs, **kwargs)\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Delete', ActivityType.PUBLICAPI)\n def begin_delete(self, name: str, **kwargs) ->LROPoller[None]:\n \"\"\"Delete schedule.\n\n :param name: Schedule name.\n :type name: str\n \"\"\"\n poller = self.service_client.begin_delete(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, polling=self._get_polling(name), **\n self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.Get', ActivityType.\n PUBLICAPI)\n def get(self, name: str, **kwargs) ->Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, cls=lambda _, obj, __: Schedule.\n _from_rest_object(obj), **self._kwargs, **kwargs)\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.Get', ActivityType.\n PUBLICAPI)\n def get(self, name: str, **kwargs) ->Schedule:\n \"\"\"Get a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: The schedule object.\n :rtype: Schedule\n \"\"\"\n return self.service_client.get(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, name=name, cls=lambda _, obj, __: Schedule.\n _from_rest_object(obj), **self._kwargs, **kwargs)\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n\n @property\n def _job_operations(self) ->JobOperations:\n return self._all_operations.get_operation(AzureMLResourceType.JOB, \n lambda x: isinstance(x, JobOperations))\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n\n def _resolve_monitor_schedule_arm_id(self, schedule: MonitorSchedule\n ) ->None:\n schedule.create_monitor.compute = self._orchestrators.get_asset_arm_id(\n schedule.create_monitor.compute, AzureMLResourceType.COMPUTE,\n register_asset=False)\n target = schedule.create_monitor.monitoring_target\n if target and target.endpoint_deployment_id:\n target.endpoint_deployment_id = target.endpoint_deployment_id[len\n (ARM_ID_PREFIX):] if target.endpoint_deployment_id.startswith(\n ARM_ID_PREFIX) else target.endpoint_deployment_id\n if not is_ARM_id_for_parented_resource(target.\n endpoint_deployment_id, snake_to_camel(AzureMLResourceType.\n ONLINE_ENDPOINT), AzureMLResourceType.DEPLOYMENT):\n endpoint_name, deployment_name = (target.\n endpoint_deployment_id.split(':'))\n target.endpoint_deployment_id = (\n NAMED_RESOURCE_ID_FORMAT_WITH_PARENT.format(self.\n _subscription_id, self._resource_group_name,\n AZUREML_RESOURCE_PROVIDER, self._workspace_name,\n snake_to_camel(AzureMLResourceType.ONLINE_ENDPOINT),\n endpoint_name, AzureMLResourceType.DEPLOYMENT,\n deployment_name))\n elif target and target.model_id:\n target.model_id = self._orchestrators.get_asset_arm_id(target.\n model_id, AzureMLResourceType.MODEL, register_asset=False)\n for signal in schedule.create_monitor.monitoring_signals.values():\n if signal.type == MonitorSignalType.CUSTOM:\n for input_value in signal.input_datasets.values():\n self._job_operations._resolve_job_input(input_value.\n input_dataset, schedule._base_path)\n input_value.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=input_value.\n pre_processing_component, azureml_type=\n AzureMLResourceType.COMPONENT))\n else:\n self._job_operations._resolve_job_inputs([signal.\n target_dataset.dataset.input_dataset, signal.\n baseline_dataset.input_dataset], schedule._base_path)\n signal.target_dataset.dataset.pre_processing_component = (self\n ._orchestrators.get_asset_arm_id(asset=signal.\n target_dataset.dataset.pre_processing_component,\n azureml_type=AzureMLResourceType.COMPONENT))\n signal.baseline_dataset.pre_processing_component = (self.\n _orchestrators.get_asset_arm_id(asset=signal.\n baseline_dataset.pre_processing_component, azureml_type\n =AzureMLResourceType.COMPONENT))\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Enable', ActivityType.PUBLICAPI)\n def begin_enable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Enable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = True\n return self.begin_create_or_update(schedule, **kwargs)\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.Disable', ActivityType.PUBLICAPI)\n def begin_disable(self, name: str, **kwargs) ->LROPoller[Schedule]:\n \"\"\"Disable a schedule.\n\n :param name: Schedule name.\n :type name: str\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: LROPoller\n \"\"\"\n schedule = self.get(name=name)\n schedule._is_enabled = False\n return self.begin_create_or_update(schedule, **kwargs)\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n\n @distributed_trace\n @monitor_with_telemetry_mixin(logger, 'Schedule.CreateOrUpdate',\n ActivityType.PUBLICAPI)\n def begin_create_or_update(self, schedule: Schedule, **kwargs) ->LROPoller[\n Schedule]:\n \"\"\"Create or update schedule.\n\n :param schedule: Schedule definition.\n :type schedule: Schedule\n :return: An instance of LROPoller that returns Schedule if no_wait=True, or Schedule if no_wait=False\n :rtype: Union[LROPoller, Schedule]\n :rtype: Union[LROPoller, ~azure.ai.ml.entities.Schedule]\n \"\"\"\n if isinstance(schedule, JobSchedule):\n schedule._validate(raise_error=True)\n if isinstance(schedule.create_job, Job):\n self._job_operations._resolve_arm_id_or_upload_dependencies(\n schedule.create_job)\n elif isinstance(schedule, MonitorSchedule):\n self._resolve_monitor_schedule_arm_id(schedule)\n schedule_data = schedule._to_rest_object()\n poller = self.service_client.begin_create_or_update(resource_group_name\n =self._operation_scope.resource_group_name, workspace_name=self\n ._workspace_name, name=schedule.name, cls=lambda _, obj, __:\n Schedule._from_rest_object(obj), body=schedule_data, polling=\n self._get_polling(schedule.name), **self._kwargs, **kwargs)\n return poller\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n\n def _get_polling(self, name):\n \"\"\"Return the polling with custom poll interval.\"\"\"\n path_format_arguments = {'scheduleName': name, 'resourceGroupName':\n self._resource_group_name, 'workspaceName': self._workspace_name}\n return AzureMLPolling(LROConfigurations.POLL_INTERVAL,\n path_format_arguments=path_format_arguments)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n\n @distributed_trace\n @monitor_with_activity(logger, 'Schedule.List', ActivityType.PUBLICAPI)\n def list(self, *, list_view_type: ScheduleListViewType=\n ScheduleListViewType.ENABLED_ONLY, **kwargs) ->Iterable[Schedule]:\n \"\"\"List schedules in specified workspace.\n\n :param list_view_type: View type for including/excluding (for example)\n archived schedules. Default: ENABLED_ONLY.\n :type list_view_type: Optional[ScheduleListViewType]\n :return: An iterator to list Schedule.\n :rtype: Iterable[Schedule]\n \"\"\"\n\n def safe_from_rest_object(objs):\n result = []\n for obj in objs:\n try:\n result.append(Schedule._from_rest_object(obj))\n except Exception as e:\n print(f'Translate {obj.name} to Schedule failed with: {e}')\n return result\n return self.service_client.list(resource_group_name=self.\n _operation_scope.resource_group_name, workspace_name=self.\n _workspace_name, list_view_type=list_view_type, cls=\n safe_from_rest_object, **self._kwargs, **kwargs)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n\n def __init__(self, operation_scope: OperationScope, operation_config:\n OperationConfig, service_client_04_2023_preview:\n ServiceClient042023Preview, all_operations: OperationsContainer,\n credential: TokenCredential, **kwargs: Any):\n super(ScheduleOperations, self).__init__(operation_scope,\n operation_config)\n ops_logger.update_info(kwargs)\n self.service_client = service_client_04_2023_preview.schedules\n self._all_operations = all_operations\n self._stream_logs_until_completion = stream_logs_until_completion\n self._runs_operations_client = None\n self._dataset_dataplane_operations_client = None\n self._model_dataplane_operations_client = None\n self._service_client_kwargs = kwargs.pop('_service_client_kwargs', {})\n self._api_base_url = None\n self._container = 'azureml'\n self._credential = credential\n self._orchestrators = OperationOrchestrator(self._all_operations,\n self._operation_scope, self._operation_config)\n self._kwargs = kwargs\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<assignment token>\n\n\nclass ScheduleOperations(_ScopeDependentOperations):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<assignment token>\n<class token>\n"
] | false |
99,749 | 0efb30e5b1b39a7691c4c80d4a646aa42b627e3f | # --------------------------------------------------
# Programm by Yoatn
#
# Start date 09.01.2018 00:33
# End date 09.01.2018 00:39
#
# Description:
#
# --------------------------------------------------
#
# import datetime
# print(datetime.datetime.now().strftime("%d.%m.%Y %H:%M"))
print((-12 + 6 / 17) / (3 ** 4 - 40))
| [
"# --------------------------------------------------\n# Programm by Yoatn\n#\n# Start date 09.01.2018 00:33\n# End date 09.01.2018 00:39\n# \n# Description:\n#\n# --------------------------------------------------\n#\n# import datetime\n# print(datetime.datetime.now().strftime(\"%d.%m.%Y %H:%M\"))\n\n\nprint((-12 + 6 / 17) / (3 ** 4 - 40))\n",
"print((-12 + 6 / 17) / (3 ** 4 - 40))\n",
"<code token>\n"
] | false |
99,750 | 29dbfea7da5bcf11dddedcb8796e966110ac35e8 | """
This module enables loading of different perturbation functions in poisoning
"""
import os
from art.attacks.poisoning import PoisoningAttackBackdoor
from art.attacks.poisoning import perturbations
import armory
def poison_loader_GTSRB(**kwargs):
poison_type = kwargs["poison_type"]
if poison_type == "pattern":
def mod(x):
return perturbations.add_pattern_bd(x, pixel_value=1)
elif poison_type == "pixel":
def mod(x):
return perturbations.add_single_bd(x, pixel_value=1)
elif poison_type == "image":
backdoor_path = kwargs.get("backdoor_path")
if backdoor_path is None:
raise ValueError(
"poison_type 'image' requires 'backdoor_path' kwarg path to image"
)
backdoor_packaged_with_armory = kwargs.get(
"backdoor_packaged_with_armory", False
)
if backdoor_packaged_with_armory:
backdoor_path = os.path.join(
# Get base directory where armory is pip installed
os.path.dirname(os.path.dirname(armory.__file__)),
backdoor_path,
)
size = kwargs.get("size")
if size is None:
raise ValueError("poison_type 'image' requires 'size' kwarg tuple")
size = tuple(size)
mode = kwargs.get("mode", "RGB")
blend = kwargs.get("blend", 0.6)
base_img_size_x = kwargs.get("base_img_size_x", 48)
base_img_size_y = kwargs.get("base_img_size_y", 48)
channels_first = kwargs.get("channels_first", False)
x_shift = kwargs.get("x_shift", (base_img_size_x - size[0]) // 2)
y_shift = kwargs.get("y_shift", (base_img_size_y - size[1]) // 2)
def mod(x):
return perturbations.insert_image(
x,
backdoor_path=backdoor_path,
size=size,
mode=mode,
x_shift=x_shift,
y_shift=y_shift,
channels_first=channels_first,
blend=blend,
random=False,
)
else:
raise ValueError(f"Unknown poison_type {poison_type}")
return PoisoningAttackBackdoor(mod)
| [
"\"\"\"\nThis module enables loading of different perturbation functions in poisoning\n\"\"\"\nimport os\n\nfrom art.attacks.poisoning import PoisoningAttackBackdoor\nfrom art.attacks.poisoning import perturbations\nimport armory\n\n\ndef poison_loader_GTSRB(**kwargs):\n poison_type = kwargs[\"poison_type\"]\n if poison_type == \"pattern\":\n\n def mod(x):\n return perturbations.add_pattern_bd(x, pixel_value=1)\n\n elif poison_type == \"pixel\":\n\n def mod(x):\n return perturbations.add_single_bd(x, pixel_value=1)\n\n elif poison_type == \"image\":\n backdoor_path = kwargs.get(\"backdoor_path\")\n if backdoor_path is None:\n raise ValueError(\n \"poison_type 'image' requires 'backdoor_path' kwarg path to image\"\n )\n backdoor_packaged_with_armory = kwargs.get(\n \"backdoor_packaged_with_armory\", False\n )\n if backdoor_packaged_with_armory:\n backdoor_path = os.path.join(\n # Get base directory where armory is pip installed\n os.path.dirname(os.path.dirname(armory.__file__)),\n backdoor_path,\n )\n size = kwargs.get(\"size\")\n if size is None:\n raise ValueError(\"poison_type 'image' requires 'size' kwarg tuple\")\n size = tuple(size)\n mode = kwargs.get(\"mode\", \"RGB\")\n blend = kwargs.get(\"blend\", 0.6)\n base_img_size_x = kwargs.get(\"base_img_size_x\", 48)\n base_img_size_y = kwargs.get(\"base_img_size_y\", 48)\n channels_first = kwargs.get(\"channels_first\", False)\n x_shift = kwargs.get(\"x_shift\", (base_img_size_x - size[0]) // 2)\n y_shift = kwargs.get(\"y_shift\", (base_img_size_y - size[1]) // 2)\n\n def mod(x):\n return perturbations.insert_image(\n x,\n backdoor_path=backdoor_path,\n size=size,\n mode=mode,\n x_shift=x_shift,\n y_shift=y_shift,\n channels_first=channels_first,\n blend=blend,\n random=False,\n )\n\n else:\n raise ValueError(f\"Unknown poison_type {poison_type}\")\n\n return PoisoningAttackBackdoor(mod)\n",
"<docstring token>\nimport os\nfrom art.attacks.poisoning import PoisoningAttackBackdoor\nfrom art.attacks.poisoning import perturbations\nimport armory\n\n\ndef poison_loader_GTSRB(**kwargs):\n poison_type = kwargs['poison_type']\n if poison_type == 'pattern':\n\n def mod(x):\n return perturbations.add_pattern_bd(x, pixel_value=1)\n elif poison_type == 'pixel':\n\n def mod(x):\n return perturbations.add_single_bd(x, pixel_value=1)\n elif poison_type == 'image':\n backdoor_path = kwargs.get('backdoor_path')\n if backdoor_path is None:\n raise ValueError(\n \"poison_type 'image' requires 'backdoor_path' kwarg path to image\"\n )\n backdoor_packaged_with_armory = kwargs.get(\n 'backdoor_packaged_with_armory', False)\n if backdoor_packaged_with_armory:\n backdoor_path = os.path.join(os.path.dirname(os.path.dirname(\n armory.__file__)), backdoor_path)\n size = kwargs.get('size')\n if size is None:\n raise ValueError(\"poison_type 'image' requires 'size' kwarg tuple\")\n size = tuple(size)\n mode = kwargs.get('mode', 'RGB')\n blend = kwargs.get('blend', 0.6)\n base_img_size_x = kwargs.get('base_img_size_x', 48)\n base_img_size_y = kwargs.get('base_img_size_y', 48)\n channels_first = kwargs.get('channels_first', False)\n x_shift = kwargs.get('x_shift', (base_img_size_x - size[0]) // 2)\n y_shift = kwargs.get('y_shift', (base_img_size_y - size[1]) // 2)\n\n def mod(x):\n return perturbations.insert_image(x, backdoor_path=\n backdoor_path, size=size, mode=mode, x_shift=x_shift,\n y_shift=y_shift, channels_first=channels_first, blend=blend,\n random=False)\n else:\n raise ValueError(f'Unknown poison_type {poison_type}')\n return PoisoningAttackBackdoor(mod)\n",
"<docstring token>\n<import token>\n\n\ndef poison_loader_GTSRB(**kwargs):\n poison_type = kwargs['poison_type']\n if poison_type == 'pattern':\n\n def mod(x):\n return perturbations.add_pattern_bd(x, pixel_value=1)\n elif poison_type == 'pixel':\n\n def mod(x):\n return perturbations.add_single_bd(x, pixel_value=1)\n elif poison_type == 'image':\n backdoor_path = kwargs.get('backdoor_path')\n if backdoor_path is None:\n raise ValueError(\n \"poison_type 'image' requires 'backdoor_path' kwarg path to image\"\n )\n backdoor_packaged_with_armory = kwargs.get(\n 'backdoor_packaged_with_armory', False)\n if backdoor_packaged_with_armory:\n backdoor_path = os.path.join(os.path.dirname(os.path.dirname(\n armory.__file__)), backdoor_path)\n size = kwargs.get('size')\n if size is None:\n raise ValueError(\"poison_type 'image' requires 'size' kwarg tuple\")\n size = tuple(size)\n mode = kwargs.get('mode', 'RGB')\n blend = kwargs.get('blend', 0.6)\n base_img_size_x = kwargs.get('base_img_size_x', 48)\n base_img_size_y = kwargs.get('base_img_size_y', 48)\n channels_first = kwargs.get('channels_first', False)\n x_shift = kwargs.get('x_shift', (base_img_size_x - size[0]) // 2)\n y_shift = kwargs.get('y_shift', (base_img_size_y - size[1]) // 2)\n\n def mod(x):\n return perturbations.insert_image(x, backdoor_path=\n backdoor_path, size=size, mode=mode, x_shift=x_shift,\n y_shift=y_shift, channels_first=channels_first, blend=blend,\n random=False)\n else:\n raise ValueError(f'Unknown poison_type {poison_type}')\n return PoisoningAttackBackdoor(mod)\n",
"<docstring token>\n<import token>\n<function token>\n"
] | false |
99,751 | 83a68fc6cd30a9af9fb7e637a26e2aeeeadbe79b | # 구현
# # 방향벡터
# dx = [0, -1, 0, 1]
# dy = [1, 0, -1, 0]
#
# x, y = 2, 2
#
# for i in range(4):
# nx = x + dx[i]
# ny = y + dy[i]
# print(nx, ny)
##### 시각
# 정수 N이 입력되면 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 3이 하나라도 포함되는 모든 경우의 수를 구하는 프로그램을 작성하세요. 예를 들어 1을 ㄹ입력했을 때 다음은 3이 하나라도 포함되어 있으므로 세어야 하는 시각이다.
# 00시 00분 03초
# 00시 13분 30초
# 반면에 다음은 ㄷ이 하나도 포함되어 있지 않으므로 세면 안되는 시각이다.
# 00시 02분 55초
# 01시 27분 45초
# -> 대표적인 완전탐색 유형
# 하루는 86400초 ( 24 * 60 * 60 ) 이므로 가능한 경우의 수를 모두 검사해보는 탐색 방법 -> 브루트 포스
# h = int(input())
#
# count = 0
# for i in range(h + 1):
# for j in range(60):
# for k in range(60):
# if '3' in str(i) + str(j) + str(k):
# count += 1
# print(count)
##### 상하좌우
# 여행가 A는 N * N 크기의 정사각형 공간 위에 서있다. 이 공간은 1 * 1 크기의 정사각형으로 나누어져 있다. 가장 왼쪽 위 좌표는 (1,1) 가장 오른쪽 아래좌표는 (N,N)
# 여행가 A는 상, 하, 좌, 우 방향으로 이동할 수 있으며, 시작 좌표는 항상 (1,1)이다. 우리 앞에는 여행가 A가 이동할 계획이 적인 계획서가 있다.
# 계획서에는 하나의 줄에 띄어쓰기를 기준으로 하여 L, R, U, D 중 하나의 문자가 반복적으로 적혀있다.
# 이때 여행가 A가 N * N 크기의 정사각형 공간을 벗어나느 움직임은 무시된다.
# 방향벡터 활용
n = int(input())
x, y = 1, 1
plans = input().split()
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
move_types = ['L', 'R', 'U', 'D']
for plan in plans:
for i in range(len(move_types)):
if plan == move_types[i]:
nx = x + dx[i]
ny = y + dy[i]
if nx < 1 or ny < 1 or nx > n or ny > n:
continue
x, y = nx, ny
print(x, y)
| [
"# 구현\n\n# # 방향벡터\n# dx = [0, -1, 0, 1]\n# dy = [1, 0, -1, 0]\n#\n# x, y = 2, 2\n#\n# for i in range(4):\n# nx = x + dx[i]\n# ny = y + dy[i]\n# print(nx, ny)\n\n##### 시각\n# 정수 N이 입력되면 00시 00분 00초부터 N시 59분 59초까지의 모든 시각 중에서 3이 하나라도 포함되는 모든 경우의 수를 구하는 프로그램을 작성하세요. 예를 들어 1을 ㄹ입력했을 때 다음은 3이 하나라도 포함되어 있으므로 세어야 하는 시각이다.\n# 00시 00분 03초\n# 00시 13분 30초\n# 반면에 다음은 ㄷ이 하나도 포함되어 있지 않으므로 세면 안되는 시각이다.\n# 00시 02분 55초\n# 01시 27분 45초\n\n# -> 대표적인 완전탐색 유형\n\n# 하루는 86400초 ( 24 * 60 * 60 ) 이므로 가능한 경우의 수를 모두 검사해보는 탐색 방법 -> 브루트 포스\n\n# h = int(input())\n#\n# count = 0\n# for i in range(h + 1):\n# for j in range(60):\n# for k in range(60):\n# if '3' in str(i) + str(j) + str(k):\n# count += 1\n# print(count)\n\n##### 상하좌우\n# 여행가 A는 N * N 크기의 정사각형 공간 위에 서있다. 이 공간은 1 * 1 크기의 정사각형으로 나누어져 있다. 가장 왼쪽 위 좌표는 (1,1) 가장 오른쪽 아래좌표는 (N,N)\n# 여행가 A는 상, 하, 좌, 우 방향으로 이동할 수 있으며, 시작 좌표는 항상 (1,1)이다. 우리 앞에는 여행가 A가 이동할 계획이 적인 계획서가 있다.\n# 계획서에는 하나의 줄에 띄어쓰기를 기준으로 하여 L, R, U, D 중 하나의 문자가 반복적으로 적혀있다.\n# 이때 여행가 A가 N * N 크기의 정사각형 공간을 벗어나느 움직임은 무시된다.\n\n# 방향벡터 활용\n\nn = int(input())\nx, y = 1, 1\nplans = input().split()\n\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\nmove_types = ['L', 'R', 'U', 'D']\n\nfor plan in plans:\n for i in range(len(move_types)):\n if plan == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx < 1 or ny < 1 or nx > n or ny > n:\n continue\n x, y = nx, ny\n\nprint(x, y)\n",
"n = int(input())\nx, y = 1, 1\nplans = input().split()\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\nmove_types = ['L', 'R', 'U', 'D']\nfor plan in plans:\n for i in range(len(move_types)):\n if plan == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 1 or ny < 1 or nx > n or ny > n:\n continue\n x, y = nx, ny\nprint(x, y)\n",
"<assignment token>\nfor plan in plans:\n for i in range(len(move_types)):\n if plan == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 1 or ny < 1 or nx > n or ny > n:\n continue\n x, y = nx, ny\nprint(x, y)\n",
"<assignment token>\n<code token>\n"
] | false |
99,752 | 27d7dbc1b870a06f8bf08accd153108a5e01eefd | from django.shortcuts import render
from .models import Item,OrderItem
# Create your views here.
def home(request):
context ={
'items' : Item.objects.all()
}
return render(request,'shop/home.html',context)
def cart(request):
content ={
'things' : OrderItem.objects.all()
}
return render(request,'shop/cart.html',content)
| [
"from django.shortcuts import render\nfrom .models import Item,OrderItem\n# Create your views here.\ndef home(request):\n context ={\n 'items' : Item.objects.all()\n }\n return render(request,'shop/home.html',context)\n\ndef cart(request):\n content ={\n 'things' : OrderItem.objects.all()\n }\n return render(request,'shop/cart.html',content)\n",
"from django.shortcuts import render\nfrom .models import Item, OrderItem\n\n\ndef home(request):\n context = {'items': Item.objects.all()}\n return render(request, 'shop/home.html', context)\n\n\ndef cart(request):\n content = {'things': OrderItem.objects.all()}\n return render(request, 'shop/cart.html', content)\n",
"<import token>\n\n\ndef home(request):\n context = {'items': Item.objects.all()}\n return render(request, 'shop/home.html', context)\n\n\ndef cart(request):\n content = {'things': OrderItem.objects.all()}\n return render(request, 'shop/cart.html', content)\n",
"<import token>\n<function token>\n\n\ndef cart(request):\n content = {'things': OrderItem.objects.all()}\n return render(request, 'shop/cart.html', content)\n",
"<import token>\n<function token>\n<function token>\n"
] | false |
99,753 | efa4c0a362b81de284d3151898211947190526d3 | import string
n = int(input())
if not set(string.ascii_lowercase) - set(input().lower()):
print('YES')
else:
print('NO')
| [
"import string\n\n\nn = int(input())\nif not set(string.ascii_lowercase) - set(input().lower()):\n print('YES')\nelse:\n print('NO')\n",
"import string\nn = int(input())\nif not set(string.ascii_lowercase) - set(input().lower()):\n print('YES')\nelse:\n print('NO')\n",
"<import token>\nn = int(input())\nif not set(string.ascii_lowercase) - set(input().lower()):\n print('YES')\nelse:\n print('NO')\n",
"<import token>\n<assignment token>\nif not set(string.ascii_lowercase) - set(input().lower()):\n print('YES')\nelse:\n print('NO')\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,754 | 40b5698fed5c55894bed2855928a5fff5ea9a72d | # Specify the default walltime if it is not specified
default_walltime = sql_to_duration('2:00:00')
for i, mold in enumerate(resource_request):
if not mold[1]:
print('[ADMISSION RULE] Set default walltime to {}.'\
.format(default_walltime))
resource_request[i] = (mold[0], default_walltime)
| [
"# Specify the default walltime if it is not specified\ndefault_walltime = sql_to_duration('2:00:00')\n\nfor i, mold in enumerate(resource_request):\n if not mold[1]:\n print('[ADMISSION RULE] Set default walltime to {}.'\\\n .format(default_walltime))\n resource_request[i] = (mold[0], default_walltime)\n",
"default_walltime = sql_to_duration('2:00:00')\nfor i, mold in enumerate(resource_request):\n if not mold[1]:\n print('[ADMISSION RULE] Set default walltime to {}.'.format(\n default_walltime))\n resource_request[i] = mold[0], default_walltime\n",
"<assignment token>\nfor i, mold in enumerate(resource_request):\n if not mold[1]:\n print('[ADMISSION RULE] Set default walltime to {}.'.format(\n default_walltime))\n resource_request[i] = mold[0], default_walltime\n",
"<assignment token>\n<code token>\n"
] | false |
99,755 | 7f5d5468ac6a6b9feb879c325e1fed22051271de | import os
import string
def read_words(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
ord_lista = []
for line in open(filepath, encoding='utf-8'):
ord_lista.extend(line.split())
ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for word in ord_lista]
return ord_lista
def count_only(text, bra_ord):
my_dict = {key: 0 for key in bra_ord}
for word in text:
if word in bra_ord:
my_dict[word] += 1
return my_dict
def count_all_except(text, kassa_ord):
my_set = set(text)
my_dict = {key: 0 for key in my_set if key not in kassa_ord}
for word in text:
if word not in kassa_ord:
my_dict[word] += 1
return my_dict
def sorted_hist(my_dict):
my_list = []
for key in my_dict.keys():
my_list.append((my_dict[key], key))
my_list.sort(reverse=True)
return my_list
def filter_hist(my_dict, n):
my_dict = {key: value for key, value in my_dict.items() if value >= n}
return my_dict
nils_lista = read_words('nilsholg.txt')
landskap = set(read_words('landskap.txt'))
undantag = set(read_words('undantagsord.txt'))
my_dict = count_all_except(nils_lista, undantag)
#my_list = sorted_hist(my_dict)
my_dict = filter_hist(my_dict, 100)
print(my_dict)
| [
"import os\nimport string\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n \n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for word in ord_lista]\n\n return ord_lista\n \n\ndef count_only(text, bra_ord):\n my_dict = {key: 0 for key in bra_ord}\n for word in text:\n if word in bra_ord:\n my_dict[word] += 1\n\n return my_dict\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: 0 for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n \n my_list.sort(reverse=True)\n\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n\n return my_dict\n\n\nnils_lista = read_words('nilsholg.txt')\n\nlandskap = set(read_words('landskap.txt'))\n\nundantag = set(read_words('undantagsord.txt'))\n\nmy_dict = count_all_except(nils_lista, undantag)\n\n#my_list = sorted_hist(my_dict)\n\nmy_dict = filter_hist(my_dict, 100)\n\nprint(my_dict)\n\n",
"import os\nimport string\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\ndef count_only(text, bra_ord):\n my_dict = {key: (0) for key in bra_ord}\n for word in text:\n if word in bra_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n my_list.sort(reverse=True)\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\nnils_lista = read_words('nilsholg.txt')\nlandskap = set(read_words('landskap.txt'))\nundantag = set(read_words('undantagsord.txt'))\nmy_dict = count_all_except(nils_lista, undantag)\nmy_dict = filter_hist(my_dict, 100)\nprint(my_dict)\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\ndef count_only(text, bra_ord):\n my_dict = {key: (0) for key in bra_ord}\n for word in text:\n if word in bra_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n my_list.sort(reverse=True)\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\nnils_lista = read_words('nilsholg.txt')\nlandskap = set(read_words('landskap.txt'))\nundantag = set(read_words('undantagsord.txt'))\nmy_dict = count_all_except(nils_lista, undantag)\nmy_dict = filter_hist(my_dict, 100)\nprint(my_dict)\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\ndef count_only(text, bra_ord):\n my_dict = {key: (0) for key in bra_ord}\n for word in text:\n if word in bra_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n my_list.sort(reverse=True)\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\nprint(my_dict)\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\ndef count_only(text, bra_ord):\n my_dict = {key: (0) for key in bra_ord}\n for word in text:\n if word in bra_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n my_list.sort(reverse=True)\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\n<code token>\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\n<function token>\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\ndef sorted_hist(my_dict):\n my_list = []\n for key in my_dict.keys():\n my_list.append((my_dict[key], key))\n my_list.sort(reverse=True)\n return my_list\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\n<code token>\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\n<function token>\n\n\ndef count_all_except(text, kassa_ord):\n my_set = set(text)\n my_dict = {key: (0) for key in my_set if key not in kassa_ord}\n for word in text:\n if word not in kassa_ord:\n my_dict[word] += 1\n return my_dict\n\n\n<function token>\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\n<code token>\n",
"<import token>\n\n\ndef read_words(filename):\n filepath = os.path.join(os.path.dirname(__file__), filename)\n ord_lista = []\n for line in open(filepath, encoding='utf-8'):\n ord_lista.extend(line.split())\n ord_lista = [word.strip(string.punctuation + string.whitespace).lower() for\n word in ord_lista]\n return ord_lista\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef filter_hist(my_dict, n):\n my_dict = {key: value for key, value in my_dict.items() if value >= n}\n return my_dict\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n"
] | false |
99,756 | 5ec8d4ac37250074cf216b02a1f38415f8766299 | x::int = 3
y::str = x
| [
"x::int = 3\ny::str = x\n"
] | true |
99,757 | 34573f6f1d3cc538ec19418ae6c17bfc107294a6 | from petsc4py import PETSc
import sys,time
class Viz:
'''A crude Python vizualization engine. If your mayavi works,
uncomment the corresponding lines in the viewRho method to
use that for vizualization instead.'''
@staticmethod
def init(v):
pass
@staticmethod
def viewRho(v):
import numpy
# Then extract objects attached to v:
# a DA "mesh" and a Vec "rho"
da = v.query("mesh")
rho = v.query("rho").getArray()
# Get DA parameters and make sure rho conforms to them
N = da.getSizes()
dim = da.getDim()
d = da.getDof()-1
assert dim == 3
assert rho.size == N[0]*N[1]*N[2]*(d)
# Reshape the Vec's data array to conform to the DMDA shape
shape = list(N)
shape.append(d)
rho = rho.reshape(shape)
# Plot all of the components of rho over the da
# Use a contour plot in 3D
for s in range(d):
#from enthought.mayavi import mlab as mlab
#mlab.contour3d(rho[:,:,:,s])
sys.stdout.write(str(rho[:,:,:,s]))
sys.stdout.flush()
time.sleep(1)
#mlab.clf()
time.sleep(3)
| [
"from petsc4py import PETSc\nimport sys,time\n\n\nclass Viz:\n '''A crude Python vizualization engine. If your mayavi works,\n uncomment the corresponding lines in the viewRho method to\n use that for vizualization instead.'''\n @staticmethod\n def init(v):\n pass\n\n @staticmethod\n def viewRho(v):\n import numpy\n # Then extract objects attached to v:\n # a DA \"mesh\" and a Vec \"rho\"\n da = v.query(\"mesh\")\n rho = v.query(\"rho\").getArray()\n # Get DA parameters and make sure rho conforms to them\n N = da.getSizes()\n dim = da.getDim()\n d = da.getDof()-1\n assert dim == 3\n assert rho.size == N[0]*N[1]*N[2]*(d)\n # Reshape the Vec's data array to conform to the DMDA shape\n shape = list(N)\n shape.append(d)\n rho = rho.reshape(shape)\n # Plot all of the components of rho over the da\n # Use a contour plot in 3D\n for s in range(d):\n #from enthought.mayavi import mlab as mlab\n #mlab.contour3d(rho[:,:,:,s])\n sys.stdout.write(str(rho[:,:,:,s]))\n sys.stdout.flush()\n time.sleep(1)\n #mlab.clf()\n time.sleep(3)\n\n\n\n",
"from petsc4py import PETSc\nimport sys, time\n\n\nclass Viz:\n \"\"\"A crude Python vizualization engine. If your mayavi works,\n uncomment the corresponding lines in the viewRho method to\n use that for vizualization instead.\"\"\"\n\n @staticmethod\n def init(v):\n pass\n\n @staticmethod\n def viewRho(v):\n import numpy\n da = v.query('mesh')\n rho = v.query('rho').getArray()\n N = da.getSizes()\n dim = da.getDim()\n d = da.getDof() - 1\n assert dim == 3\n assert rho.size == N[0] * N[1] * N[2] * d\n shape = list(N)\n shape.append(d)\n rho = rho.reshape(shape)\n for s in range(d):\n sys.stdout.write(str(rho[:, :, :, s]))\n sys.stdout.flush()\n time.sleep(1)\n time.sleep(3)\n",
"<import token>\n\n\nclass Viz:\n \"\"\"A crude Python vizualization engine. If your mayavi works,\n uncomment the corresponding lines in the viewRho method to\n use that for vizualization instead.\"\"\"\n\n @staticmethod\n def init(v):\n pass\n\n @staticmethod\n def viewRho(v):\n import numpy\n da = v.query('mesh')\n rho = v.query('rho').getArray()\n N = da.getSizes()\n dim = da.getDim()\n d = da.getDof() - 1\n assert dim == 3\n assert rho.size == N[0] * N[1] * N[2] * d\n shape = list(N)\n shape.append(d)\n rho = rho.reshape(shape)\n for s in range(d):\n sys.stdout.write(str(rho[:, :, :, s]))\n sys.stdout.flush()\n time.sleep(1)\n time.sleep(3)\n",
"<import token>\n\n\nclass Viz:\n <docstring token>\n\n @staticmethod\n def init(v):\n pass\n\n @staticmethod\n def viewRho(v):\n import numpy\n da = v.query('mesh')\n rho = v.query('rho').getArray()\n N = da.getSizes()\n dim = da.getDim()\n d = da.getDof() - 1\n assert dim == 3\n assert rho.size == N[0] * N[1] * N[2] * d\n shape = list(N)\n shape.append(d)\n rho = rho.reshape(shape)\n for s in range(d):\n sys.stdout.write(str(rho[:, :, :, s]))\n sys.stdout.flush()\n time.sleep(1)\n time.sleep(3)\n",
"<import token>\n\n\nclass Viz:\n <docstring token>\n\n @staticmethod\n def init(v):\n pass\n <function token>\n",
"<import token>\n\n\nclass Viz:\n <docstring token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,758 | 4d686b2adc0f02b37ed1209b65ea44d1117eda8f | #!/usr/bin/python3
"""
Database storage engine using SQLAlchemy with mysql+mysqldb database connection
"""
import os
from models.base_model import Base
from models.website import Website
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
classes = {"Website": Website}
class DBStorage:
"""Database Storage"""
def __init__(self):
"""Initializes the database object"""
user = os.getenv('URL_MYSQL_USER')
passwd = os.getenv('URL_MYSQL_PWD')
host = os.getenv('URL_MYSQL_HOST')
database = os.getenv('URL_MYSQL_DB')
self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'
.format(user, passwd, host, database))
def all(self, cls=None):
"""returns a dictionary of all the objects present"""
if not self.__session:
self.reload()
objects = {}
if type(cls) == str:
cls = classes.get(cls, None)
if cls:
for obj in self.__session.query(cls):
objects[obj.__class__.__name__ + '.' + obj.id] = obj
else:
for cls in classes.values():
for obj in self.__session.query(cls):
objects[obj.__class__.__name__ + '.' + obj.id] = obj
return objects
def reload(self):
"""reloads objects from the database"""
session_factory = sessionmaker(bind=self.__engine,
expire_on_commit=False)
Base.metadata.create_all(self.__engine)
self.__session = scoped_session(session_factory)
def new(self, obj):
"""creates a new object"""
self.__session.add(obj)
def save(self):
"""saves the current session"""
self.__session.commit()
def delete(self, obj=None):
"""deletes an object"""
if not self.__session:
self.reload()
if obj:
self.__session.delete(obj)
def close(self):
"""Dispose of current session if active"""
self.__session.remove()
def get(self, cls, id):
"""Retrieve an object"""
if cls is "Website" and id is not None and type(id) is str:
return self.__session.query(Website).filter(Website.
short_url == id).first()
elif cls is not None and type(cls) is str and id is not None and\
type(id) is str and cls in classes:
cls = classes[cls]
result = self.__session.query(cls).filter(cls.id == id).first()
return result
else:
return None
def count(self, cls=None):
"""Count number of objects in storage"""
total = 0
if type(cls) == str and cls in classes:
cls = classes[cls]
total = self.__session.query(cls).count()
elif cls is None:
for cls in classes.values():
total += self.__session.query(cls).count()
return total
def get_short(self, cls, long):
"""retrieve a short_url from a website name"""
if cls == "Website":
result = self.__session.query(Website).filter(Website.name == long).first()
return result
| [
"#!/usr/bin/python3\n\"\"\"\nDatabase storage engine using SQLAlchemy with mysql+mysqldb database connection\n\"\"\"\n\nimport os\nfrom models.base_model import Base\nfrom models.website import Website\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\nclasses = {\"Website\": Website}\n\n\nclass DBStorage:\n \"\"\"Database Storage\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is \"Website\" and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.\n short_url == id).first()\n elif cls is not None and type(cls) is str and id is not None and\\\n type(id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n\n def get_short(self, cls, long):\n \"\"\"retrieve a short_url from a website name\"\"\"\n if cls == \"Website\":\n result = self.__session.query(Website).filter(Website.name == long).first()\n return result\n",
"<docstring token>\nimport os\nfrom models.base_model import Base\nfrom models.website import Website\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nclasses = {'Website': Website}\n\n\nclass DBStorage:\n \"\"\"Database Storage\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n\n def get_short(self, cls, long):\n \"\"\"retrieve a short_url from a website name\"\"\"\n if cls == 'Website':\n result = self.__session.query(Website).filter(Website.name == long\n ).first()\n return result\n",
"<docstring token>\n<import token>\nclasses = {'Website': Website}\n\n\nclass DBStorage:\n \"\"\"Database Storage\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n\n def get_short(self, cls, long):\n \"\"\"retrieve a short_url from a website name\"\"\"\n if cls == 'Website':\n result = self.__session.query(Website).filter(Website.name == long\n ).first()\n return result\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n \"\"\"Database Storage\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n\n def get_short(self, cls, long):\n \"\"\"retrieve a short_url from a website name\"\"\"\n if cls == 'Website':\n result = self.__session.query(Website).filter(Website.name == long\n ).first()\n return result\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n\n def get_short(self, cls, long):\n \"\"\"retrieve a short_url from a website name\"\"\"\n if cls == 'Website':\n result = self.__session.query(Website).filter(Website.name == long\n ).first()\n return result\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"saves the current session\"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n\n def all(self, cls=None):\n \"\"\"returns a dictionary of all the objects present\"\"\"\n if not self.__session:\n self.reload()\n objects = {}\n if type(cls) == str:\n cls = classes.get(cls, None)\n if cls:\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n else:\n for cls in classes.values():\n for obj in self.__session.query(cls):\n objects[obj.__class__.__name__ + '.' + obj.id] = obj\n return objects\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n <function token>\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n\n def get(self, cls, id):\n \"\"\"Retrieve an object\"\"\"\n if cls is 'Website' and id is not None and type(id) is str:\n return self.__session.query(Website).filter(Website.short_url == id\n ).first()\n elif cls is not None and type(cls) is str and id is not None and type(\n id) is str and cls in classes:\n cls = classes[cls]\n result = self.__session.query(cls).filter(cls.id == id).first()\n return result\n else:\n return None\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n <function token>\n\n def reload(self):\n \"\"\"reloads objects from the database\"\"\"\n session_factory = sessionmaker(bind=self.__engine, expire_on_commit\n =False)\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(session_factory)\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n <function token>\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n <function token>\n <function token>\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n <function token>\n\n def count(self, cls=None):\n \"\"\"Count number of objects in storage\"\"\"\n total = 0\n if type(cls) == str and cls in classes:\n cls = classes[cls]\n total = self.__session.query(cls).count()\n elif cls is None:\n for cls in classes.values():\n total += self.__session.query(cls).count()\n return total\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n <function token>\n <function token>\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n\n def delete(self, obj=None):\n \"\"\"deletes an object\"\"\"\n if not self.__session:\n self.reload()\n if obj:\n self.__session.delete(obj)\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n\n def __init__(self):\n \"\"\"Initializes the database object\"\"\"\n user = os.getenv('URL_MYSQL_USER')\n passwd = os.getenv('URL_MYSQL_PWD')\n host = os.getenv('URL_MYSQL_HOST')\n database = os.getenv('URL_MYSQL_DB')\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n user, passwd, host, database))\n <function token>\n <function token>\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n <function token>\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n <function token>\n\n def close(self):\n \"\"\"Dispose of current session if active\"\"\"\n self.__session.remove()\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def new(self, obj):\n \"\"\"creates a new object\"\"\"\n self.__session.add(obj)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass DBStorage:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<class token>\n"
] | false |
99,759 | b3d7f541f264922813655cfdf92440895e00d44f | # COMMAND LINE INTERFACE CLASS
# do enough to create a data.json file from scatch with the current test data
import json
import glob
from file import File
from chip import Chip
from tile import Tile
class CLI:
'''
METHODS:
- ability to display a tile's initialized chips
- ability to display a tile's uart path
- ability to display a chip's config data
- ability to display a chip's config file path
- ability to add a new tile by inputting serial number
- ability to add a new uart path to the tile
- ability to save all data when program is going inactive (.larpix ext)
- ability to copy all data onto a <file1>.larpix backup
- ability to open all data when program is going active (.larpix ext)
- ability to change a tile's info/ chip's info (more advanced method)
ATTRIBUTES:
- a menu showing a user which actions to perform
'''
def __init__(self):
print("Initializing interface...")
self.init_file = File('', [False, False, True])
self.init_data = self.init_file.open_file()
print("Interface initialized!")
self.tile_arr = []
def display_menu(self):
print('\n')
print("Welcome to the UTA LArPix QC Testing Database, choose an option...")
print("(1) Add a new tile to the database") # input serial number -> initialize chips, uarts, and configs
print("(2) Display all tiles saved to the database")
print("(q) Save and exit program")
print('\n')
def add_tile(self):
tile_input = str(input("Enter a tile serial number (000, 001, 002, etc...) or quit (q): ")).lower()
if tile_input == 'q': pass
else:
try:
tile = Tile(tile_input)
print("Data found for: {}".format(tile))
print("Adding tile to database...")
self.tile_arr.append(tile)
except:
pass
def display_all_tiles(self):
for tile in self.tile_arr: print("{}".format(tile))
def save(self):
data = {
"data": [
{
"serial_number": tile.serial_num,
"uart_path": tile.uart_data,
"chips": [
{
"chip_id": chip.chip_id,
"chip_config": chip.config_data
} for chip in tile.chips
]
} for tile in self.tile_arr
]
}
json_object = json.dumps(data, indent = 4)
self.init_file.save_file(json_object)
def run(self):
while True:
self.display_menu()
menu_input = str(input("Enter an option: ")).lower()
if menu_input == 'q':
self.save()
break
elif menu_input == '1':
self.add_tile()
continue
elif menu_input == '2':
self.display_all_tiles()
continue
else:
print("Not an acceptable input! Try again!")
continue
if __name__ == "__main__":
interface = CLI()
interface.run()
| [
"# COMMAND LINE INTERFACE CLASS\n\n# do enough to create a data.json file from scatch with the current test data\n\nimport json\nimport glob\nfrom file import File\nfrom chip import Chip\nfrom tile import Tile\n\nclass CLI:\n\t'''\n\tMETHODS:\n\t\t- ability to display a tile's initialized chips\n\t\t- ability to display a tile's uart path\n\t\t- ability to display a chip's config data\n\t\t- ability to display a chip's config file path\n\n\t\t- ability to add a new tile by inputting serial number\n\t\t- ability to add a new uart path to the tile\n\t\t- ability to save all data when program is going inactive (.larpix ext)\n\t\t- ability to copy all data onto a <file1>.larpix backup\n\t\t- ability to open all data when program is going active (.larpix ext)\n\t\t- ability to change a tile's info/ chip's info (more advanced method)\n\n\tATTRIBUTES:\n\t\t- a menu showing a user which actions to perform\n\t'''\n\tdef __init__(self):\n\t\tprint(\"Initializing interface...\")\n\t\tself.init_file = File('', [False, False, True])\n\t\tself.init_data = self.init_file.open_file()\n\t\tprint(\"Interface initialized!\")\n\n\t\tself.tile_arr = []\n\n\n\tdef display_menu(self):\n\t\tprint('\\n')\n\t\tprint(\"Welcome to the UTA LArPix QC Testing Database, choose an option...\")\n\t\tprint(\"(1) Add a new tile to the database\") # input serial number -> initialize chips, uarts, and configs\n\t\tprint(\"(2) Display all tiles saved to the database\")\n\t\tprint(\"(q) Save and exit program\")\n\t\tprint('\\n')\n\n\n\tdef add_tile(self):\n\t\ttile_input = str(input(\"Enter a tile serial number (000, 001, 002, etc...) or quit (q): \")).lower()\n\t\tif tile_input == 'q': pass\n\t\telse:\n\t\t\ttry:\n\t\t\t\ttile = Tile(tile_input)\n\t\t\t\tprint(\"Data found for: {}\".format(tile))\n\t\t\t\tprint(\"Adding tile to database...\")\n\t\t\t\tself.tile_arr.append(tile)\n\t\t\texcept:\n\t\t\t\tpass\n\n\n\tdef display_all_tiles(self):\n\t\tfor tile in self.tile_arr: print(\"{}\".format(tile))\n\n\n\tdef save(self):\n\t\tdata = {\n\t\t\t\t\"data\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"serial_number\": tile.serial_num,\n\t\t\t\t\t\t\"uart_path\": tile.uart_data, \n\t\t\t\t\t\t\"chips\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"chip_id\": chip.chip_id,\n\t\t\t\t\t\t\t\t\"chip_config\": chip.config_data\n\t\t\t\t\t\t\t} for chip in tile.chips\n\t\t\t\t\t\t]\n\t\t\t\t\t} for tile in self.tile_arr\n\t\t\t\t]\n\t\t\t}\n\t\tjson_object = json.dumps(data, indent = 4)\n\t\tself.init_file.save_file(json_object)\n\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tself.display_menu()\n\t\t\tmenu_input = str(input(\"Enter an option: \")).lower()\n\n\t\t\tif menu_input == 'q':\n\t\t\t\tself.save()\n\t\t\t\tbreak\n\t\t\telif menu_input == '1':\n\t\t\t\tself.add_tile()\n\t\t\t\tcontinue\n\t\t\telif menu_input == '2':\n\t\t\t\tself.display_all_tiles()\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint(\"Not an acceptable input! Try again!\")\n\t\t\t\tcontinue\n\n\nif __name__ == \"__main__\":\n\tinterface = CLI()\n\tinterface.run()\n",
"import json\nimport glob\nfrom file import File\nfrom chip import Chip\nfrom tile import Tile\n\n\nclass CLI:\n \"\"\"\n\tMETHODS:\n\t\t- ability to display a tile's initialized chips\n\t\t- ability to display a tile's uart path\n\t\t- ability to display a chip's config data\n\t\t- ability to display a chip's config file path\n\n\t\t- ability to add a new tile by inputting serial number\n\t\t- ability to add a new uart path to the tile\n\t\t- ability to save all data when program is going inactive (.larpix ext)\n\t\t- ability to copy all data onto a <file1>.larpix backup\n\t\t- ability to open all data when program is going active (.larpix ext)\n\t\t- ability to change a tile's info/ chip's info (more advanced method)\n\n\tATTRIBUTES:\n\t\t- a menu showing a user which actions to perform\n\t\"\"\"\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n\n def add_tile(self):\n tile_input = str(input(\n 'Enter a tile serial number (000, 001, 002, etc...) or quit (q): ')\n ).lower()\n if tile_input == 'q':\n pass\n else:\n try:\n tile = Tile(tile_input)\n print('Data found for: {}'.format(tile))\n print('Adding tile to database...')\n self.tile_arr.append(tile)\n except:\n pass\n\n def display_all_tiles(self):\n for tile in self.tile_arr:\n print('{}'.format(tile))\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\nif __name__ == '__main__':\n interface = CLI()\n interface.run()\n",
"<import token>\n\n\nclass CLI:\n \"\"\"\n\tMETHODS:\n\t\t- ability to display a tile's initialized chips\n\t\t- ability to display a tile's uart path\n\t\t- ability to display a chip's config data\n\t\t- ability to display a chip's config file path\n\n\t\t- ability to add a new tile by inputting serial number\n\t\t- ability to add a new uart path to the tile\n\t\t- ability to save all data when program is going inactive (.larpix ext)\n\t\t- ability to copy all data onto a <file1>.larpix backup\n\t\t- ability to open all data when program is going active (.larpix ext)\n\t\t- ability to change a tile's info/ chip's info (more advanced method)\n\n\tATTRIBUTES:\n\t\t- a menu showing a user which actions to perform\n\t\"\"\"\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n\n def add_tile(self):\n tile_input = str(input(\n 'Enter a tile serial number (000, 001, 002, etc...) or quit (q): ')\n ).lower()\n if tile_input == 'q':\n pass\n else:\n try:\n tile = Tile(tile_input)\n print('Data found for: {}'.format(tile))\n print('Adding tile to database...')\n self.tile_arr.append(tile)\n except:\n pass\n\n def display_all_tiles(self):\n for tile in self.tile_arr:\n print('{}'.format(tile))\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\nif __name__ == '__main__':\n interface = CLI()\n interface.run()\n",
"<import token>\n\n\nclass CLI:\n \"\"\"\n\tMETHODS:\n\t\t- ability to display a tile's initialized chips\n\t\t- ability to display a tile's uart path\n\t\t- ability to display a chip's config data\n\t\t- ability to display a chip's config file path\n\n\t\t- ability to add a new tile by inputting serial number\n\t\t- ability to add a new uart path to the tile\n\t\t- ability to save all data when program is going inactive (.larpix ext)\n\t\t- ability to copy all data onto a <file1>.larpix backup\n\t\t- ability to open all data when program is going active (.larpix ext)\n\t\t- ability to change a tile's info/ chip's info (more advanced method)\n\n\tATTRIBUTES:\n\t\t- a menu showing a user which actions to perform\n\t\"\"\"\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n\n def add_tile(self):\n tile_input = str(input(\n 'Enter a tile serial number (000, 001, 002, etc...) or quit (q): ')\n ).lower()\n if tile_input == 'q':\n pass\n else:\n try:\n tile = Tile(tile_input)\n print('Data found for: {}'.format(tile))\n print('Adding tile to database...')\n self.tile_arr.append(tile)\n except:\n pass\n\n def display_all_tiles(self):\n for tile in self.tile_arr:\n print('{}'.format(tile))\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n\n def add_tile(self):\n tile_input = str(input(\n 'Enter a tile serial number (000, 001, 002, etc...) or quit (q): ')\n ).lower()\n if tile_input == 'q':\n pass\n else:\n try:\n tile = Tile(tile_input)\n print('Data found for: {}'.format(tile))\n print('Adding tile to database...')\n self.tile_arr.append(tile)\n except:\n pass\n\n def display_all_tiles(self):\n for tile in self.tile_arr:\n print('{}'.format(tile))\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n <function token>\n\n def display_all_tiles(self):\n for tile in self.tile_arr:\n print('{}'.format(tile))\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n\n def __init__(self):\n print('Initializing interface...')\n self.init_file = File('', [False, False, True])\n self.init_data = self.init_file.open_file()\n print('Interface initialized!')\n self.tile_arr = []\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n <function token>\n <function token>\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n <function token>\n\n def display_menu(self):\n print('\\n')\n print(\n 'Welcome to the UTA LArPix QC Testing Database, choose an option...'\n )\n print('(1) Add a new tile to the database')\n print('(2) Display all tiles saved to the database')\n print('(q) Save and exit program')\n print('\\n')\n <function token>\n <function token>\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n\n def run(self):\n while True:\n self.display_menu()\n menu_input = str(input('Enter an option: ')).lower()\n if menu_input == 'q':\n self.save()\n break\n elif menu_input == '1':\n self.add_tile()\n continue\n elif menu_input == '2':\n self.display_all_tiles()\n continue\n else:\n print('Not an acceptable input! Try again!')\n continue\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def save(self):\n data = {'data': [{'serial_number': tile.serial_num, 'uart_path':\n tile.uart_data, 'chips': [{'chip_id': chip.chip_id,\n 'chip_config': chip.config_data} for chip in tile.chips]} for\n tile in self.tile_arr]}\n json_object = json.dumps(data, indent=4)\n self.init_file.save_file(json_object)\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CLI:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<class token>\n<code token>\n"
] | false |
99,760 | 33437c76a9d8da1a2896287e7d6276eb90050ff4 | #! /usr/bin/env python
#encoding=utf-8
import threading
import time
from multiprocessing import Queue
import os
import sys
import subprocess
queue = Queue()
def initQueue():
global queue
file_object = open("curllist.txt", "r")
for line in file_object:
queue.put(line)
class Consumer(threading.Thread):
def run(self):
global queue
while queue.qsize() > 0:
cmd = queue.get()
if cmd.strip() == "testcmd":
time.sleep(10)
msg = self.name + '执行了 '+ cmd
print(msg)
#os.system(cmd)
#output = os.popen(cmd)
#print("output is : ",self.name,output.readlines())
print("output is : ",subprocess.check_output(cmd))
time.sleep(0.01)
def main():
initQueue()
size = queue.qsize()
for i in range(size):
c = Consumer()
c.start()
if __name__ == '__main__':
main()
| [
"#! /usr/bin/env python \n\n#encoding=utf-8 \n\nimport threading\nimport time\nfrom multiprocessing import Queue\nimport os\nimport sys\nimport subprocess\n\nqueue = Queue()\n\ndef initQueue():\n global queue\n file_object = open(\"curllist.txt\", \"r\")\n for line in file_object:\n queue.put(line)\n\nclass Consumer(threading.Thread):\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == \"testcmd\":\n time.sleep(10)\n msg = self.name + '执行了 '+ cmd\n print(msg)\n #os.system(cmd)\n #output = os.popen(cmd)\n #print(\"output is : \",self.name,output.readlines())\n print(\"output is : \",subprocess.check_output(cmd))\n time.sleep(0.01)\n\ndef main():\n initQueue()\n size = queue.qsize()\n for i in range(size):\n c = Consumer()\n c.start()\n\nif __name__ == '__main__':\n main()\n",
"import threading\nimport time\nfrom multiprocessing import Queue\nimport os\nimport sys\nimport subprocess\nqueue = Queue()\n\n\ndef initQueue():\n global queue\n file_object = open('curllist.txt', 'r')\n for line in file_object:\n queue.put(line)\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\ndef main():\n initQueue()\n size = queue.qsize()\n for i in range(size):\n c = Consumer()\n c.start()\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\nqueue = Queue()\n\n\ndef initQueue():\n global queue\n file_object = open('curllist.txt', 'r')\n for line in file_object:\n queue.put(line)\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\ndef main():\n initQueue()\n size = queue.qsize()\n for i in range(size):\n c = Consumer()\n c.start()\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<assignment token>\n\n\ndef initQueue():\n global queue\n file_object = open('curllist.txt', 'r')\n for line in file_object:\n queue.put(line)\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\ndef main():\n initQueue()\n size = queue.qsize()\n for i in range(size):\n c = Consumer()\n c.start()\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<assignment token>\n\n\ndef initQueue():\n global queue\n file_object = open('curllist.txt', 'r')\n for line in file_object:\n queue.put(line)\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\ndef main():\n initQueue()\n size = queue.qsize()\n for i in range(size):\n c = Consumer()\n c.start()\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\ndef initQueue():\n global queue\n file_object = open('curllist.txt', 'r')\n for line in file_object:\n queue.put(line)\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass Consumer(threading.Thread):\n\n def run(self):\n global queue\n while queue.qsize() > 0:\n cmd = queue.get()\n if cmd.strip() == 'testcmd':\n time.sleep(10)\n msg = self.name + '执行了 ' + cmd\n print(msg)\n print('output is : ', subprocess.check_output(cmd))\n time.sleep(0.01)\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass Consumer(threading.Thread):\n <function token>\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n<class token>\n<function token>\n<code token>\n"
] | false |
99,761 | 620f95acb878c4cab558e3916a865e34a3c71f49 | class Entity:
def __init__(self, entityId):
self.__entityId = entityId
@property
def entityId(self):
return self.__entityId
@entityId.setter
def entityId(self, idEnt):
self.__entityId = idEnt
| [
"class Entity:\r\n\r\n def __init__(self, entityId):\r\n self.__entityId = entityId\r\n\r\n @property\r\n def entityId(self):\r\n return self.__entityId\r\n\r\n @entityId.setter\r\n def entityId(self, idEnt):\r\n self.__entityId = idEnt\r\n",
"class Entity:\n\n def __init__(self, entityId):\n self.__entityId = entityId\n\n @property\n def entityId(self):\n return self.__entityId\n\n @entityId.setter\n def entityId(self, idEnt):\n self.__entityId = idEnt\n",
"class Entity:\n\n def __init__(self, entityId):\n self.__entityId = entityId\n <function token>\n\n @entityId.setter\n def entityId(self, idEnt):\n self.__entityId = idEnt\n",
"class Entity:\n <function token>\n <function token>\n\n @entityId.setter\n def entityId(self, idEnt):\n self.__entityId = idEnt\n",
"class Entity:\n <function token>\n <function token>\n <function token>\n",
"<class token>\n"
] | false |
99,762 | 15245fa756cc001da5cafce7bfd0d75dda0c28f8 | def max_array(a,k):
# print(k)
list = a.split()
sum=0
p=[]
n=len(list)
pp=k
for i in range(0,len(list)-k+1):
l=0
k=pp
for j in range(i,k):
if(j<=n):
l=max(l,int(list[j]))
pp=pp+1
p.append(l)
l=0
print(p)
a=input()
k=int(input())
max_array(a,k)
| [
"def max_array(a,k):\n # print(k)\n list = a.split()\n sum=0\n p=[]\n n=len(list)\n pp=k\n for i in range(0,len(list)-k+1):\n l=0\n k=pp\n \n for j in range(i,k):\n \n if(j<=n):\n l=max(l,int(list[j]))\n \n pp=pp+1\n p.append(l)\n l=0\n \n print(p)\na=input()\nk=int(input())\nmax_array(a,k)\n",
"def max_array(a, k):\n list = a.split()\n sum = 0\n p = []\n n = len(list)\n pp = k\n for i in range(0, len(list) - k + 1):\n l = 0\n k = pp\n for j in range(i, k):\n if j <= n:\n l = max(l, int(list[j]))\n pp = pp + 1\n p.append(l)\n l = 0\n print(p)\n\n\na = input()\nk = int(input())\nmax_array(a, k)\n",
"def max_array(a, k):\n list = a.split()\n sum = 0\n p = []\n n = len(list)\n pp = k\n for i in range(0, len(list) - k + 1):\n l = 0\n k = pp\n for j in range(i, k):\n if j <= n:\n l = max(l, int(list[j]))\n pp = pp + 1\n p.append(l)\n l = 0\n print(p)\n\n\n<assignment token>\nmax_array(a, k)\n",
"def max_array(a, k):\n list = a.split()\n sum = 0\n p = []\n n = len(list)\n pp = k\n for i in range(0, len(list) - k + 1):\n l = 0\n k = pp\n for j in range(i, k):\n if j <= n:\n l = max(l, int(list[j]))\n pp = pp + 1\n p.append(l)\n l = 0\n print(p)\n\n\n<assignment token>\n<code token>\n",
"<function token>\n<assignment token>\n<code token>\n"
] | false |
99,763 | 4d31892df3391fb326b516adb2a0fe83f0a2e07d | def has_digit(digit, num):
if digit in str(num):
return True
return False
def find_numbers(digit, number):
all_nums = []
for num in range(0, number+1):
if has_digit(digit, num):
all_nums.append(num)
return all_nums
if __name__ == '__main__':
number = int(input("Enter the number \n"))
digit = input("Enter the digit \n")
all_nums = find_numbers(digit, number)
print(f"The number with the digit {digit} are - {all_nums}" if all_nums else f"There are no numbers that contain digit {digit}")
| [
"def has_digit(digit, num):\r\n\tif digit in str(num):\r\n\t\treturn True\r\n\treturn False\r\n\r\ndef find_numbers(digit, number):\r\n\tall_nums = []\r\n\tfor num in range(0, number+1):\r\n\t\tif has_digit(digit, num):\r\n\t\t\tall_nums.append(num)\r\n\treturn all_nums\r\n\r\nif __name__ == '__main__':\r\n\tnumber = int(input(\"Enter the number \\n\"))\r\n\tdigit = input(\"Enter the digit \\n\")\r\n\r\n\tall_nums = find_numbers(digit, number)\r\n\tprint(f\"The number with the digit {digit} are - {all_nums}\" if all_nums else f\"There are no numbers that contain digit {digit}\")\r\n\r\n",
"def has_digit(digit, num):\n if digit in str(num):\n return True\n return False\n\n\ndef find_numbers(digit, number):\n all_nums = []\n for num in range(0, number + 1):\n if has_digit(digit, num):\n all_nums.append(num)\n return all_nums\n\n\nif __name__ == '__main__':\n number = int(input('Enter the number \\n'))\n digit = input('Enter the digit \\n')\n all_nums = find_numbers(digit, number)\n print(f'The number with the digit {digit} are - {all_nums}' if all_nums\n else f'There are no numbers that contain digit {digit}')\n",
"def has_digit(digit, num):\n if digit in str(num):\n return True\n return False\n\n\ndef find_numbers(digit, number):\n all_nums = []\n for num in range(0, number + 1):\n if has_digit(digit, num):\n all_nums.append(num)\n return all_nums\n\n\n<code token>\n",
"<function token>\n\n\ndef find_numbers(digit, number):\n all_nums = []\n for num in range(0, number + 1):\n if has_digit(digit, num):\n all_nums.append(num)\n return all_nums\n\n\n<code token>\n",
"<function token>\n<function token>\n<code token>\n"
] | false |
99,764 | cda587c6155b4b1608c24a3c8620560a41805e62 | import numpy as np
from scipy import sparse as ss
import torch
from torch.utils.data import TensorDataset
from knodle.trainer.snorkel.utils import (
z_t_matrix_to_snorkel_matrix,
prepare_empty_rule_matches,
add_labels_for_empty_examples
)
def test_z_t_matrix_to_snorkel_matrix():
# test dense case
z = np.array([
[0, 1, 0, 0],
[0, 0, 1, 1]
])
t = np.array([
[1, 0],
[0, 1],
[1, 0],
[0, 1]
])
snorkel_gold = np.array([
[-1, 1, -1, -1],
[-1, -1, 0, 1]
])
snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)
np.testing.assert_equal(snorkel_gold, snorkel_test)
# test sparse case
z = ss.csr_matrix([
[0, 1, 0, 0],
[0, 0, 1, 1]
])
t = ss.csr_matrix([
[1, 0],
[0, 1],
[1, 0],
[0, 1]
])
snorkel_gold = np.array([
[-1, 1, -1, -1],
[-1, -1, 0, 1]
])
snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)
np.testing.assert_equal(snorkel_gold, snorkel_test)
def test_label_model_data():
num_samples = 5
num_rules = 6
rule_matches_z = np.ones((num_samples, num_rules))
rule_matches_z[[1, 4]] = 0
non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(rule_matches_z)
expected_mask = np.array([True, False, True, True, False])
expected_rule_matches = np.ones((3, num_rules))
np.testing.assert_equal(non_zero_mask, expected_mask)
np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)
def test_other_class_labels():
label_probs_gen = np.array([
[0.3, 0.6, 0.0, 0.1],
[0.2, 0.2, 0.2, 0.4],
[1.0, 0.0, 0.0, 0.0]
])
output_classes = 5
other_class_id = 4
# test without empty rows
non_zero_mask = np.array([True, True, True])
expected_probs = np.array([
[0.3, 0.6, 0.0, 0.1, 0.0],
[0.2, 0.2, 0.2, 0.4, 0.0],
[1.0, 0.0, 0.0, 0.0, 0.0]
])
label_probs = add_labels_for_empty_examples(label_probs_gen, non_zero_mask, output_classes, other_class_id)
np.testing.assert_equal(label_probs, expected_probs)
# test with empty rows
non_zero_mask = np.array([True, False, False, True, True])
expected_probs = np.array([
[0.3, 0.6, 0.0, 0.1, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 0.0, 1.0],
[0.2, 0.2, 0.2, 0.4, 0.0],
[1.0, 0.0, 0.0, 0.0, 0.0]
])
label_probs = add_labels_for_empty_examples(label_probs_gen, non_zero_mask, output_classes, other_class_id)
np.testing.assert_equal(label_probs, expected_probs)
| [
"import numpy as np\nfrom scipy import sparse as ss\n\nimport torch\nfrom torch.utils.data import TensorDataset\nfrom knodle.trainer.snorkel.utils import (\n z_t_matrix_to_snorkel_matrix,\n prepare_empty_rule_matches,\n add_labels_for_empty_examples\n)\n\n\ndef test_z_t_matrix_to_snorkel_matrix():\n # test dense case\n z = np.array([\n [0, 1, 0, 0],\n [0, 0, 1, 1]\n ])\n\n t = np.array([\n [1, 0],\n [0, 1],\n [1, 0],\n [0, 1]\n ])\n\n snorkel_gold = np.array([\n [-1, 1, -1, -1],\n [-1, -1, 0, 1]\n ])\n\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n\n # test sparse case\n z = ss.csr_matrix([\n [0, 1, 0, 0],\n [0, 0, 1, 1]\n ])\n\n t = ss.csr_matrix([\n [1, 0],\n [0, 1],\n [1, 0],\n [0, 1]\n ])\n\n snorkel_gold = np.array([\n [-1, 1, -1, -1],\n [-1, -1, 0, 1]\n ])\n\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n\n\ndef test_label_model_data():\n num_samples = 5\n num_rules = 6\n\n rule_matches_z = np.ones((num_samples, num_rules))\n rule_matches_z[[1, 4]] = 0\n\n non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(rule_matches_z)\n\n expected_mask = np.array([True, False, True, True, False])\n expected_rule_matches = np.ones((3, num_rules))\n\n np.testing.assert_equal(non_zero_mask, expected_mask)\n np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)\n\n\ndef test_other_class_labels():\n label_probs_gen = np.array([\n [0.3, 0.6, 0.0, 0.1],\n [0.2, 0.2, 0.2, 0.4],\n [1.0, 0.0, 0.0, 0.0]\n ])\n output_classes = 5\n other_class_id = 4\n\n # test without empty rows\n non_zero_mask = np.array([True, True, True])\n expected_probs = np.array([\n [0.3, 0.6, 0.0, 0.1, 0.0],\n [0.2, 0.2, 0.2, 0.4, 0.0],\n [1.0, 0.0, 0.0, 0.0, 0.0]\n ])\n label_probs = add_labels_for_empty_examples(label_probs_gen, non_zero_mask, output_classes, other_class_id)\n\n np.testing.assert_equal(label_probs, expected_probs)\n\n # test with empty rows\n non_zero_mask = np.array([True, False, False, True, True])\n expected_probs = np.array([\n [0.3, 0.6, 0.0, 0.1, 0.0],\n [0.0, 0.0, 0.0, 0.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 1.0],\n [0.2, 0.2, 0.2, 0.4, 0.0],\n [1.0, 0.0, 0.0, 0.0, 0.0]\n ])\n label_probs = add_labels_for_empty_examples(label_probs_gen, non_zero_mask, output_classes, other_class_id)\n\n np.testing.assert_equal(label_probs, expected_probs)\n",
"import numpy as np\nfrom scipy import sparse as ss\nimport torch\nfrom torch.utils.data import TensorDataset\nfrom knodle.trainer.snorkel.utils import z_t_matrix_to_snorkel_matrix, prepare_empty_rule_matches, add_labels_for_empty_examples\n\n\ndef test_z_t_matrix_to_snorkel_matrix():\n z = np.array([[0, 1, 0, 0], [0, 0, 1, 1]])\n t = np.array([[1, 0], [0, 1], [1, 0], [0, 1]])\n snorkel_gold = np.array([[-1, 1, -1, -1], [-1, -1, 0, 1]])\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n z = ss.csr_matrix([[0, 1, 0, 0], [0, 0, 1, 1]])\n t = ss.csr_matrix([[1, 0], [0, 1], [1, 0], [0, 1]])\n snorkel_gold = np.array([[-1, 1, -1, -1], [-1, -1, 0, 1]])\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n\n\ndef test_label_model_data():\n num_samples = 5\n num_rules = 6\n rule_matches_z = np.ones((num_samples, num_rules))\n rule_matches_z[[1, 4]] = 0\n non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(\n rule_matches_z)\n expected_mask = np.array([True, False, True, True, False])\n expected_rule_matches = np.ones((3, num_rules))\n np.testing.assert_equal(non_zero_mask, expected_mask)\n np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)\n\n\ndef test_other_class_labels():\n label_probs_gen = np.array([[0.3, 0.6, 0.0, 0.1], [0.2, 0.2, 0.2, 0.4],\n [1.0, 0.0, 0.0, 0.0]])\n output_classes = 5\n other_class_id = 4\n non_zero_mask = np.array([True, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.2, 0.2, 0.2, \n 0.4, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n non_zero_mask = np.array([True, False, False, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.0, 0.0, 0.0, \n 0.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], [0.2, 0.2, 0.2, 0.4, 0.0], [\n 1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n",
"<import token>\n\n\ndef test_z_t_matrix_to_snorkel_matrix():\n z = np.array([[0, 1, 0, 0], [0, 0, 1, 1]])\n t = np.array([[1, 0], [0, 1], [1, 0], [0, 1]])\n snorkel_gold = np.array([[-1, 1, -1, -1], [-1, -1, 0, 1]])\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n z = ss.csr_matrix([[0, 1, 0, 0], [0, 0, 1, 1]])\n t = ss.csr_matrix([[1, 0], [0, 1], [1, 0], [0, 1]])\n snorkel_gold = np.array([[-1, 1, -1, -1], [-1, -1, 0, 1]])\n snorkel_test = z_t_matrix_to_snorkel_matrix(z, t)\n np.testing.assert_equal(snorkel_gold, snorkel_test)\n\n\ndef test_label_model_data():\n num_samples = 5\n num_rules = 6\n rule_matches_z = np.ones((num_samples, num_rules))\n rule_matches_z[[1, 4]] = 0\n non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(\n rule_matches_z)\n expected_mask = np.array([True, False, True, True, False])\n expected_rule_matches = np.ones((3, num_rules))\n np.testing.assert_equal(non_zero_mask, expected_mask)\n np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)\n\n\ndef test_other_class_labels():\n label_probs_gen = np.array([[0.3, 0.6, 0.0, 0.1], [0.2, 0.2, 0.2, 0.4],\n [1.0, 0.0, 0.0, 0.0]])\n output_classes = 5\n other_class_id = 4\n non_zero_mask = np.array([True, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.2, 0.2, 0.2, \n 0.4, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n non_zero_mask = np.array([True, False, False, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.0, 0.0, 0.0, \n 0.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], [0.2, 0.2, 0.2, 0.4, 0.0], [\n 1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n",
"<import token>\n<function token>\n\n\ndef test_label_model_data():\n num_samples = 5\n num_rules = 6\n rule_matches_z = np.ones((num_samples, num_rules))\n rule_matches_z[[1, 4]] = 0\n non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(\n rule_matches_z)\n expected_mask = np.array([True, False, True, True, False])\n expected_rule_matches = np.ones((3, num_rules))\n np.testing.assert_equal(non_zero_mask, expected_mask)\n np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)\n\n\ndef test_other_class_labels():\n label_probs_gen = np.array([[0.3, 0.6, 0.0, 0.1], [0.2, 0.2, 0.2, 0.4],\n [1.0, 0.0, 0.0, 0.0]])\n output_classes = 5\n other_class_id = 4\n non_zero_mask = np.array([True, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.2, 0.2, 0.2, \n 0.4, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n non_zero_mask = np.array([True, False, False, True, True])\n expected_probs = np.array([[0.3, 0.6, 0.0, 0.1, 0.0], [0.0, 0.0, 0.0, \n 0.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], [0.2, 0.2, 0.2, 0.4, 0.0], [\n 1.0, 0.0, 0.0, 0.0, 0.0]])\n label_probs = add_labels_for_empty_examples(label_probs_gen,\n non_zero_mask, output_classes, other_class_id)\n np.testing.assert_equal(label_probs, expected_probs)\n",
"<import token>\n<function token>\n\n\ndef test_label_model_data():\n num_samples = 5\n num_rules = 6\n rule_matches_z = np.ones((num_samples, num_rules))\n rule_matches_z[[1, 4]] = 0\n non_zero_mask, out_rule_matches_z = prepare_empty_rule_matches(\n rule_matches_z)\n expected_mask = np.array([True, False, True, True, False])\n expected_rule_matches = np.ones((3, num_rules))\n np.testing.assert_equal(non_zero_mask, expected_mask)\n np.testing.assert_equal(out_rule_matches_z, expected_rule_matches)\n\n\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,765 | 104e94b1fc47efcfe32e61968f4a8f98b9ac8bc2 | # coding:utf8
__author__ = 'seal'
__data__ = '7/29/17'
from flask import Blueprint
admin = Blueprint("admin", __name__)
import app.admin.views | [
"# coding:utf8\n__author__ = 'seal'\n__data__ = '7/29/17'\n\n\nfrom flask import Blueprint\n\nadmin = Blueprint(\"admin\", __name__)\n\nimport app.admin.views",
"__author__ = 'seal'\n__data__ = '7/29/17'\nfrom flask import Blueprint\nadmin = Blueprint('admin', __name__)\nimport app.admin.views\n",
"__author__ = 'seal'\n__data__ = '7/29/17'\n<import token>\nadmin = Blueprint('admin', __name__)\n<import token>\n",
"<assignment token>\n<import token>\n<assignment token>\n<import token>\n"
] | false |
99,766 | 82ec7fe9351ddf05c74d0d83a6fd68b3b2d4489e | import torch
from tqdm import tqdm
import json
class MovieDataSet(torch.utils.data.Dataset):
def __init__(self, vocab, infile):
self.vocab = vocab
self.labels = []
self.sentences = []
line_cnt = 0
with open(infile, "r") as f:
for line in f:
line_cnt += 1
with open(infile, "r") as f:
for i, line in enumerate(tqdm(f, total=line_cnt, desc=f"Loading {infile}", unit=" lines")):
data = json.loads(line)
self.labels.append(data["label"])
self.sentences.append([vocab.piece_to_id(p) for p in data["doc"]])
def __len__(self):
assert len(self.labels) == len(self.sentences)
return len(self.labels)
def __getitem__(self, item):
return (torch.tensor(self.labels[item]),
torch.tensor(self.sentences[item]),
torch.tensor([self.vocab.piece_to_id("[BOS]")])) | [
"import torch\nfrom tqdm import tqdm\nimport json\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n def __init__(self, vocab, infile):\n self.vocab = vocab\n self.labels = []\n self.sentences = []\n\n line_cnt = 0\n with open(infile, \"r\") as f:\n for line in f:\n line_cnt += 1\n\n with open(infile, \"r\") as f:\n for i, line in enumerate(tqdm(f, total=line_cnt, desc=f\"Loading {infile}\", unit=\" lines\")):\n data = json.loads(line)\n self.labels.append(data[\"label\"])\n self.sentences.append([vocab.piece_to_id(p) for p in data[\"doc\"]])\n \n def __len__(self):\n assert len(self.labels) == len(self.sentences)\n return len(self.labels)\n \n def __getitem__(self, item):\n return (torch.tensor(self.labels[item]),\n torch.tensor(self.sentences[item]),\n torch.tensor([self.vocab.piece_to_id(\"[BOS]\")]))",
"import torch\nfrom tqdm import tqdm\nimport json\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n\n def __init__(self, vocab, infile):\n self.vocab = vocab\n self.labels = []\n self.sentences = []\n line_cnt = 0\n with open(infile, 'r') as f:\n for line in f:\n line_cnt += 1\n with open(infile, 'r') as f:\n for i, line in enumerate(tqdm(f, total=line_cnt, desc=\n f'Loading {infile}', unit=' lines')):\n data = json.loads(line)\n self.labels.append(data['label'])\n self.sentences.append([vocab.piece_to_id(p) for p in data[\n 'doc']])\n\n def __len__(self):\n assert len(self.labels) == len(self.sentences)\n return len(self.labels)\n\n def __getitem__(self, item):\n return torch.tensor(self.labels[item]), torch.tensor(self.sentences\n [item]), torch.tensor([self.vocab.piece_to_id('[BOS]')])\n",
"<import token>\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n\n def __init__(self, vocab, infile):\n self.vocab = vocab\n self.labels = []\n self.sentences = []\n line_cnt = 0\n with open(infile, 'r') as f:\n for line in f:\n line_cnt += 1\n with open(infile, 'r') as f:\n for i, line in enumerate(tqdm(f, total=line_cnt, desc=\n f'Loading {infile}', unit=' lines')):\n data = json.loads(line)\n self.labels.append(data['label'])\n self.sentences.append([vocab.piece_to_id(p) for p in data[\n 'doc']])\n\n def __len__(self):\n assert len(self.labels) == len(self.sentences)\n return len(self.labels)\n\n def __getitem__(self, item):\n return torch.tensor(self.labels[item]), torch.tensor(self.sentences\n [item]), torch.tensor([self.vocab.piece_to_id('[BOS]')])\n",
"<import token>\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n <function token>\n\n def __len__(self):\n assert len(self.labels) == len(self.sentences)\n return len(self.labels)\n\n def __getitem__(self, item):\n return torch.tensor(self.labels[item]), torch.tensor(self.sentences\n [item]), torch.tensor([self.vocab.piece_to_id('[BOS]')])\n",
"<import token>\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n <function token>\n <function token>\n\n def __getitem__(self, item):\n return torch.tensor(self.labels[item]), torch.tensor(self.sentences\n [item]), torch.tensor([self.vocab.piece_to_id('[BOS]')])\n",
"<import token>\n\n\nclass MovieDataSet(torch.utils.data.Dataset):\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,767 | 1e85755070688e2959c113e016d46b5ee2377313 | from django.contrib import admin
from environment.models import *
class ServiceInline(admin.TabularInline):
model = Service
extra = 1
class JobServiceInline(admin.TabularInline):
model = JobService
extra = 1
class EnvironmentAdmin(admin.ModelAdmin):
fields = ['name', 'description','portal','setting']
inlines = [ServiceInline]
list_display = ('name', 'description','portal','setting')
class ServerAdmin(admin.ModelAdmin):
fields = ['hostname','type']
class MonitorAdmin(admin.ModelAdmin):
fields = ['name','headerscript','pidscript','script','server']
class ServiceAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'hostname', 'port','url','logfile','server','monitored','pslocator','monitor_script']
list_display = ('name', 'description', 'hostname', 'port','url','logfile','server','monitored','pslocator','monitor_script')
class JobAdmin(admin.ModelAdmin):
fields = ['name', 'description','pattern','function']
inlines = [JobServiceInline]
list_display = ('name', 'description','pattern','function')
class JobServiceAdmin(admin.ModelAdmin):
fields = ['name', 'description','sequence','service','job']
admin.site.register(Environment, EnvironmentAdmin)
admin.site.register(Service, ServiceAdmin)
admin.site.register(Job,JobAdmin)
admin.site.register(JobService,JobServiceAdmin)
admin.site.register(Server,ServerAdmin)
admin.site.register(Monitor,MonitorAdmin)
# Register your models here.
| [
"from django.contrib import admin\nfrom environment.models import *\n\nclass ServiceInline(admin.TabularInline):\n\tmodel = Service\n\textra = 1\n\t\nclass JobServiceInline(admin.TabularInline):\n\tmodel = JobService\n\textra = 1\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n\tfields = ['name', 'description','portal','setting']\n\tinlines = [ServiceInline]\n\tlist_display = ('name', 'description','portal','setting')\n\t\nclass ServerAdmin(admin.ModelAdmin):\n\tfields = ['hostname','type']\n\t\nclass MonitorAdmin(admin.ModelAdmin):\n\tfields = ['name','headerscript','pidscript','script','server']\n\nclass ServiceAdmin(admin.ModelAdmin):\n\tfields = ['name', 'description', 'hostname', 'port','url','logfile','server','monitored','pslocator','monitor_script']\n\tlist_display = ('name', 'description', 'hostname', 'port','url','logfile','server','monitored','pslocator','monitor_script')\n\nclass JobAdmin(admin.ModelAdmin):\n\tfields = ['name', 'description','pattern','function']\n\tinlines = [JobServiceInline]\n\tlist_display = ('name', 'description','pattern','function')\n\nclass JobServiceAdmin(admin.ModelAdmin):\n\tfields = ['name', 'description','sequence','service','job']\n\t\n\t\n\n\t\nadmin.site.register(Environment, EnvironmentAdmin)\nadmin.site.register(Service, ServiceAdmin)\nadmin.site.register(Job,JobAdmin)\nadmin.site.register(JobService,JobServiceAdmin)\nadmin.site.register(Server,ServerAdmin)\nadmin.site.register(Monitor,MonitorAdmin)\n\n# Register your models here.\n",
"from django.contrib import admin\nfrom environment.models import *\n\n\nclass ServiceInline(admin.TabularInline):\n model = Service\n extra = 1\n\n\nclass JobServiceInline(admin.TabularInline):\n model = JobService\n extra = 1\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\nadmin.site.register(Environment, EnvironmentAdmin)\nadmin.site.register(Service, ServiceAdmin)\nadmin.site.register(Job, JobAdmin)\nadmin.site.register(JobService, JobServiceAdmin)\nadmin.site.register(Server, ServerAdmin)\nadmin.site.register(Monitor, MonitorAdmin)\n",
"<import token>\n\n\nclass ServiceInline(admin.TabularInline):\n model = Service\n extra = 1\n\n\nclass JobServiceInline(admin.TabularInline):\n model = JobService\n extra = 1\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\nadmin.site.register(Environment, EnvironmentAdmin)\nadmin.site.register(Service, ServiceAdmin)\nadmin.site.register(Job, JobAdmin)\nadmin.site.register(JobService, JobServiceAdmin)\nadmin.site.register(Server, ServerAdmin)\nadmin.site.register(Monitor, MonitorAdmin)\n",
"<import token>\n\n\nclass ServiceInline(admin.TabularInline):\n model = Service\n extra = 1\n\n\nclass JobServiceInline(admin.TabularInline):\n model = JobService\n extra = 1\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n\n\nclass ServiceInline(admin.TabularInline):\n <assignment token>\n <assignment token>\n\n\nclass JobServiceInline(admin.TabularInline):\n model = JobService\n extra = 1\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n\n\nclass JobServiceInline(admin.TabularInline):\n model = JobService\n extra = 1\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n\n\nclass JobServiceInline(admin.TabularInline):\n <assignment token>\n <assignment token>\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'portal', 'setting']\n inlines = [ServiceInline]\n list_display = 'name', 'description', 'portal', 'setting'\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass EnvironmentAdmin(admin.ModelAdmin):\n <assignment token>\n <assignment token>\n <assignment token>\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass ServerAdmin(admin.ModelAdmin):\n fields = ['hostname', 'type']\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass ServerAdmin(admin.ModelAdmin):\n <assignment token>\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n fields = ['name', 'headerscript', 'pidscript', 'script', 'server']\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorAdmin(admin.ModelAdmin):\n <assignment token>\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'hostname', 'port', 'url', 'logfile',\n 'server', 'monitored', 'pslocator', 'monitor_script']\n list_display = ('name', 'description', 'hostname', 'port', 'url',\n 'logfile', 'server', 'monitored', 'pslocator', 'monitor_script')\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n <assignment token>\n <assignment token>\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass JobAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'pattern', 'function']\n inlines = [JobServiceInline]\n list_display = 'name', 'description', 'pattern', 'function'\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass JobAdmin(admin.ModelAdmin):\n <assignment token>\n <assignment token>\n <assignment token>\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'sequence', 'service', 'job']\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass JobServiceAdmin(admin.ModelAdmin):\n <assignment token>\n\n\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<code token>\n"
] | false |
99,768 | d05c39ec0683a35336546c1589dac6de9c8d22b9 | from .. import _type as t
from .. import _base as b
import random
def test_meta1():
class Rect(object):
__metaclass__ = b.ReactiveMeta
width = t._Type(int)
height = t._Type(int)
def __init__(self, width=None, height=None):
self.width = width or 0
self.height = height or 0
r = Rect.rtype.get_default()
assert isinstance(r, Rect)
assert hasattr(r, 'width')
assert hasattr(r, 'height')
def test_meta2():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
r = Rect.create()
assert isinstance(r, Rect)
assert hasattr(r, 'width')
assert hasattr(r, 'height')
def test_meta3():
class Polygon(b.Reactive):
points = t.List().add_idx('multi', t._Type(int))
p = Polygon.create()
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, int) for el in p.points)
def test_meta4():
class Shape(b.Reactive):
ttype = t.Union(children=[t._Type(int), t._Type(float), t._Type(str)])
s = Shape.create()
assert isinstance(s, Shape)
assert hasattr(s, 'ttype')
assert isinstance(s.ttype, (int,float,str))
def test_meta5():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
class Circle(b.Reactive):
radius = t._Type(int)
class Shape(b.Reactive):
kind = t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)])
s = Shape.create()
def test_meta6():
class Polygon(b.Reactive):
points = t.List().add_idx('multi', t._Type(int))
def __repr__(self):
return str(self.points)
p = Polygon.create()
name_node = p.rnode.children[0]
trs = []
#==
trs.append(name_node.replace([1,2,3], True))
trs.append(name_node.replace([1], True))
trs.append(name_node.append(5, True))
trs.append(name_node.remove(1, True))
trs.append(name_node.insert(1,6, True))
#==
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, int) for el in p.points)
def test_meta7():
class Polygon(b.Reactive):
points = t.List().add_idx('multi', t._Type(int))
def __repr__(self):
return str(self.points)
p = Polygon.create()
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, int) for el in p.points)
#==
name_node = p.rnode.children[0]
trs = []
#==
trs.append(name_node.replace([1,2,3], True))
trs.append(name_node.replace([1], True))
trs.append(name_node.append(5, True))
trs.append(name_node.remove(1, True))
trs.append(name_node.insert(1,6, True))
#==
assert p.points == [1,6]
for tr in reversed(trs):
name_node.set_value(tr.reverse())
assert p.points == []
def test_meta8():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
class Circle(b.Reactive):
radius = t._Type(int)
class Polygon(b.Reactive):
points = t.List().add_idx('multi', t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)]))
def __repr__(self):
return str(self.points)
p = Polygon.create()
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, (Rect, Circle)) for el in p.points)
#==
r = Rect.create()
c = Circle.create()
c2 = Circle.create()
#==
trs = []
points_node = p.rnode['points']
#==
trs.append(points_node.replace([r], True))
trs.append(points_node.replace([c], True))
trs.append(points_node.append(c2, True))
trs.append(points_node.remove(1, True))
trs.append(points_node.insert(1,c2, True))
#==
assert len(p.points) == 2 and all( isinstance(c, Circle) for c in p.points)
for tr in reversed(trs):
p.rnode.children[0].set_value(tr.reverse())
assert p.points == []
def test_meta9():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
class Circle(b.Reactive):
radius = t._Type(int)
class Polygon(b.Reactive):
points = t.List().add_idx('multi', t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)]))
def __repr__(self):
return str(self.points)
p = Polygon.create()
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, (Rect, Circle)) for el in p.points)
#==
start = []
r = Rect.create()
c = Circle.create()
c2 = Circle.create()
#==
trs = []
points_node = p.rnode['points']
#==
trs.append(points_node.replace([c], True))
#==
radius_node = points_node[0]['radius']
tr_radius = radius_node.replace(10, True)
trs.append(tr_radius)
trs.append(points_node.replace([r], True))
trs.append(points_node.remove(0, True))
#==
assert len(p.points) == 0 and all( isinstance(c, Circle) for c in p.points)
for tr in reversed(trs):
if tr is tr_radius: target = radius_node
else : target = points_node
target.set_value(tr.reverse())
assert p.points == []
def test_meta10():
class Polygon(b.Reactive):
points = t.List().add_idx('multi', \
t.List().add_idx('multi', t._Type(int)))
def __repr__(self):
return str(self.points)
p = Polygon.create()
p.rnode['points'].append([1,2,3], True)
assert isinstance(p, Polygon)
assert hasattr(p, 'points')
assert isinstance(p.points, list)
assert all( isinstance(el, list) for el in p.points)
#==
class Listener(object):
def tr_append(self, transaction):
print transaction
def tr_remove(self, transaction):
print transaction
def tr_delete(self, transaction):
print transaction
def tr_replace(self, transaction):
print transaction
def tr_insert(self, transaction):
print transaction
#==
start = p.points
points_node = p.rnode['points']
sublist_node = points_node[0]
int_node = sublist_node[0]
#==
int_node.register(Listener())
sublist_node.register(Listener())
points_node.register(Listener())
#==
tr0 = []
for i in range(10):
i = random.randint(0, 50)
tr0.append(sublist_node.append(i, True))
#==
trs = []
tr_int = int_node.replace(1999, True)
trs.append(tr_int)
trs.append(points_node.remove(0, True))
for tr in reversed(trs):
target = points_node if tr != tr_int else int_node
target.set_value(tr.reverse())
for tr in reversed(tr0):
target = sublist_node
target.set_value(tr.reverse())
assert p.points == start
def test_meta11():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
class Circle(b.Reactive):
radius = t._Type(int)
class Node(b.Reactive):
name = t._Type(str)
shape = t.Union(children=[t.Rtype(Circle), t.Rtype(Rect)])
class Mesh(b.Reactive):
path = t._Type(str)
scale = t._Type(float)
pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])
#==
m = Mesh.create()
m.rnode['path'].replace("models/environment", True)
m.rnode['scale'].replace(0.25, True)
m.rnode['pos'].replace([-8.0,42.0,0.0], True)
n = Node.create()
n.rnode['shape']['radius'].replace(10, True)
n.rnode['shape'].replace(Rect.create(), True)
n.rnode['shape']['width'].replace(10, True)
#==
assert isinstance(n.shape, Rect)
assert n.shape.width == 10
def test_meta12():
class Rect(b.Reactive):
width = t._Type(int)
height = t._Type(int)
class Circle(b.Reactive):
radius = t._Type(int)
class Node(b.Reactive):
name = t._Type(str)
shape = t.Union(children=[t.Rtype(Circle), t.Rtype(Rect)])
class Mesh(b.Reactive):
path = t._Type(str)
scale = t._Type(float)
pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])
node = t.Rtype(Node)
#==
m = Mesh.create().rnode
m['path'].replace("models/environment", True)
m['scale'].replace(0.25, True)
m['pos'].replace([-8.0,42.0,0.0], True)
n = m['node']
n['shape']['radius'].replace(10, True)
n['shape'].replace(Rect.create(), True)
n['shape']['width'].replace(10, True)
#==
inst = n.get_value()
assert isinstance(inst.shape, Rect)
assert inst.shape.width == 10
return m
def test_meta13():
class Mesh(b.Reactive):
path = t._Type(str)
scale = t._Type(float)
pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])
class Node(b.Reactive):
name = t._Type(str)
mesh = t.Rtype(Mesh)
class Selection(b.Reactive):
nodes = t.List().add_idx('multi', t.Rtype(Node))
class World(b.Reactive):
selection = t.Rtype(Selection)
nodes = t.List().add_idx('multi', t.Rtype(Node))
#==
n = Node.create()
m = n.rnode['mesh']
m['path'].replace("models/environment", True)
m['scale'].replace(0.25, True)
m['pos'].replace([-8.0,42.0,0.0], True)
assert n.mesh.path == "models/environment"
assert n.rnode['mesh']['path'].get_value() == "models/environment"
#==
w = World.create()
w.rnode['nodes'].append(n, True)
#==
assert n.mesh.path == "models/environment"
assert n.rnode['mesh']['path'].get_value() == "models/environment"
#==
assert w.nodes[0].mesh.path == "models/environment"
| [
"from .. import _type as t\nfrom .. import _base as b\nimport random\n\ndef test_meta1():\n class Rect(object):\n __metaclass__ = b.ReactiveMeta\n width = t._Type(int)\n height = t._Type(int)\n def __init__(self, width=None, height=None):\n self.width = width or 0\n self.height = height or 0\n r = Rect.rtype.get_default()\n assert isinstance(r, Rect)\n assert hasattr(r, 'width')\n assert hasattr(r, 'height')\n \ndef test_meta2():\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n r = Rect.create()\n assert isinstance(r, Rect)\n assert hasattr(r, 'width')\n assert hasattr(r, 'height')\n\ndef test_meta3():\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', t._Type(int))\n p = Polygon.create()\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, int) for el in p.points)\n\ndef test_meta4():\n class Shape(b.Reactive):\n ttype = t.Union(children=[t._Type(int), t._Type(float), t._Type(str)])\n s = Shape.create()\n assert isinstance(s, Shape)\n assert hasattr(s, 'ttype')\n assert isinstance(s.ttype, (int,float,str))\n\ndef test_meta5():\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n class Circle(b.Reactive):\n radius = t._Type(int)\n class Shape(b.Reactive):\n kind = t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)])\n s = Shape.create()\n\n\ndef test_meta6():\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', t._Type(int))\n def __repr__(self):\n return str(self.points)\n p = Polygon.create()\n name_node = p.rnode.children[0]\n trs = []\n #==\n trs.append(name_node.replace([1,2,3], True))\n trs.append(name_node.replace([1], True))\n trs.append(name_node.append(5, True))\n trs.append(name_node.remove(1, True))\n trs.append(name_node.insert(1,6, True))\n #==\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, int) for el in p.points)\n\ndef test_meta7():\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', t._Type(int))\n def __repr__(self):\n return str(self.points)\n p = Polygon.create()\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, int) for el in p.points)\n #==\n name_node = p.rnode.children[0]\n trs = []\n #==\n trs.append(name_node.replace([1,2,3], True))\n trs.append(name_node.replace([1], True))\n trs.append(name_node.append(5, True))\n trs.append(name_node.remove(1, True))\n trs.append(name_node.insert(1,6, True))\n #==\n assert p.points == [1,6]\n for tr in reversed(trs):\n name_node.set_value(tr.reverse())\n assert p.points == []\n\ndef test_meta8():\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n class Circle(b.Reactive):\n radius = t._Type(int)\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)]))\n def __repr__(self):\n return str(self.points)\n p = Polygon.create()\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, (Rect, Circle)) for el in p.points)\n #==\n r = Rect.create()\n c = Circle.create()\n c2 = Circle.create()\n #==\n trs = []\n points_node = p.rnode['points']\n #==\n trs.append(points_node.replace([r], True))\n trs.append(points_node.replace([c], True))\n trs.append(points_node.append(c2, True))\n trs.append(points_node.remove(1, True))\n trs.append(points_node.insert(1,c2, True))\n #==\n assert len(p.points) == 2 and all( isinstance(c, Circle) for c in p.points)\n for tr in reversed(trs):\n p.rnode.children[0].set_value(tr.reverse())\n assert p.points == []\n\ndef test_meta9():\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n class Circle(b.Reactive):\n radius = t._Type(int)\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', t.Union(children=[t.Rtype(Rect), t.Rtype(Circle)]))\n def __repr__(self):\n return str(self.points)\n p = Polygon.create()\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, (Rect, Circle)) for el in p.points)\n #==\n start = [] \n r = Rect.create()\n c = Circle.create()\n c2 = Circle.create()\n #==\n trs = []\n points_node = p.rnode['points']\n #==\n trs.append(points_node.replace([c], True))\n #==\n radius_node = points_node[0]['radius']\n tr_radius = radius_node.replace(10, True)\n trs.append(tr_radius)\n trs.append(points_node.replace([r], True))\n trs.append(points_node.remove(0, True))\n #==\n assert len(p.points) == 0 and all( isinstance(c, Circle) for c in p.points)\n for tr in reversed(trs):\n if tr is tr_radius: target = radius_node\n else : target = points_node\n target.set_value(tr.reverse())\n assert p.points == []\n\ndef test_meta10():\n class Polygon(b.Reactive):\n points = t.List().add_idx('multi', \\\n t.List().add_idx('multi', t._Type(int)))\n def __repr__(self):\n return str(self.points)\n p = Polygon.create()\n p.rnode['points'].append([1,2,3], True)\n assert isinstance(p, Polygon)\n assert hasattr(p, 'points')\n assert isinstance(p.points, list)\n assert all( isinstance(el, list) for el in p.points)\n #==\n class Listener(object):\n def tr_append(self, transaction):\n print transaction\n def tr_remove(self, transaction):\n print transaction\n def tr_delete(self, transaction):\n print transaction\n def tr_replace(self, transaction):\n print transaction\n def tr_insert(self, transaction):\n print transaction\n #==\n start = p.points\n points_node = p.rnode['points']\n sublist_node = points_node[0]\n int_node = sublist_node[0]\n #==\n int_node.register(Listener())\n sublist_node.register(Listener())\n points_node.register(Listener())\n #==\n tr0 = []\n for i in range(10):\n i = random.randint(0, 50)\n tr0.append(sublist_node.append(i, True))\n #==\n trs = []\n tr_int = int_node.replace(1999, True)\n trs.append(tr_int)\n trs.append(points_node.remove(0, True))\n for tr in reversed(trs):\n target = points_node if tr != tr_int else int_node\n target.set_value(tr.reverse())\n for tr in reversed(tr0):\n target = sublist_node\n target.set_value(tr.reverse())\n assert p.points == start\n\n\ndef test_meta11():\n\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n\n class Circle(b.Reactive):\n radius = t._Type(int)\n\n class Node(b.Reactive):\n name = t._Type(str)\n shape = t.Union(children=[t.Rtype(Circle), t.Rtype(Rect)])\n\n class Mesh(b.Reactive):\n path = t._Type(str)\n scale = t._Type(float)\n pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])\n\n #==\n m = Mesh.create()\n m.rnode['path'].replace(\"models/environment\", True)\n m.rnode['scale'].replace(0.25, True)\n m.rnode['pos'].replace([-8.0,42.0,0.0], True)\n n = Node.create()\n n.rnode['shape']['radius'].replace(10, True)\n n.rnode['shape'].replace(Rect.create(), True)\n n.rnode['shape']['width'].replace(10, True)\n #==\n assert isinstance(n.shape, Rect)\n assert n.shape.width == 10\n\ndef test_meta12():\n\n class Rect(b.Reactive):\n width = t._Type(int)\n height = t._Type(int)\n\n class Circle(b.Reactive):\n radius = t._Type(int)\n\n class Node(b.Reactive):\n name = t._Type(str)\n shape = t.Union(children=[t.Rtype(Circle), t.Rtype(Rect)])\n\n class Mesh(b.Reactive):\n path = t._Type(str)\n scale = t._Type(float)\n pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])\n node = t.Rtype(Node)\n\n #==\n m = Mesh.create().rnode\n m['path'].replace(\"models/environment\", True)\n m['scale'].replace(0.25, True)\n m['pos'].replace([-8.0,42.0,0.0], True)\n n = m['node']\n n['shape']['radius'].replace(10, True)\n n['shape'].replace(Rect.create(), True)\n n['shape']['width'].replace(10, True)\n #==\n inst = n.get_value()\n assert isinstance(inst.shape, Rect)\n assert inst.shape.width == 10\n return m\n\ndef test_meta13():\n\n class Mesh(b.Reactive):\n path = t._Type(str)\n scale = t._Type(float)\n pos = t.List().add_idxs([t._Type(float), t._Type(float), t._Type(float)])\n\n class Node(b.Reactive):\n name = t._Type(str)\n mesh = t.Rtype(Mesh)\n\n class Selection(b.Reactive):\n nodes = t.List().add_idx('multi', t.Rtype(Node))\n\n class World(b.Reactive):\n selection = t.Rtype(Selection)\n nodes = t.List().add_idx('multi', t.Rtype(Node))\n\n #==\n n = Node.create()\n m = n.rnode['mesh']\n m['path'].replace(\"models/environment\", True)\n m['scale'].replace(0.25, True)\n m['pos'].replace([-8.0,42.0,0.0], True)\n assert n.mesh.path == \"models/environment\"\n assert n.rnode['mesh']['path'].get_value() == \"models/environment\"\n #==\n w = World.create()\n w.rnode['nodes'].append(n, True)\n #==\n assert n.mesh.path == \"models/environment\"\n assert n.rnode['mesh']['path'].get_value() == \"models/environment\"\n #==\n assert w.nodes[0].mesh.path == \"models/environment\"\n"
] | true |
99,769 | 0edbd7403fac7cf192274481cb3edb571f6686a6 | # coding: utf-8
import logging
import sys
if 'stdout' not in globals():
stdout = sys.stdout
if 'stderr' not in globals():
stderr = sys.stderr
class StdOutLogger(object):
def __init__(self, orig, writer):
self.orig = orig
self.writer = writer
self.buffer = ''
def write(self, s):
if s.endswith('\n'):
self.writer(self.buffer + s[0:-1])
self.buffer = ''
else:
self.buffer = self.buffer + s
def flush(self):
pass
def __getattr__(self, name):
return object.__getattribute__(self.orig, name)
def init_logger(output_file='output.log',
log_format='%(asctime)-15s [%(levelname)s] %(message)s'):
logger = logging.getLogger()
logger.handlers = []
logger.addHandler(logging.StreamHandler(stdout))
if output_file is not None:
logger.addHandler(logging.FileHandler(output_file))
for x in logger.handlers:
x.setFormatter(logging.Formatter(log_format))
logger.setLevel(logging.INFO)
sys.stdout = StdOutLogger(stdout, lambda s: logger.info(s))
sys.stderr = StdOutLogger(stderr, lambda s: logger.error(s))
return logger
| [
"# coding: utf-8\n\nimport logging\nimport sys\n\nif 'stdout' not in globals():\n stdout = sys.stdout\nif 'stderr' not in globals():\n stderr = sys.stderr\n\nclass StdOutLogger(object):\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n\n def write(self, s):\n if s.endswith('\\n'):\n self.writer(self.buffer + s[0:-1])\n self.buffer = ''\n else:\n self.buffer = self.buffer + s\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\ndef init_logger(output_file='output.log',\n log_format='%(asctime)-15s [%(levelname)s] %(message)s'):\n logger = logging.getLogger()\n logger.handlers = []\n logger.addHandler(logging.StreamHandler(stdout))\n if output_file is not None:\n logger.addHandler(logging.FileHandler(output_file))\n for x in logger.handlers:\n x.setFormatter(logging.Formatter(log_format))\n logger.setLevel(logging.INFO)\n sys.stdout = StdOutLogger(stdout, lambda s: logger.info(s))\n sys.stderr = StdOutLogger(stderr, lambda s: logger.error(s))\n return logger\n",
"import logging\nimport sys\nif 'stdout' not in globals():\n stdout = sys.stdout\nif 'stderr' not in globals():\n stderr = sys.stderr\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n\n def write(self, s):\n if s.endswith('\\n'):\n self.writer(self.buffer + s[0:-1])\n self.buffer = ''\n else:\n self.buffer = self.buffer + s\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\ndef init_logger(output_file='output.log', log_format=\n '%(asctime)-15s [%(levelname)s] %(message)s'):\n logger = logging.getLogger()\n logger.handlers = []\n logger.addHandler(logging.StreamHandler(stdout))\n if output_file is not None:\n logger.addHandler(logging.FileHandler(output_file))\n for x in logger.handlers:\n x.setFormatter(logging.Formatter(log_format))\n logger.setLevel(logging.INFO)\n sys.stdout = StdOutLogger(stdout, lambda s: logger.info(s))\n sys.stderr = StdOutLogger(stderr, lambda s: logger.error(s))\n return logger\n",
"<import token>\nif 'stdout' not in globals():\n stdout = sys.stdout\nif 'stderr' not in globals():\n stderr = sys.stderr\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n\n def write(self, s):\n if s.endswith('\\n'):\n self.writer(self.buffer + s[0:-1])\n self.buffer = ''\n else:\n self.buffer = self.buffer + s\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\ndef init_logger(output_file='output.log', log_format=\n '%(asctime)-15s [%(levelname)s] %(message)s'):\n logger = logging.getLogger()\n logger.handlers = []\n logger.addHandler(logging.StreamHandler(stdout))\n if output_file is not None:\n logger.addHandler(logging.FileHandler(output_file))\n for x in logger.handlers:\n x.setFormatter(logging.Formatter(log_format))\n logger.setLevel(logging.INFO)\n sys.stdout = StdOutLogger(stdout, lambda s: logger.info(s))\n sys.stderr = StdOutLogger(stderr, lambda s: logger.error(s))\n return logger\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n\n def write(self, s):\n if s.endswith('\\n'):\n self.writer(self.buffer + s[0:-1])\n self.buffer = ''\n else:\n self.buffer = self.buffer + s\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\ndef init_logger(output_file='output.log', log_format=\n '%(asctime)-15s [%(levelname)s] %(message)s'):\n logger = logging.getLogger()\n logger.handlers = []\n logger.addHandler(logging.StreamHandler(stdout))\n if output_file is not None:\n logger.addHandler(logging.FileHandler(output_file))\n for x in logger.handlers:\n x.setFormatter(logging.Formatter(log_format))\n logger.setLevel(logging.INFO)\n sys.stdout = StdOutLogger(stdout, lambda s: logger.info(s))\n sys.stderr = StdOutLogger(stderr, lambda s: logger.error(s))\n return logger\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n\n def write(self, s):\n if s.endswith('\\n'):\n self.writer(self.buffer + s[0:-1])\n self.buffer = ''\n else:\n self.buffer = self.buffer + s\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\n<function token>\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n <function token>\n\n def flush(self):\n pass\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\n<function token>\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n\n def __init__(self, orig, writer):\n self.orig = orig\n self.writer = writer\n self.buffer = ''\n <function token>\n <function token>\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\n<function token>\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n <function token>\n <function token>\n <function token>\n\n def __getattr__(self, name):\n return object.__getattribute__(self.orig, name)\n\n\n<function token>\n",
"<import token>\n<code token>\n\n\nclass StdOutLogger(object):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n",
"<import token>\n<code token>\n<class token>\n<function token>\n"
] | false |
99,770 | 5ac90f6186df20e2ec976b4c6e94818a5d18d7c5 | import os
import platform
#import pyttsx3
print("#############################################################")
print('Hey ' + os.getlogin() + '!! Welcome to IIEC Rise Python challenge world !!!!!')
print('To fetch the OS & resources details, network checks, play with files and dirs')
print("#############################################################")
print('press 1: if you want to chat with bot : ')
print('press 2: if you want to drive through menu :', end='')
op = int(input())
while True:
if(op == 1):
print("enter the message please : ", end='')
txt = input()
if(("dns lookup" in txt) or ("dns query" in txt) or ("perform dns" in txt) or ("dns resolution" in txt) or ("dns" in txt)):
print("enter hostname to lookup : ", end='')
a1 = input()
res = os.system("nslookup " + a1)
elif("ping" in txt):
print("enter hostname to ping : ", end='')
a2 = input()
res = os.system("ping " + a2)
elif(("install tool" in txt) or ("install software" in txt) or ("application install" in txt) or ("add new software" in txt) or ("new tool" in txt)):
print("enter path to install new application :", end='')
fpath = input()
cpath = os.chdir(fpath)
print("changed directory is : " + os.getcwd())
print('enter application name to be installed :', end='')
aname = input()
if(aname):
os.system(aname)
else:
print('invalid name')
elif(("print OS details" in txt) or ("fetch OS details" in txt) or ("OS and user details" in txt) or ("OS details" in txt)):
print("OS is : " + platform.system())
print("USer logged in is : " + os.getlogin())
print("CPU Count is : " + str(os.cpu_count()))
elif("quit" in txt or "bye" in txt or "terminate" in txt or "exit" in txt):
exit()
if(op == 2):
print("#############################################################")
print('Hey ' + os.getlogin() + '!! Welcome to IIEC Rise Python challenge world !!!!!')
print('press 1: to fetch the OS & resources details')
print('press 2: to explore network bot')
print('press 3: to install any software (setup must be in .exe format only)')
print('press 4: play with files and directories')
print('press 5: quit to exit')
print("#############################################################")
print('enter your choice: ', end='')
c = int(input())
if(c == 1):
print("OS is : " + platform.system())
print("USer logged in is : " + os.getlogin())
print("CPU Count is : " + str(os.cpu_count()))
#print(os.getuid())
#os.system("chrome")
if(c == 2):
print('press 1: for ping check')
print('press 2: for nslookup check')
print('press 3: quit')
print('######################################')
print('enter your choice for network bot: ', end='')
ch = int(input())
if(ch == 1):
print("enter IP or hostname to check ping: ", end='')
ip = input()
resp = os.system("ping " + ip)
if(resp == 0):
print("Host is up")
else:
print("down or unreachable or not valid FQDN")
print()
# file = open('pingout.txt','w')
# file.write(resp)
# file.close()
# r = open('pingout.txt','r')
# if("0%" in r.read()):
# print("its up")
# elif(("timed out" in r.read()) or ("host unreachable" in r.read()) or ("ttl expired in transit" in r.read())):
# print("There seems to be an issue reaching host")
# elif(("unknown host" in r.read()) or ("could not find host") in r.read()):
# print("Invalid host")
elif(ch == 2):
print("enter hostname or IP to perform DNS lookup: ", end='')
hn = input()
res = os.system("nslookup " + hn)
elif(ch == 3):
exit()
if(c == 3):
print("Does the software already exists ? ")
curfilepath = os.getcwd()
print('current working dir is :' + curfilepath)
print('Enter file/application path to install')
newfilepath = input()
chgfilepath = os.chdir(newfilepath)
print('Changed directory is:' + os.getcwd())
print('Below are files present in directory : ')
print(os.listdir(chgfilepath))
print('Enter application name to be installed :', end='')
appname = input()
if(appname):
os.system(appname)
else:
print('invalid name')
if(c == 4):
print('Press 1: to create directories')
os.makedirs(input())
if(c == 5):
exit()
| [
"import os\nimport platform\n#import pyttsx3\n\nprint(\"#############################################################\")\nprint('Hey ' + os.getlogin() + '!! Welcome to IIEC Rise Python challenge world !!!!!')\nprint('To fetch the OS & resources details, network checks, play with files and dirs')\nprint(\"#############################################################\")\n\nprint('press 1: if you want to chat with bot : ')\nprint('press 2: if you want to drive through menu :', end='')\nop = int(input())\nwhile True:\n if(op == 1):\n print(\"enter the message please : \", end='')\n txt = input()\n if((\"dns lookup\" in txt) or (\"dns query\" in txt) or (\"perform dns\" in txt) or (\"dns resolution\" in txt) or (\"dns\" in txt)):\n print(\"enter hostname to lookup : \", end='')\n a1 = input()\n res = os.system(\"nslookup \" + a1)\n elif(\"ping\" in txt):\n print(\"enter hostname to ping : \", end='')\n a2 = input()\n res = os.system(\"ping \" + a2)\n elif((\"install tool\" in txt) or (\"install software\" in txt) or (\"application install\" in txt) or (\"add new software\" in txt) or (\"new tool\" in txt)):\n print(\"enter path to install new application :\", end='')\n fpath = input()\n cpath = os.chdir(fpath)\n print(\"changed directory is : \" + os.getcwd())\n print('enter application name to be installed :', end='')\n aname = input()\n if(aname):\n os.system(aname)\n else:\n print('invalid name')\n elif((\"print OS details\" in txt) or (\"fetch OS details\" in txt) or (\"OS and user details\" in txt) or (\"OS details\" in txt)):\n print(\"OS is : \" + platform.system())\n print(\"USer logged in is : \" + os.getlogin())\n print(\"CPU Count is : \" + str(os.cpu_count()))\n elif(\"quit\" in txt or \"bye\" in txt or \"terminate\" in txt or \"exit\" in txt):\n exit()\n\n\n if(op == 2):\n print(\"#############################################################\")\n print('Hey ' + os.getlogin() + '!! Welcome to IIEC Rise Python challenge world !!!!!')\n print('press 1: to fetch the OS & resources details')\n print('press 2: to explore network bot')\n print('press 3: to install any software (setup must be in .exe format only)')\n print('press 4: play with files and directories')\n print('press 5: quit to exit')\n print(\"#############################################################\")\n\n print('enter your choice: ', end='')\n c = int(input())\n if(c == 1):\n print(\"OS is : \" + platform.system())\n print(\"USer logged in is : \" + os.getlogin())\n print(\"CPU Count is : \" + str(os.cpu_count()))\n #print(os.getuid())\n #os.system(\"chrome\")\n\n\n if(c == 2):\n print('press 1: for ping check')\n print('press 2: for nslookup check')\n print('press 3: quit')\n \n print('######################################')\n print('enter your choice for network bot: ', end='')\n ch = int(input())\n if(ch == 1):\n print(\"enter IP or hostname to check ping: \", end='')\n ip = input()\n resp = os.system(\"ping \" + ip)\n if(resp == 0):\n print(\"Host is up\")\n else:\n print(\"down or unreachable or not valid FQDN\")\n print()\n # file = open('pingout.txt','w')\n # file.write(resp)\n # file.close()\n # r = open('pingout.txt','r')\n # if(\"0%\" in r.read()):\n # print(\"its up\")\n # elif((\"timed out\" in r.read()) or (\"host unreachable\" in r.read()) or (\"ttl expired in transit\" in r.read())):\n # print(\"There seems to be an issue reaching host\")\n # elif((\"unknown host\" in r.read()) or (\"could not find host\") in r.read()):\n # print(\"Invalid host\")\n elif(ch == 2):\n print(\"enter hostname or IP to perform DNS lookup: \", end='')\n hn = input()\n res = os.system(\"nslookup \" + hn)\n elif(ch == 3):\n exit()\n\n\n if(c == 3):\n print(\"Does the software already exists ? \")\n curfilepath = os.getcwd()\n print('current working dir is :' + curfilepath)\n print('Enter file/application path to install')\n newfilepath = input()\n chgfilepath = os.chdir(newfilepath)\n print('Changed directory is:' + os.getcwd())\n print('Below are files present in directory : ')\n print(os.listdir(chgfilepath))\n print('Enter application name to be installed :', end='')\n appname = input()\n if(appname):\n os.system(appname)\n else:\n print('invalid name')\n \n\n if(c == 4):\n print('Press 1: to create directories')\n os.makedirs(input())\n\n\n if(c == 5):\n exit()\n\n\n\n\n ",
"import os\nimport platform\nprint('#############################################################')\nprint('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\nprint(\n 'To fetch the OS & resources details, network checks, play with files and dirs'\n )\nprint('#############################################################')\nprint('press 1: if you want to chat with bot : ')\nprint('press 2: if you want to drive through menu :', end='')\nop = int(input())\nwhile True:\n if op == 1:\n print('enter the message please : ', end='')\n txt = input()\n if ('dns lookup' in txt or 'dns query' in txt or 'perform dns' in\n txt or 'dns resolution' in txt or 'dns' in txt):\n print('enter hostname to lookup : ', end='')\n a1 = input()\n res = os.system('nslookup ' + a1)\n elif 'ping' in txt:\n print('enter hostname to ping : ', end='')\n a2 = input()\n res = os.system('ping ' + a2)\n elif 'install tool' in txt or 'install software' in txt or 'application install' in txt or 'add new software' in txt or 'new tool' in txt:\n print('enter path to install new application :', end='')\n fpath = input()\n cpath = os.chdir(fpath)\n print('changed directory is : ' + os.getcwd())\n print('enter application name to be installed :', end='')\n aname = input()\n if aname:\n os.system(aname)\n else:\n print('invalid name')\n elif 'print OS details' in txt or 'fetch OS details' in txt or 'OS and user details' in txt or 'OS details' in txt:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n elif 'quit' in txt or 'bye' in txt or 'terminate' in txt or 'exit' in txt:\n exit()\n if op == 2:\n print('#############################################################')\n print('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\n print('press 1: to fetch the OS & resources details')\n print('press 2: to explore network bot')\n print(\n 'press 3: to install any software (setup must be in .exe format only)'\n )\n print('press 4: play with files and directories')\n print('press 5: quit to exit')\n print('#############################################################')\n print('enter your choice: ', end='')\n c = int(input())\n if c == 1:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n if c == 2:\n print('press 1: for ping check')\n print('press 2: for nslookup check')\n print('press 3: quit')\n print('######################################')\n print('enter your choice for network bot: ', end='')\n ch = int(input())\n if ch == 1:\n print('enter IP or hostname to check ping: ', end='')\n ip = input()\n resp = os.system('ping ' + ip)\n if resp == 0:\n print('Host is up')\n else:\n print('down or unreachable or not valid FQDN')\n print()\n elif ch == 2:\n print('enter hostname or IP to perform DNS lookup: ', end='')\n hn = input()\n res = os.system('nslookup ' + hn)\n elif ch == 3:\n exit()\n if c == 3:\n print('Does the software already exists ? ')\n curfilepath = os.getcwd()\n print('current working dir is :' + curfilepath)\n print('Enter file/application path to install')\n newfilepath = input()\n chgfilepath = os.chdir(newfilepath)\n print('Changed directory is:' + os.getcwd())\n print('Below are files present in directory : ')\n print(os.listdir(chgfilepath))\n print('Enter application name to be installed :', end='')\n appname = input()\n if appname:\n os.system(appname)\n else:\n print('invalid name')\n if c == 4:\n print('Press 1: to create directories')\n os.makedirs(input())\n if c == 5:\n exit()\n",
"<import token>\nprint('#############################################################')\nprint('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\nprint(\n 'To fetch the OS & resources details, network checks, play with files and dirs'\n )\nprint('#############################################################')\nprint('press 1: if you want to chat with bot : ')\nprint('press 2: if you want to drive through menu :', end='')\nop = int(input())\nwhile True:\n if op == 1:\n print('enter the message please : ', end='')\n txt = input()\n if ('dns lookup' in txt or 'dns query' in txt or 'perform dns' in\n txt or 'dns resolution' in txt or 'dns' in txt):\n print('enter hostname to lookup : ', end='')\n a1 = input()\n res = os.system('nslookup ' + a1)\n elif 'ping' in txt:\n print('enter hostname to ping : ', end='')\n a2 = input()\n res = os.system('ping ' + a2)\n elif 'install tool' in txt or 'install software' in txt or 'application install' in txt or 'add new software' in txt or 'new tool' in txt:\n print('enter path to install new application :', end='')\n fpath = input()\n cpath = os.chdir(fpath)\n print('changed directory is : ' + os.getcwd())\n print('enter application name to be installed :', end='')\n aname = input()\n if aname:\n os.system(aname)\n else:\n print('invalid name')\n elif 'print OS details' in txt or 'fetch OS details' in txt or 'OS and user details' in txt or 'OS details' in txt:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n elif 'quit' in txt or 'bye' in txt or 'terminate' in txt or 'exit' in txt:\n exit()\n if op == 2:\n print('#############################################################')\n print('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\n print('press 1: to fetch the OS & resources details')\n print('press 2: to explore network bot')\n print(\n 'press 3: to install any software (setup must be in .exe format only)'\n )\n print('press 4: play with files and directories')\n print('press 5: quit to exit')\n print('#############################################################')\n print('enter your choice: ', end='')\n c = int(input())\n if c == 1:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n if c == 2:\n print('press 1: for ping check')\n print('press 2: for nslookup check')\n print('press 3: quit')\n print('######################################')\n print('enter your choice for network bot: ', end='')\n ch = int(input())\n if ch == 1:\n print('enter IP or hostname to check ping: ', end='')\n ip = input()\n resp = os.system('ping ' + ip)\n if resp == 0:\n print('Host is up')\n else:\n print('down or unreachable or not valid FQDN')\n print()\n elif ch == 2:\n print('enter hostname or IP to perform DNS lookup: ', end='')\n hn = input()\n res = os.system('nslookup ' + hn)\n elif ch == 3:\n exit()\n if c == 3:\n print('Does the software already exists ? ')\n curfilepath = os.getcwd()\n print('current working dir is :' + curfilepath)\n print('Enter file/application path to install')\n newfilepath = input()\n chgfilepath = os.chdir(newfilepath)\n print('Changed directory is:' + os.getcwd())\n print('Below are files present in directory : ')\n print(os.listdir(chgfilepath))\n print('Enter application name to be installed :', end='')\n appname = input()\n if appname:\n os.system(appname)\n else:\n print('invalid name')\n if c == 4:\n print('Press 1: to create directories')\n os.makedirs(input())\n if c == 5:\n exit()\n",
"<import token>\nprint('#############################################################')\nprint('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\nprint(\n 'To fetch the OS & resources details, network checks, play with files and dirs'\n )\nprint('#############################################################')\nprint('press 1: if you want to chat with bot : ')\nprint('press 2: if you want to drive through menu :', end='')\n<assignment token>\nwhile True:\n if op == 1:\n print('enter the message please : ', end='')\n txt = input()\n if ('dns lookup' in txt or 'dns query' in txt or 'perform dns' in\n txt or 'dns resolution' in txt or 'dns' in txt):\n print('enter hostname to lookup : ', end='')\n a1 = input()\n res = os.system('nslookup ' + a1)\n elif 'ping' in txt:\n print('enter hostname to ping : ', end='')\n a2 = input()\n res = os.system('ping ' + a2)\n elif 'install tool' in txt or 'install software' in txt or 'application install' in txt or 'add new software' in txt or 'new tool' in txt:\n print('enter path to install new application :', end='')\n fpath = input()\n cpath = os.chdir(fpath)\n print('changed directory is : ' + os.getcwd())\n print('enter application name to be installed :', end='')\n aname = input()\n if aname:\n os.system(aname)\n else:\n print('invalid name')\n elif 'print OS details' in txt or 'fetch OS details' in txt or 'OS and user details' in txt or 'OS details' in txt:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n elif 'quit' in txt or 'bye' in txt or 'terminate' in txt or 'exit' in txt:\n exit()\n if op == 2:\n print('#############################################################')\n print('Hey ' + os.getlogin() +\n '!! Welcome to IIEC Rise Python challenge world !!!!!')\n print('press 1: to fetch the OS & resources details')\n print('press 2: to explore network bot')\n print(\n 'press 3: to install any software (setup must be in .exe format only)'\n )\n print('press 4: play with files and directories')\n print('press 5: quit to exit')\n print('#############################################################')\n print('enter your choice: ', end='')\n c = int(input())\n if c == 1:\n print('OS is : ' + platform.system())\n print('USer logged in is : ' + os.getlogin())\n print('CPU Count is : ' + str(os.cpu_count()))\n if c == 2:\n print('press 1: for ping check')\n print('press 2: for nslookup check')\n print('press 3: quit')\n print('######################################')\n print('enter your choice for network bot: ', end='')\n ch = int(input())\n if ch == 1:\n print('enter IP or hostname to check ping: ', end='')\n ip = input()\n resp = os.system('ping ' + ip)\n if resp == 0:\n print('Host is up')\n else:\n print('down or unreachable or not valid FQDN')\n print()\n elif ch == 2:\n print('enter hostname or IP to perform DNS lookup: ', end='')\n hn = input()\n res = os.system('nslookup ' + hn)\n elif ch == 3:\n exit()\n if c == 3:\n print('Does the software already exists ? ')\n curfilepath = os.getcwd()\n print('current working dir is :' + curfilepath)\n print('Enter file/application path to install')\n newfilepath = input()\n chgfilepath = os.chdir(newfilepath)\n print('Changed directory is:' + os.getcwd())\n print('Below are files present in directory : ')\n print(os.listdir(chgfilepath))\n print('Enter application name to be installed :', end='')\n appname = input()\n if appname:\n os.system(appname)\n else:\n print('invalid name')\n if c == 4:\n print('Press 1: to create directories')\n os.makedirs(input())\n if c == 5:\n exit()\n",
"<import token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,771 | 14bca1e52f2d85865d5fae159d6944bb18d46280 | import os
import logging
BASE_DIR = os.path.dirname(__file__)
def init_config():
logging.basicConfig(
format='%(asctime)-15s %(levelname)s %(message)s',
level=logging.DEBUG)
class Config(object):
DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')
API_HOST = '0.0.0.0'
API_PORT = 8001
CACHE_SIZE = 1 # In GB
| [
"import os\nimport logging\n\nBASE_DIR = os.path.dirname(__file__)\n\n\ndef init_config():\n logging.basicConfig(\n format='%(asctime)-15s %(levelname)s %(message)s',\n level=logging.DEBUG)\n\n\nclass Config(object):\n\n DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')\n\n API_HOST = '0.0.0.0'\n API_PORT = 8001\n\n CACHE_SIZE = 1 # In GB\n",
"import os\nimport logging\nBASE_DIR = os.path.dirname(__file__)\n\n\ndef init_config():\n logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s',\n level=logging.DEBUG)\n\n\nclass Config(object):\n DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')\n API_HOST = '0.0.0.0'\n API_PORT = 8001\n CACHE_SIZE = 1\n",
"<import token>\nBASE_DIR = os.path.dirname(__file__)\n\n\ndef init_config():\n logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s',\n level=logging.DEBUG)\n\n\nclass Config(object):\n DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')\n API_HOST = '0.0.0.0'\n API_PORT = 8001\n CACHE_SIZE = 1\n",
"<import token>\n<assignment token>\n\n\ndef init_config():\n logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s',\n level=logging.DEBUG)\n\n\nclass Config(object):\n DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')\n API_HOST = '0.0.0.0'\n API_PORT = 8001\n CACHE_SIZE = 1\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass Config(object):\n DB_PATH = os.path.join(BASE_DIR, 'db', 'lineserver.db')\n API_HOST = '0.0.0.0'\n API_PORT = 8001\n CACHE_SIZE = 1\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass Config(object):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<class token>\n"
] | false |
99,772 | a1505591a4446e30a4312eeb23cb6005effa4858 | #PRICE ALERT FOR AMAZON and SENDING MAIL and PUSH NOTIFICATION
#CREATED BY AYUSH MISHRA
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import requests,time,smtplib
from bs4 import BeautifulSoup
from notify_run import Notify
from datetime import datetime
'''
url = input("Enter your URL here : ")
dp = int(input("Enter your desired price : "))
'''
#-----------------------------------------------
url = "https://www.amazon.in/HP-Chrom-11-6-N3060-16G/dp/B01KWCIC8C/ref=pd_sbs_147_7?_encoding=UTF8&pd_rd_i=B01KWCIC8C&pd_rd_r=49259425-6622-48ec-96e6-cc18c90cdd69&pd_rd_w=rQXI3&pd_rd_wg=cbo19&pf_rd_p=00b53f5d-d1f8-4708-89df-2987ccce05ce&pf_rd_r=GV1J135GRPJ8PEB7SGKQ&psc=1&refRID=GV1J135GRPJ8PEB7SGKQ"
dp = 30000
URL = url
#pnmsg = "Below Rs. "+str(dp)+" you can get your laptop"
headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
def check_price():
page = requests.get(URL, headers=headers)
soup= BeautifulSoup(page.content,'html.parser')
#----------------------------------------------------- TO CHECK WHETHER soup IS WORKING OR NOT
'''m=open('soupw.txt',"wb")
m.write(soup.prettify().encode("utf-8"))
m.close'''
#--------------------------------------------------------------------------------------
title = soup.find(id="productTitle").get_text()
price = soup.find(id="priceblock_saleprice").get_text()
main_price = price[2:]
#LETS MAKE IT AN INTEGER---------------------------------------------------------------
l = len(main_price)
if (l<=6) :
main_price = price[2:5]
else:
p1 = price[2:4]
p2 = price[5:8]
pf = str(p1)+str(p2)
main_price = int(pf)
price_now = int(main_price)
#VARIABLES FOR SENDING MAIL AND PUSH NOTIFICATION---------------------------------------
title1=str(title.strip())
main_price1 = main_price
print("NAME : "+ title1)
print("CURRENT PRICE : "+ str(main_price1))
print("DESIRED PRICE : "+ str(dp))
#-----------------------------------------------Temporary fixed for values under Rs. 9,999
#FUNCTION TO CHECK THE PRICE-------------------------------------------------------
count = 0
if(price_now <= dp):
send_mail()
push_notification()
else:
count = count+1
print("Rechecking... Last checked at "+str(datetime.now()))
#Lets send the mail-----------------------------------------------------------------
def send_mail():
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.ehlo()
try:
server.login('[email protected]','ypjuoigfnwzqahzt')
except:
print("Wrong Mail_id or password..!")
exit()
subject = "Amazon: Product available at desired price, i.e, "+str(dp)
body = "Hey Ayush \n The price of the selected laptop on AMAZON has fallen down below Rs."+str(dp)+".\n So, hurry up & check the amazon link right now : "+url
msg = f"Subject: {subject} \n\n {body} "
server.sendmail(
'[email protected]',
'[email protected]',
msg
)
print("HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.")
server.quit()
#Now lets send the push notification-------------------------------------------------
def push_notification():
notify = Notify()
notify.send("Below Rs."+str(dp)+" you can get your Laptop")
print("HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID")
print("Will check again after an hour.")
#Now lets check the price after 1 min -----------------------------------------------
count = 0
while(True):
count += 1
print("Count : "+str(count))
check_price()
time.sleep(3600)
| [
"#PRICE ALERT FOR AMAZON and SENDING MAIL and PUSH NOTIFICATION\n#CREATED BY AYUSH MISHRA\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport requests,time,smtplib\nfrom bs4 import BeautifulSoup\nfrom notify_run import Notify\nfrom datetime import datetime\n'''\nurl = input(\"Enter your URL here : \")\ndp = int(input(\"Enter your desired price : \"))\n'''\n#-----------------------------------------------\nurl = \"https://www.amazon.in/HP-Chrom-11-6-N3060-16G/dp/B01KWCIC8C/ref=pd_sbs_147_7?_encoding=UTF8&pd_rd_i=B01KWCIC8C&pd_rd_r=49259425-6622-48ec-96e6-cc18c90cdd69&pd_rd_w=rQXI3&pd_rd_wg=cbo19&pf_rd_p=00b53f5d-d1f8-4708-89df-2987ccce05ce&pf_rd_r=GV1J135GRPJ8PEB7SGKQ&psc=1&refRID=GV1J135GRPJ8PEB7SGKQ\"\ndp = 30000\nURL = url\n#pnmsg = \"Below Rs. \"+str(dp)+\" you can get your laptop\"\nheaders = {\"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}\n \ndef check_price():\n page = requests.get(URL, headers=headers)\n soup= BeautifulSoup(page.content,'html.parser')\n #----------------------------------------------------- TO CHECK WHETHER soup IS WORKING OR NOT\n \n '''m=open('soupw.txt',\"wb\")\n m.write(soup.prettify().encode(\"utf-8\"))\n m.close'''\n \n #--------------------------------------------------------------------------------------\n title = soup.find(id=\"productTitle\").get_text()\n price = soup.find(id=\"priceblock_saleprice\").get_text()\n main_price = price[2:]\n #LETS MAKE IT AN INTEGER---------------------------------------------------------------\n l = len(main_price)\n if (l<=6) :\n main_price = price[2:5]\n else:\n p1 = price[2:4]\n p2 = price[5:8]\n pf = str(p1)+str(p2)\n main_price = int(pf)\n \n price_now = int(main_price)\n #VARIABLES FOR SENDING MAIL AND PUSH NOTIFICATION---------------------------------------\n title1=str(title.strip())\n main_price1 = main_price\n print(\"NAME : \"+ title1)\n print(\"CURRENT PRICE : \"+ str(main_price1))\n print(\"DESIRED PRICE : \"+ str(dp))\n #-----------------------------------------------Temporary fixed for values under Rs. 9,999\n #FUNCTION TO CHECK THE PRICE-------------------------------------------------------\n \n count = 0\n if(price_now <= dp):\n send_mail()\n push_notification()\n else:\n count = count+1\n print(\"Rechecking... Last checked at \"+str(datetime.now()))\n \n#Lets send the mail-----------------------------------------------------------------\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]','ypjuoigfnwzqahzt')\n except:\n print(\"Wrong Mail_id or password..!\")\n exit()\n subject = \"Amazon: Product available at desired price, i.e, \"+str(dp)\n body = \"Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.\"+str(dp)+\".\\n So, hurry up & check the amazon link right now : \"+url\n msg = f\"Subject: {subject} \\n\\n {body} \"\n server.sendmail(\n '[email protected]',\n '[email protected]',\n msg\n )\n print(\"HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.\")\n \n server.quit()\n#Now lets send the push notification-------------------------------------------------\ndef push_notification():\n notify = Notify()\n notify.send(\"Below Rs.\"+str(dp)+\" you can get your Laptop\")\n print(\"HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID\")\n \n print(\"Will check again after an hour.\")\n#Now lets check the price after 1 min ----------------------------------------------- \ncount = 0\nwhile(True):\n count += 1\n print(\"Count : \"+str(count))\n check_price()\n time.sleep(3600)\n",
"import requests, time, smtplib\nfrom bs4 import BeautifulSoup\nfrom notify_run import Notify\nfrom datetime import datetime\n<docstring token>\nurl = (\n 'https://www.amazon.in/HP-Chrom-11-6-N3060-16G/dp/B01KWCIC8C/ref=pd_sbs_147_7?_encoding=UTF8&pd_rd_i=B01KWCIC8C&pd_rd_r=49259425-6622-48ec-96e6-cc18c90cdd69&pd_rd_w=rQXI3&pd_rd_wg=cbo19&pf_rd_p=00b53f5d-d1f8-4708-89df-2987ccce05ce&pf_rd_r=GV1J135GRPJ8PEB7SGKQ&psc=1&refRID=GV1J135GRPJ8PEB7SGKQ'\n )\ndp = 30000\nURL = url\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'\n }\n\n\ndef check_price():\n page = requests.get(URL, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n \"\"\"m=open('soupw.txt',\"wb\")\n m.write(soup.prettify().encode(\"utf-8\"))\n m.close\"\"\"\n title = soup.find(id='productTitle').get_text()\n price = soup.find(id='priceblock_saleprice').get_text()\n main_price = price[2:]\n l = len(main_price)\n if l <= 6:\n main_price = price[2:5]\n else:\n p1 = price[2:4]\n p2 = price[5:8]\n pf = str(p1) + str(p2)\n main_price = int(pf)\n price_now = int(main_price)\n title1 = str(title.strip())\n main_price1 = main_price\n print('NAME : ' + title1)\n print('CURRENT PRICE : ' + str(main_price1))\n print('DESIRED PRICE : ' + str(dp))\n count = 0\n if price_now <= dp:\n send_mail()\n push_notification()\n else:\n count = count + 1\n print('Rechecking... Last checked at ' + str(datetime.now()))\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\ndef push_notification():\n notify = Notify()\n notify.send('Below Rs.' + str(dp) + ' you can get your Laptop')\n print('HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID')\n print('Will check again after an hour.')\n\n\ncount = 0\nwhile True:\n count += 1\n print('Count : ' + str(count))\n check_price()\n time.sleep(3600)\n",
"<import token>\n<docstring token>\nurl = (\n 'https://www.amazon.in/HP-Chrom-11-6-N3060-16G/dp/B01KWCIC8C/ref=pd_sbs_147_7?_encoding=UTF8&pd_rd_i=B01KWCIC8C&pd_rd_r=49259425-6622-48ec-96e6-cc18c90cdd69&pd_rd_w=rQXI3&pd_rd_wg=cbo19&pf_rd_p=00b53f5d-d1f8-4708-89df-2987ccce05ce&pf_rd_r=GV1J135GRPJ8PEB7SGKQ&psc=1&refRID=GV1J135GRPJ8PEB7SGKQ'\n )\ndp = 30000\nURL = url\nheaders = {'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'\n }\n\n\ndef check_price():\n page = requests.get(URL, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n \"\"\"m=open('soupw.txt',\"wb\")\n m.write(soup.prettify().encode(\"utf-8\"))\n m.close\"\"\"\n title = soup.find(id='productTitle').get_text()\n price = soup.find(id='priceblock_saleprice').get_text()\n main_price = price[2:]\n l = len(main_price)\n if l <= 6:\n main_price = price[2:5]\n else:\n p1 = price[2:4]\n p2 = price[5:8]\n pf = str(p1) + str(p2)\n main_price = int(pf)\n price_now = int(main_price)\n title1 = str(title.strip())\n main_price1 = main_price\n print('NAME : ' + title1)\n print('CURRENT PRICE : ' + str(main_price1))\n print('DESIRED PRICE : ' + str(dp))\n count = 0\n if price_now <= dp:\n send_mail()\n push_notification()\n else:\n count = count + 1\n print('Rechecking... Last checked at ' + str(datetime.now()))\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\ndef push_notification():\n notify = Notify()\n notify.send('Below Rs.' + str(dp) + ' you can get your Laptop')\n print('HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID')\n print('Will check again after an hour.')\n\n\ncount = 0\nwhile True:\n count += 1\n print('Count : ' + str(count))\n check_price()\n time.sleep(3600)\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef check_price():\n page = requests.get(URL, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n \"\"\"m=open('soupw.txt',\"wb\")\n m.write(soup.prettify().encode(\"utf-8\"))\n m.close\"\"\"\n title = soup.find(id='productTitle').get_text()\n price = soup.find(id='priceblock_saleprice').get_text()\n main_price = price[2:]\n l = len(main_price)\n if l <= 6:\n main_price = price[2:5]\n else:\n p1 = price[2:4]\n p2 = price[5:8]\n pf = str(p1) + str(p2)\n main_price = int(pf)\n price_now = int(main_price)\n title1 = str(title.strip())\n main_price1 = main_price\n print('NAME : ' + title1)\n print('CURRENT PRICE : ' + str(main_price1))\n print('DESIRED PRICE : ' + str(dp))\n count = 0\n if price_now <= dp:\n send_mail()\n push_notification()\n else:\n count = count + 1\n print('Rechecking... Last checked at ' + str(datetime.now()))\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\ndef push_notification():\n notify = Notify()\n notify.send('Below Rs.' + str(dp) + ' you can get your Laptop')\n print('HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID')\n print('Will check again after an hour.')\n\n\n<assignment token>\nwhile True:\n count += 1\n print('Count : ' + str(count))\n check_price()\n time.sleep(3600)\n",
"<import token>\n<docstring token>\n<assignment token>\n\n\ndef check_price():\n page = requests.get(URL, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n \"\"\"m=open('soupw.txt',\"wb\")\n m.write(soup.prettify().encode(\"utf-8\"))\n m.close\"\"\"\n title = soup.find(id='productTitle').get_text()\n price = soup.find(id='priceblock_saleprice').get_text()\n main_price = price[2:]\n l = len(main_price)\n if l <= 6:\n main_price = price[2:5]\n else:\n p1 = price[2:4]\n p2 = price[5:8]\n pf = str(p1) + str(p2)\n main_price = int(pf)\n price_now = int(main_price)\n title1 = str(title.strip())\n main_price1 = main_price\n print('NAME : ' + title1)\n print('CURRENT PRICE : ' + str(main_price1))\n print('DESIRED PRICE : ' + str(dp))\n count = 0\n if price_now <= dp:\n send_mail()\n push_notification()\n else:\n count = count + 1\n print('Rechecking... Last checked at ' + str(datetime.now()))\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\ndef push_notification():\n notify = Notify()\n notify.send('Below Rs.' + str(dp) + ' you can get your Laptop')\n print('HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID')\n print('Will check again after an hour.')\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\ndef push_notification():\n notify = Notify()\n notify.send('Below Rs.' + str(dp) + ' you can get your Laptop')\n print('HEY AYUSH, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY ON ANDROID')\n print('Will check again after an hour.')\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n\n\ndef send_mail():\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n try:\n server.login('[email protected]', 'ypjuoigfnwzqahzt')\n except:\n print('Wrong Mail_id or password..!')\n exit()\n subject = 'Amazon: Product available at desired price, i.e, ' + str(dp)\n body = (\n 'Hey Ayush \\n The price of the selected laptop on AMAZON has fallen down below Rs.'\n + str(dp) +\n \"\"\".\n So, hurry up & check the amazon link right now : \"\"\" + url)\n msg = f'Subject: {subject} \\n\\n {body} '\n server.sendmail('[email protected]', '[email protected]', msg)\n print('HEY AYUSH, EMAIL HAS BEEN SENT SUCCESSFULLY.')\n server.quit()\n\n\n<function token>\n<assignment token>\n<code token>\n",
"<import token>\n<docstring token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n"
] | false |
99,773 | ced79ecbde0c92bc8fc43f4032d4caa93092c28f | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import messages
from django.shortcuts import render, redirect
# Create your views here.
def index(request):
print "MADE IT TO INDEX"
return render(request, "index.html")
def process(request):
print "MADE IT TO PROCESS"
print request.POST
print request.POST['name']
print request.POST['location']
print request.POST['language']
print request.POST['comment']
request.session['name'] = request.POST['name']
request.session['location'] = request.POST["location"]
request.session['language'] = request.POST['language']
request.session['comment'] = request.POST['comment']
# context= {
# 'name': request.POST['name'],
# 'location': request.POST['location'],
# 'language': request.POST['language'],
# 'comment': request.POST['comment']
# }
return redirect ('/survey/results')
def results(request):
return render(request, "results.html")
| [
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect\n# Create your views here.\n\n\ndef index(request):\n print \"MADE IT TO INDEX\"\n return render(request, \"index.html\")\n\ndef process(request):\n print \"MADE IT TO PROCESS\"\n print request.POST\n print request.POST['name']\n print request.POST['location']\n print request.POST['language']\n print request.POST['comment']\n request.session['name'] = request.POST['name']\n request.session['location'] = request.POST[\"location\"]\n request.session['language'] = request.POST['language']\n request.session['comment'] = request.POST['comment']\n # context= {\n # 'name': request.POST['name'],\n # 'location': request.POST['location'],\n # 'language': request.POST['language'],\n # 'comment': request.POST['comment']\n # }\n return redirect ('/survey/results')\n\ndef results(request):\n return render(request, \"results.html\")\n"
] | true |
99,774 | c4baa1a5c88ded48e0bba791adb4a3e5167acda5 | # 9 - Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
# C = 5 * ((F-32) / 9).
fahrenheit = float(input('Quantos Fahrenheit deseja converter em Graus Celsius? --> '))
resultado = 5 * ((fahrenheit - 32) / 9)
print(f'O valor de {fahrenheit}ºF é equivalente há {resultado:.2f}ºC.')
| [
"# 9 - Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.\n# C = 5 * ((F-32) / 9).\n\nfahrenheit = float(input('Quantos Fahrenheit deseja converter em Graus Celsius? --> '))\nresultado = 5 * ((fahrenheit - 32) / 9)\n\nprint(f'O valor de {fahrenheit}ºF é equivalente há {resultado:.2f}ºC.')\n\n\n",
"fahrenheit = float(input(\n 'Quantos Fahrenheit deseja converter em Graus Celsius? --> '))\nresultado = 5 * ((fahrenheit - 32) / 9)\nprint(f'O valor de {fahrenheit}ºF é equivalente há {resultado:.2f}ºC.')\n",
"<assignment token>\nprint(f'O valor de {fahrenheit}ºF é equivalente há {resultado:.2f}ºC.')\n",
"<assignment token>\n<code token>\n"
] | false |
99,775 | e7d7033dc857930ad821fbe01964607c04ec1f72 | n = int(input())
s = set(map(int, input().split()))
N = int(input())
for i in range(N):
command,num = input().split()
value = list(map(int,input().split()))
if command == 'intersection_update':
s.intersection_update(value)
if command == 'update':
s.update(value)
if command == 'symmetric_difference_update':
s.symmetric_difference_update(value)
if command == 'difference_update':
s.difference_update(value)
print(sum(s)) | [
"n = int(input())\ns = set(map(int, input().split())) \nN = int(input())\nfor i in range(N):\n command,num = input().split()\n value = list(map(int,input().split()))\n if command == 'intersection_update':\n s.intersection_update(value)\n if command == 'update':\n s.update(value)\n if command == 'symmetric_difference_update':\n s.symmetric_difference_update(value)\n if command == 'difference_update':\n s.difference_update(value)\nprint(sum(s))",
"n = int(input())\ns = set(map(int, input().split()))\nN = int(input())\nfor i in range(N):\n command, num = input().split()\n value = list(map(int, input().split()))\n if command == 'intersection_update':\n s.intersection_update(value)\n if command == 'update':\n s.update(value)\n if command == 'symmetric_difference_update':\n s.symmetric_difference_update(value)\n if command == 'difference_update':\n s.difference_update(value)\nprint(sum(s))\n",
"<assignment token>\nfor i in range(N):\n command, num = input().split()\n value = list(map(int, input().split()))\n if command == 'intersection_update':\n s.intersection_update(value)\n if command == 'update':\n s.update(value)\n if command == 'symmetric_difference_update':\n s.symmetric_difference_update(value)\n if command == 'difference_update':\n s.difference_update(value)\nprint(sum(s))\n",
"<assignment token>\n<code token>\n"
] | false |
99,776 | 0d85a9a4143939cde9951841302fd900150cb819 | import nltk
import re
import string
import matplotlib.pyplot as plt
import math
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory, StopWordRemover, ArrayDictionary
from collections import Counter
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
def createStopword(more_stopword = []) :
stop_factory = StopWordRemoverFactory().get_stop_words()
new_stop_word = stop_factory + more_stopword
dictionary = ArrayDictionary(new_stop_word)
stopword = StopWordRemover(dictionary)
return stopword
def stemming(sentence) :
return stemmer.stem(sentence)
def normalize_text(text) :
text = text.lower()
text = re.sub(r"\d+", " ", text)
text = text.translate(str.maketrans("","",string.punctuation)).strip()
return text
def preTextProcessing(text) :
global factory , stemmer , stopword
text = text.rstrip()
text= normalize_text(text)
text_no_stopword = stopword.remove(text)
text_stemmed =stemmer.stem(text_no_stopword)
print("stemmed : \n")
print(text_stemmed)
print("\n")
return text_stemmed
def tokenization(text) :
text = preTextProcessing(text)
tokens = nltk.tokenize.word_tokenize(text)
frequency = nltk.FreqDist(tokens)
return dict(frequency.most_common())
stopword = createStopword(['saya','kamu', 'bukan','huruf','bagai'])
factory = StemmerFactory()
stemmer = factory.create_stemmer() | [
"import nltk\nimport re \nimport string\nimport matplotlib.pyplot as plt\nimport math\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nfrom Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory, StopWordRemover, ArrayDictionary\nfrom collections import Counter\nfrom nltk.tokenize import word_tokenize\nfrom nltk.probability import FreqDist\n\n\n\ndef createStopword(more_stopword = []) : \n stop_factory = StopWordRemoverFactory().get_stop_words() \n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\n\ndef stemming(sentence) : \n return stemmer.stem(sentence)\n\ndef normalize_text(text) : \n text = text.lower()\n text = re.sub(r\"\\d+\", \" \", text)\n text = text.translate(str.maketrans(\"\",\"\",string.punctuation)).strip()\n return text\n\ndef preTextProcessing(text) : \n global factory , stemmer , stopword\n \n text = text.rstrip()\n text= normalize_text(text)\n\n text_no_stopword = stopword.remove(text)\n text_stemmed =stemmer.stem(text_no_stopword)\n \n print(\"stemmed : \\n\")\n print(text_stemmed)\n print(\"\\n\")\n return text_stemmed\n\ndef tokenization(text) : \n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\nstopword = createStopword(['saya','kamu', 'bukan','huruf','bagai'])\nfactory = StemmerFactory()\nstemmer = factory.create_stemmer()",
"import nltk\nimport re\nimport string\nimport matplotlib.pyplot as plt\nimport math\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nfrom Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory, StopWordRemover, ArrayDictionary\nfrom collections import Counter\nfrom nltk.tokenize import word_tokenize\nfrom nltk.probability import FreqDist\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\ndef normalize_text(text):\n text = text.lower()\n text = re.sub('\\\\d+', ' ', text)\n text = text.translate(str.maketrans('', '', string.punctuation)).strip()\n return text\n\n\ndef preTextProcessing(text):\n global factory, stemmer, stopword\n text = text.rstrip()\n text = normalize_text(text)\n text_no_stopword = stopword.remove(text)\n text_stemmed = stemmer.stem(text_no_stopword)\n print('stemmed : \\n')\n print(text_stemmed)\n print('\\n')\n return text_stemmed\n\n\ndef tokenization(text):\n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\nstopword = createStopword(['saya', 'kamu', 'bukan', 'huruf', 'bagai'])\nfactory = StemmerFactory()\nstemmer = factory.create_stemmer()\n",
"<import token>\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\ndef normalize_text(text):\n text = text.lower()\n text = re.sub('\\\\d+', ' ', text)\n text = text.translate(str.maketrans('', '', string.punctuation)).strip()\n return text\n\n\ndef preTextProcessing(text):\n global factory, stemmer, stopword\n text = text.rstrip()\n text = normalize_text(text)\n text_no_stopword = stopword.remove(text)\n text_stemmed = stemmer.stem(text_no_stopword)\n print('stemmed : \\n')\n print(text_stemmed)\n print('\\n')\n return text_stemmed\n\n\ndef tokenization(text):\n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\nstopword = createStopword(['saya', 'kamu', 'bukan', 'huruf', 'bagai'])\nfactory = StemmerFactory()\nstemmer = factory.create_stemmer()\n",
"<import token>\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\ndef normalize_text(text):\n text = text.lower()\n text = re.sub('\\\\d+', ' ', text)\n text = text.translate(str.maketrans('', '', string.punctuation)).strip()\n return text\n\n\ndef preTextProcessing(text):\n global factory, stemmer, stopword\n text = text.rstrip()\n text = normalize_text(text)\n text_no_stopword = stopword.remove(text)\n text_stemmed = stemmer.stem(text_no_stopword)\n print('stemmed : \\n')\n print(text_stemmed)\n print('\\n')\n return text_stemmed\n\n\ndef tokenization(text):\n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\n<assignment token>\n",
"<import token>\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\ndef normalize_text(text):\n text = text.lower()\n text = re.sub('\\\\d+', ' ', text)\n text = text.translate(str.maketrans('', '', string.punctuation)).strip()\n return text\n\n\n<function token>\n\n\ndef tokenization(text):\n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\n<assignment token>\n",
"<import token>\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\n<function token>\n<function token>\n\n\ndef tokenization(text):\n text = preTextProcessing(text)\n tokens = nltk.tokenize.word_tokenize(text)\n frequency = nltk.FreqDist(tokens)\n return dict(frequency.most_common())\n\n\n<assignment token>\n",
"<import token>\n\n\ndef createStopword(more_stopword=[]):\n stop_factory = StopWordRemoverFactory().get_stop_words()\n new_stop_word = stop_factory + more_stopword\n dictionary = ArrayDictionary(new_stop_word)\n stopword = StopWordRemover(dictionary)\n return stopword\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n",
"<import token>\n<function token>\n\n\ndef stemming(sentence):\n return stemmer.stem(sentence)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n"
] | false |
99,777 | 4ced5e53ad009cfffae53bbf66f20803fd6fde8b | # -*- coding: utf-8 -*-
import sys
from PySide2.QtWidgets import QPushButton, QLabel, QVBoxLayout, QTextEdit, QHBoxLayout, QColorDialog, QApplication, \
QDoubleSpinBox
from PySide2.QtCore import Qt
from PySide2.QtGui import QColor
from ..gui.checkbox import *
from ..core.datatype import *
from ..gui.widget import BasicWidget, TableWidget
class CheckboxDemoWidget(BasicWidget):
TOTAL_COLUMN, TOTAL_ROW, CHECKBOX_COLUMN = 6, 5, 5
def __init__(self, parent=None):
super(CheckboxDemoWidget, self).__init__(parent)
def _initUi(self):
self.def_style = CheckBoxStyleSheet.default()
style = DynamicObject(background=(240, 240, 240), font=("宋体", 9))
self.ui_data = QTextEdit(self)
self.ui_table = TableWidget(self.TOTAL_COLUMN)
self.ui_factor = QDoubleSpinBox(self)
self.ui_get_data = QPushButton("Get Data")
self.ui_font_color = QPushButton(self.tr("Box Color"))
self.ui_fill_color = QPushButton(self.tr("Fill Color"))
self.ui_hover_color = QPushButton(self.tr("Hover Color"))
self.ui_bg_color = QPushButton(self.tr("Background Color"))
self.ui_fg_color = QPushButton(self.tr("Foreground Color"))
self.ui_frozen = CheckBox(self.tr("Frozen"), stylesheet=style.dict, parent=self)
self.ui_with_box = CheckBox(self.tr("With box"), stylesheet=style.dict, parent=self)
tools_layout = QHBoxLayout()
for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr("Size Factor")), self.ui_factor,
self.ui_fill_color, self.ui_hover_color, self.ui_bg_color, self.ui_fg_color):
tools_layout.addWidget(x)
layout = QVBoxLayout()
layout.addWidget(self.ui_table)
layout.addLayout(tools_layout)
layout.addWidget(self.ui_get_data)
layout.addWidget(self.ui_data)
self.setLayout(layout)
self.setWindowTitle(self.tr("Checkbox Demo"))
def _initData(self):
for row in range(self.TOTAL_ROW):
data = [str(row)] * self.ui_table.columnCount()
data[-1] = str(row % 2 == 0)
data[-2] = str(row % 2 == 1)
self.ui_table.addRow(data)
self.ui_factor.setSingleStep(0.1)
self.ui_factor.setValue(self.def_style.sizeFactor)
self.ui_with_box.setChecked(self.def_style.withBox)
self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN, CheckBoxDelegate(parent=self))
def _initStyle(self):
self.ui_table.setAutoWidth()
self.ui_table.setAutoHeight(True)
self.ui_table.setItemSelectMode()
self.ui_table.setTableAlignment(Qt.AlignCenter)
[self.ui_table.openPersistentEditor(self.ui_table.item(row, self.CHECKBOX_COLUMN))
for row in range(self.ui_table.rowCount())]
def _initSignalAndSlots(self):
self.ui_with_box.stateChanged.connect(
lambda x: self.slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked))
)
self.ui_frozen.stateChanged.connect(
lambda x: self.ui_table.frozenTable(x == Qt.Checked)
)
self.ui_factor.valueChanged.connect(
lambda x: self.slotCheckboxStyleChanged(DynamicObject(sizeFactor=x))
)
self.ui_get_data.clicked.connect(
lambda: self.ui_data.setText("{}".format(self.ui_table.getTableData()))
)
self.ui_fill_color.clicked.connect(self.slotColorChanged)
self.ui_hover_color.clicked.connect(self.slotColorChanged)
self.ui_bg_color.clicked.connect(self.slotColorChanged)
self.ui_fg_color.clicked.connect(self.slotColorChanged)
def slotColorChanged(self):
sender = self.sender()
origin_color, keyword = {
self.ui_fg_color: (self.def_style.foregroundColor(), "foreground"),
self.ui_bg_color: (self.def_style.backgroundColor(), "background"),
self.ui_fill_color: (self.def_style.getFilledColor(), "fillColor"),
self.ui_hover_color: (self.def_style.getHoverColor(), "hoverColor")
}.get(sender, (None, ""))
if not origin_color or not keyword:
return
color = QColorDialog.getColor(origin_color, self, "Get {} color".format(keyword))
if not isinstance(color, QColor):
return
self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(), color.blue())})
def slotCheckboxStyleChanged(self, stylesheet):
try:
self.def_style.update(stylesheet)
except (DynamicObjectEncodeError, TypeError) as e:
print("{}: {}".format(stylesheet, e))
return
for row in range(self.ui_table.rowCount()):
check_box = self.ui_table.indexWidget(self.ui_table.model().index(row, self.CHECKBOX_COLUMN))
if isinstance(check_box, CheckBox):
check_box.setStyleSheet(self.def_style)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = CheckboxDemoWidget()
widget.show()
sys.exit(app.exec_())
| [
"# -*- coding: utf-8 -*-\nimport sys\nfrom PySide2.QtWidgets import QPushButton, QLabel, QVBoxLayout, QTextEdit, QHBoxLayout, QColorDialog, QApplication, \\\n QDoubleSpinBox\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtGui import QColor\nfrom ..gui.checkbox import *\nfrom ..core.datatype import *\nfrom ..gui.widget import BasicWidget, TableWidget\n\n\nclass CheckboxDemoWidget(BasicWidget):\n TOTAL_COLUMN, TOTAL_ROW, CHECKBOX_COLUMN = 6, 5, 5\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=(\"宋体\", 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton(\"Get Data\")\n self.ui_font_color = QPushButton(self.tr(\"Box Color\"))\n self.ui_fill_color = QPushButton(self.tr(\"Fill Color\"))\n self.ui_hover_color = QPushButton(self.tr(\"Hover Color\"))\n self.ui_bg_color = QPushButton(self.tr(\"Background Color\"))\n self.ui_fg_color = QPushButton(self.tr(\"Foreground Color\"))\n self.ui_frozen = CheckBox(self.tr(\"Frozen\"), stylesheet=style.dict, parent=self)\n self.ui_with_box = CheckBox(self.tr(\"With box\"), stylesheet=style.dict, parent=self)\n\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\"Size Factor\")), self.ui_factor,\n self.ui_fill_color, self.ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr(\"Checkbox Demo\"))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN, CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.CHECKBOX_COLUMN))\n for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(\n lambda x: self.slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked))\n )\n\n self.ui_frozen.stateChanged.connect(\n lambda x: self.ui_table.frozenTable(x == Qt.Checked)\n )\n\n self.ui_factor.valueChanged.connect(\n lambda x: self.slotCheckboxStyleChanged(DynamicObject(sizeFactor=x))\n )\n\n self.ui_get_data.clicked.connect(\n lambda: self.ui_data.setText(\"{}\".format(self.ui_table.getTableData()))\n )\n\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n\n def slotColorChanged(self):\n sender = self.sender()\n origin_color, keyword = {\n self.ui_fg_color: (self.def_style.foregroundColor(), \"foreground\"),\n self.ui_bg_color: (self.def_style.backgroundColor(), \"background\"),\n self.ui_fill_color: (self.def_style.getFilledColor(), \"fillColor\"),\n self.ui_hover_color: (self.def_style.getHoverColor(), \"hoverColor\")\n }.get(sender, (None, \"\"))\n\n if not origin_color or not keyword:\n return\n\n color = QColorDialog.getColor(origin_color, self, \"Get {} color\".format(keyword))\n if not isinstance(color, QColor):\n return\n\n self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(), color.blue())})\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print(\"{}: {}\".format(stylesheet, e))\n return\n\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n widget = CheckboxDemoWidget()\n widget.show()\n sys.exit(app.exec_())\n",
"import sys\nfrom PySide2.QtWidgets import QPushButton, QLabel, QVBoxLayout, QTextEdit, QHBoxLayout, QColorDialog, QApplication, QDoubleSpinBox\nfrom PySide2.QtCore import Qt\nfrom PySide2.QtGui import QColor\nfrom ..gui.checkbox import *\nfrom ..core.datatype import *\nfrom ..gui.widget import BasicWidget, TableWidget\n\n\nclass CheckboxDemoWidget(BasicWidget):\n TOTAL_COLUMN, TOTAL_ROW, CHECKBOX_COLUMN = 6, 5, 5\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n\n def slotColorChanged(self):\n sender = self.sender()\n origin_color, keyword = {self.ui_fg_color: (self.def_style.\n foregroundColor(), 'foreground'), self.ui_bg_color: (self.\n def_style.backgroundColor(), 'background'), self.ui_fill_color:\n (self.def_style.getFilledColor(), 'fillColor'), self.\n ui_hover_color: (self.def_style.getHoverColor(), 'hoverColor')\n }.get(sender, (None, ''))\n if not origin_color or not keyword:\n return\n color = QColorDialog.getColor(origin_color, self, 'Get {} color'.\n format(keyword))\n if not isinstance(color, QColor):\n return\n self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(),\n color.blue())})\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print('{}: {}'.format(stylesheet, e))\n return\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().\n index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n widget = CheckboxDemoWidget()\n widget.show()\n sys.exit(app.exec_())\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n TOTAL_COLUMN, TOTAL_ROW, CHECKBOX_COLUMN = 6, 5, 5\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n\n def slotColorChanged(self):\n sender = self.sender()\n origin_color, keyword = {self.ui_fg_color: (self.def_style.\n foregroundColor(), 'foreground'), self.ui_bg_color: (self.\n def_style.backgroundColor(), 'background'), self.ui_fill_color:\n (self.def_style.getFilledColor(), 'fillColor'), self.\n ui_hover_color: (self.def_style.getHoverColor(), 'hoverColor')\n }.get(sender, (None, ''))\n if not origin_color or not keyword:\n return\n color = QColorDialog.getColor(origin_color, self, 'Get {} color'.\n format(keyword))\n if not isinstance(color, QColor):\n return\n self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(),\n color.blue())})\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print('{}: {}'.format(stylesheet, e))\n return\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().\n index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n widget = CheckboxDemoWidget()\n widget.show()\n sys.exit(app.exec_())\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n TOTAL_COLUMN, TOTAL_ROW, CHECKBOX_COLUMN = 6, 5, 5\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n\n def slotColorChanged(self):\n sender = self.sender()\n origin_color, keyword = {self.ui_fg_color: (self.def_style.\n foregroundColor(), 'foreground'), self.ui_bg_color: (self.\n def_style.backgroundColor(), 'background'), self.ui_fill_color:\n (self.def_style.getFilledColor(), 'fillColor'), self.\n ui_hover_color: (self.def_style.getHoverColor(), 'hoverColor')\n }.get(sender, (None, ''))\n if not origin_color or not keyword:\n return\n color = QColorDialog.getColor(origin_color, self, 'Get {} color'.\n format(keyword))\n if not isinstance(color, QColor):\n return\n self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(),\n color.blue())})\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print('{}: {}'.format(stylesheet, e))\n return\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().\n index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n\n def slotColorChanged(self):\n sender = self.sender()\n origin_color, keyword = {self.ui_fg_color: (self.def_style.\n foregroundColor(), 'foreground'), self.ui_bg_color: (self.\n def_style.backgroundColor(), 'background'), self.ui_fill_color:\n (self.def_style.getFilledColor(), 'fillColor'), self.\n ui_hover_color: (self.def_style.getHoverColor(), 'hoverColor')\n }.get(sender, (None, ''))\n if not origin_color or not keyword:\n return\n color = QColorDialog.getColor(origin_color, self, 'Get {} color'.\n format(keyword))\n if not isinstance(color, QColor):\n return\n self.slotCheckboxStyleChanged({keyword: (color.red(), color.green(),\n color.blue())})\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print('{}: {}'.format(stylesheet, e))\n return\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().\n index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n <function token>\n\n def slotCheckboxStyleChanged(self, stylesheet):\n try:\n self.def_style.update(stylesheet)\n except (DynamicObjectEncodeError, TypeError) as e:\n print('{}: {}'.format(stylesheet, e))\n return\n for row in range(self.ui_table.rowCount()):\n check_box = self.ui_table.indexWidget(self.ui_table.model().\n index(row, self.CHECKBOX_COLUMN))\n if isinstance(check_box, CheckBox):\n check_box.setStyleSheet(self.def_style)\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n\n def __init__(self, parent=None):\n super(CheckboxDemoWidget, self).__init__(parent)\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n <function token>\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n\n def _initSignalAndSlots(self):\n self.ui_with_box.stateChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(withBox=x == Qt.Checked)))\n self.ui_frozen.stateChanged.connect(lambda x: self.ui_table.\n frozenTable(x == Qt.Checked))\n self.ui_factor.valueChanged.connect(lambda x: self.\n slotCheckboxStyleChanged(DynamicObject(sizeFactor=x)))\n self.ui_get_data.clicked.connect(lambda : self.ui_data.setText('{}'\n .format(self.ui_table.getTableData())))\n self.ui_fill_color.clicked.connect(self.slotColorChanged)\n self.ui_hover_color.clicked.connect(self.slotColorChanged)\n self.ui_bg_color.clicked.connect(self.slotColorChanged)\n self.ui_fg_color.clicked.connect(self.slotColorChanged)\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n <function token>\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n\n def _initStyle(self):\n self.ui_table.setAutoWidth()\n self.ui_table.setAutoHeight(True)\n self.ui_table.setItemSelectMode()\n self.ui_table.setTableAlignment(Qt.AlignCenter)\n [self.ui_table.openPersistentEditor(self.ui_table.item(row, self.\n CHECKBOX_COLUMN)) for row in range(self.ui_table.rowCount())]\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n <function token>\n\n def _initUi(self):\n self.def_style = CheckBoxStyleSheet.default()\n style = DynamicObject(background=(240, 240, 240), font=('宋体', 9))\n self.ui_data = QTextEdit(self)\n self.ui_table = TableWidget(self.TOTAL_COLUMN)\n self.ui_factor = QDoubleSpinBox(self)\n self.ui_get_data = QPushButton('Get Data')\n self.ui_font_color = QPushButton(self.tr('Box Color'))\n self.ui_fill_color = QPushButton(self.tr('Fill Color'))\n self.ui_hover_color = QPushButton(self.tr('Hover Color'))\n self.ui_bg_color = QPushButton(self.tr('Background Color'))\n self.ui_fg_color = QPushButton(self.tr('Foreground Color'))\n self.ui_frozen = CheckBox(self.tr('Frozen'), stylesheet=style.dict,\n parent=self)\n self.ui_with_box = CheckBox(self.tr('With box'), stylesheet=style.\n dict, parent=self)\n tools_layout = QHBoxLayout()\n for x in (self.ui_frozen, self.ui_with_box, QLabel(self.tr(\n 'Size Factor')), self.ui_factor, self.ui_fill_color, self.\n ui_hover_color, self.ui_bg_color, self.ui_fg_color):\n tools_layout.addWidget(x)\n layout = QVBoxLayout()\n layout.addWidget(self.ui_table)\n layout.addLayout(tools_layout)\n layout.addWidget(self.ui_get_data)\n layout.addWidget(self.ui_data)\n self.setLayout(layout)\n self.setWindowTitle(self.tr('Checkbox Demo'))\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n <function token>\n <function token>\n\n def _initData(self):\n for row in range(self.TOTAL_ROW):\n data = [str(row)] * self.ui_table.columnCount()\n data[-1] = str(row % 2 == 0)\n data[-2] = str(row % 2 == 1)\n self.ui_table.addRow(data)\n self.ui_factor.setSingleStep(0.1)\n self.ui_factor.setValue(self.def_style.sizeFactor)\n self.ui_with_box.setChecked(self.def_style.withBox)\n self.ui_table.setItemDelegateForColumn(self.CHECKBOX_COLUMN,\n CheckBoxDelegate(parent=self))\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass CheckboxDemoWidget(BasicWidget):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<class token>\n<code token>\n"
] | false |
99,778 | ce7c779fce2da4821846164b5640293a444e5e4d | import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def save_bbox_images(image, bbox, label, name, path, background_class):
image = image.cpu().permute(1, 2, 0).numpy()
image = draw_boxes_on_images(image, bbox, label, background_class)
image.save(os.path.join(path,'{}.jpg'.format(name)),quality=95)
def draw_boxes_on_images(image, bbox, label, background_class):
scale = 224/max(image.shape)
H = int(scale*image.shape[0])
W = int(scale*image.shape[1])
bbox = bbox*scale
fnt = ImageFont.load_default()
image = Image.fromarray(np.uint8(image*255), 'RGB')
image = image.resize((W, H))
draw = ImageDraw.Draw(image)
for i in range(bbox.shape[0]):
if background_class and label[i]=='__background__':
continue
kp = bbox[i,:].tolist()
color = (0,0, 255)
draw.rectangle(kp, outline=color, fill=None)
color = (0,255,0)
if kp[0]<0:
x_0 = kp[2] - len(label[i])*8
else:
x_0 = kp[0] + 1
if kp[1]<0:
x_1 = kp[3] - 12
else:
x_1 = kp[1] + 1
draw.text((x_0, x_1), label[i], width=12, fill=color, font=fnt)
return image | [
"import os\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n\ndef save_bbox_images(image, bbox, label, name, path, background_class):\n image = image.cpu().permute(1, 2, 0).numpy()\n image = draw_boxes_on_images(image, bbox, label, background_class)\n image.save(os.path.join(path,'{}.jpg'.format(name)),quality=95)\n\ndef draw_boxes_on_images(image, bbox, label, background_class):\n scale = 224/max(image.shape)\n H = int(scale*image.shape[0])\n W = int(scale*image.shape[1])\n bbox = bbox*scale\n fnt = ImageFont.load_default()\n image = Image.fromarray(np.uint8(image*255), 'RGB')\n image = image.resize((W, H))\n draw = ImageDraw.Draw(image)\n for i in range(bbox.shape[0]):\n if background_class and label[i]=='__background__':\n continue\n kp = bbox[i,:].tolist()\n color = (0,0, 255)\n draw.rectangle(kp, outline=color, fill=None)\n color = (0,255,0)\n if kp[0]<0:\n x_0 = kp[2] - len(label[i])*8\n else:\n x_0 = kp[0] + 1\n if kp[1]<0:\n x_1 = kp[3] - 12\n else:\n x_1 = kp[1] + 1\n draw.text((x_0, x_1), label[i], width=12, fill=color, font=fnt)\n return image",
"import os\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n\n\ndef save_bbox_images(image, bbox, label, name, path, background_class):\n image = image.cpu().permute(1, 2, 0).numpy()\n image = draw_boxes_on_images(image, bbox, label, background_class)\n image.save(os.path.join(path, '{}.jpg'.format(name)), quality=95)\n\n\ndef draw_boxes_on_images(image, bbox, label, background_class):\n scale = 224 / max(image.shape)\n H = int(scale * image.shape[0])\n W = int(scale * image.shape[1])\n bbox = bbox * scale\n fnt = ImageFont.load_default()\n image = Image.fromarray(np.uint8(image * 255), 'RGB')\n image = image.resize((W, H))\n draw = ImageDraw.Draw(image)\n for i in range(bbox.shape[0]):\n if background_class and label[i] == '__background__':\n continue\n kp = bbox[i, :].tolist()\n color = 0, 0, 255\n draw.rectangle(kp, outline=color, fill=None)\n color = 0, 255, 0\n if kp[0] < 0:\n x_0 = kp[2] - len(label[i]) * 8\n else:\n x_0 = kp[0] + 1\n if kp[1] < 0:\n x_1 = kp[3] - 12\n else:\n x_1 = kp[1] + 1\n draw.text((x_0, x_1), label[i], width=12, fill=color, font=fnt)\n return image\n",
"<import token>\n\n\ndef save_bbox_images(image, bbox, label, name, path, background_class):\n image = image.cpu().permute(1, 2, 0).numpy()\n image = draw_boxes_on_images(image, bbox, label, background_class)\n image.save(os.path.join(path, '{}.jpg'.format(name)), quality=95)\n\n\ndef draw_boxes_on_images(image, bbox, label, background_class):\n scale = 224 / max(image.shape)\n H = int(scale * image.shape[0])\n W = int(scale * image.shape[1])\n bbox = bbox * scale\n fnt = ImageFont.load_default()\n image = Image.fromarray(np.uint8(image * 255), 'RGB')\n image = image.resize((W, H))\n draw = ImageDraw.Draw(image)\n for i in range(bbox.shape[0]):\n if background_class and label[i] == '__background__':\n continue\n kp = bbox[i, :].tolist()\n color = 0, 0, 255\n draw.rectangle(kp, outline=color, fill=None)\n color = 0, 255, 0\n if kp[0] < 0:\n x_0 = kp[2] - len(label[i]) * 8\n else:\n x_0 = kp[0] + 1\n if kp[1] < 0:\n x_1 = kp[3] - 12\n else:\n x_1 = kp[1] + 1\n draw.text((x_0, x_1), label[i], width=12, fill=color, font=fnt)\n return image\n",
"<import token>\n<function token>\n\n\ndef draw_boxes_on_images(image, bbox, label, background_class):\n scale = 224 / max(image.shape)\n H = int(scale * image.shape[0])\n W = int(scale * image.shape[1])\n bbox = bbox * scale\n fnt = ImageFont.load_default()\n image = Image.fromarray(np.uint8(image * 255), 'RGB')\n image = image.resize((W, H))\n draw = ImageDraw.Draw(image)\n for i in range(bbox.shape[0]):\n if background_class and label[i] == '__background__':\n continue\n kp = bbox[i, :].tolist()\n color = 0, 0, 255\n draw.rectangle(kp, outline=color, fill=None)\n color = 0, 255, 0\n if kp[0] < 0:\n x_0 = kp[2] - len(label[i]) * 8\n else:\n x_0 = kp[0] + 1\n if kp[1] < 0:\n x_1 = kp[3] - 12\n else:\n x_1 = kp[1] + 1\n draw.text((x_0, x_1), label[i], width=12, fill=color, font=fnt)\n return image\n",
"<import token>\n<function token>\n<function token>\n"
] | false |
99,779 | ecf050c0733d08587b2fb91ffed173a3974f6df5 | # Don't send empty bitplanes.
#
# The sender adds to the number of received bitplanes the number of
# skipped (zero) bitplanes of the chunk sent.
# The receiver computes the first received
# bitplane (apart from the bitplane with the signs) and report a
# number of bitplanes received equal to the real number of received
# bitplanes plus the number of skipped bitplanes.
import struct
import numpy as np
from intercom import Intercom
from intercom_dfc import Intercom_DFC
if __debug__:
import sys
class Intercom_empty(Intercom_DFC):
def init(self, args):
Intercom_DFC.init(self, args)
self.ignored_bps = 0
self.packet_format = f"!BHBB{self.frames_per_chunk//8}B"
def receive_and_buffer(self):
message, source_address = self.receiving_sock.recvfrom(Intercom.MAX_MESSAGE_SIZE)
ig_bps, received_chunk_number, received_bitplane_number, self.NORB, *bitplane = struct.unpack(self.packet_format, message)
bitplane = np.asarray(bitplane, dtype=np.uint8)
bitplane = np.unpackbits(bitplane)
bitplane = bitplane.astype(np.uint16)
self._buffer[received_chunk_number % self.cells_in_buffer][:, received_bitplane_number%self.number_of_channels] |= (bitplane << received_bitplane_number//self.number_of_channels)
self.received_bitplanes_per_chunk[received_chunk_number % self.cells_in_buffer] += 1 + ig_bps
return received_chunk_number
def send_bitplane(self, indata, bitplane_number, last_BPTS):
bitplane = (indata[:, bitplane_number%self.number_of_channels] >> bitplane_number//self.number_of_channels) & 1
if not np.any(bitplane) and bitplane_number != last_BPTS:
self.ignored_bps += 1
else:
bitplane = bitplane.astype(np.uint8)
bitplane = np.packbits(bitplane)
message = struct.pack(self.packet_format, self.ignored_bps, self.recorded_chunk_number, bitplane_number, self.received_bitplanes_per_chunk[(self.played_chunk_number+1) % self.cells_in_buffer]+1, *bitplane)
self.sending_sock.sendto(message, (self.destination_IP_addr, self.destination_port))
self.ignored_bps = 0
def send(self, indata):
signs = indata & 0x8000
magnitudes = abs(indata)
indata = signs | magnitudes
self.NOBPTS = int(0.75*self.NOBPTS + 0.25*self.NORB)
self.NOBPTS += 1
if self.NOBPTS > self.max_NOBPTS:
self.NOBPTS = self.max_NOBPTS
last_BPTS = self.max_NOBPTS - self.NOBPTS - 1
self.send_bitplane(indata, self.max_NOBPTS-1, last_BPTS)
self.send_bitplane(indata, self.max_NOBPTS-2, last_BPTS)
for bitplane_number in range(self.max_NOBPTS-3, last_BPTS, -1):
self.send_bitplane(indata, bitplane_number, last_BPTS)
self.recorded_chunk_number = (self.recorded_chunk_number + 1) % self.MAX_CHUNK_NUMBER
if __name__ == "__main__":
intercom = Intercom_empty()
parser = intercom.add_args()
args = parser.parse_args()
intercom.init(args)
intercom.run()
| [
"# Don't send empty bitplanes.\r\n#\r\n# The sender adds to the number of received bitplanes the number of\r\n# skipped (zero) bitplanes of the chunk sent.\r\n\r\n# The receiver computes the first received\r\n# bitplane (apart from the bitplane with the signs) and report a\r\n# number of bitplanes received equal to the real number of received\r\n# bitplanes plus the number of skipped bitplanes.\r\n\r\nimport struct\r\nimport numpy as np\r\nfrom intercom import Intercom\r\nfrom intercom_dfc import Intercom_DFC\r\n\r\nif __debug__:\r\n import sys\r\n\r\nclass Intercom_empty(Intercom_DFC):\r\n\r\n def init(self, args):\r\n Intercom_DFC.init(self, args)\r\n self.ignored_bps = 0\r\n self.packet_format = f\"!BHBB{self.frames_per_chunk//8}B\"\r\n\r\n def receive_and_buffer(self):\r\n \r\n message, source_address = self.receiving_sock.recvfrom(Intercom.MAX_MESSAGE_SIZE)\r\n ig_bps, received_chunk_number, received_bitplane_number, self.NORB, *bitplane = struct.unpack(self.packet_format, message)\r\n bitplane = np.asarray(bitplane, dtype=np.uint8)\r\n bitplane = np.unpackbits(bitplane)\r\n bitplane = bitplane.astype(np.uint16)\r\n self._buffer[received_chunk_number % self.cells_in_buffer][:, received_bitplane_number%self.number_of_channels] |= (bitplane << received_bitplane_number//self.number_of_channels)\r\n self.received_bitplanes_per_chunk[received_chunk_number % self.cells_in_buffer] += 1 + ig_bps\r\n return received_chunk_number\r\n \r\n def send_bitplane(self, indata, bitplane_number, last_BPTS): \r\n bitplane = (indata[:, bitplane_number%self.number_of_channels] >> bitplane_number//self.number_of_channels) & 1\r\n if not np.any(bitplane) and bitplane_number != last_BPTS:\r\n self.ignored_bps += 1\r\n else:\r\n bitplane = bitplane.astype(np.uint8)\r\n bitplane = np.packbits(bitplane)\r\n message = struct.pack(self.packet_format, self.ignored_bps, self.recorded_chunk_number, bitplane_number, self.received_bitplanes_per_chunk[(self.played_chunk_number+1) % self.cells_in_buffer]+1, *bitplane)\r\n self.sending_sock.sendto(message, (self.destination_IP_addr, self.destination_port))\r\n self.ignored_bps = 0\r\n\r\n def send(self, indata):\r\n signs = indata & 0x8000\r\n magnitudes = abs(indata)\r\n indata = signs | magnitudes\r\n \r\n self.NOBPTS = int(0.75*self.NOBPTS + 0.25*self.NORB)\r\n self.NOBPTS += 1\r\n if self.NOBPTS > self.max_NOBPTS:\r\n self.NOBPTS = self.max_NOBPTS\r\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\r\n self.send_bitplane(indata, self.max_NOBPTS-1, last_BPTS)\r\n self.send_bitplane(indata, self.max_NOBPTS-2, last_BPTS)\r\n for bitplane_number in range(self.max_NOBPTS-3, last_BPTS, -1):\r\n self.send_bitplane(indata, bitplane_number, last_BPTS)\r\n self.recorded_chunk_number = (self.recorded_chunk_number + 1) % self.MAX_CHUNK_NUMBER\r\n \r\n\r\nif __name__ == \"__main__\":\r\n intercom = Intercom_empty()\r\n parser = intercom.add_args()\r\n args = parser.parse_args()\r\n intercom.init(args)\r\n intercom.run()\r\n",
"import struct\nimport numpy as np\nfrom intercom import Intercom\nfrom intercom_dfc import Intercom_DFC\nif __debug__:\n import sys\n\n\nclass Intercom_empty(Intercom_DFC):\n\n def init(self, args):\n Intercom_DFC.init(self, args)\n self.ignored_bps = 0\n self.packet_format = f'!BHBB{self.frames_per_chunk // 8}B'\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n\n def send_bitplane(self, indata, bitplane_number, last_BPTS):\n bitplane = indata[:, bitplane_number % self.number_of_channels\n ] >> bitplane_number // self.number_of_channels & 1\n if not np.any(bitplane) and bitplane_number != last_BPTS:\n self.ignored_bps += 1\n else:\n bitplane = bitplane.astype(np.uint8)\n bitplane = np.packbits(bitplane)\n message = struct.pack(self.packet_format, self.ignored_bps,\n self.recorded_chunk_number, bitplane_number, self.\n received_bitplanes_per_chunk[(self.played_chunk_number + 1) %\n self.cells_in_buffer] + 1, *bitplane)\n self.sending_sock.sendto(message, (self.destination_IP_addr,\n self.destination_port))\n self.ignored_bps = 0\n\n def send(self, indata):\n signs = indata & 32768\n magnitudes = abs(indata)\n indata = signs | magnitudes\n self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB)\n self.NOBPTS += 1\n if self.NOBPTS > self.max_NOBPTS:\n self.NOBPTS = self.max_NOBPTS\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\n self.send_bitplane(indata, self.max_NOBPTS - 1, last_BPTS)\n self.send_bitplane(indata, self.max_NOBPTS - 2, last_BPTS)\n for bitplane_number in range(self.max_NOBPTS - 3, last_BPTS, -1):\n self.send_bitplane(indata, bitplane_number, last_BPTS)\n self.recorded_chunk_number = (self.recorded_chunk_number + 1\n ) % self.MAX_CHUNK_NUMBER\n\n\nif __name__ == '__main__':\n intercom = Intercom_empty()\n parser = intercom.add_args()\n args = parser.parse_args()\n intercom.init(args)\n intercom.run()\n",
"<import token>\nif __debug__:\n import sys\n\n\nclass Intercom_empty(Intercom_DFC):\n\n def init(self, args):\n Intercom_DFC.init(self, args)\n self.ignored_bps = 0\n self.packet_format = f'!BHBB{self.frames_per_chunk // 8}B'\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n\n def send_bitplane(self, indata, bitplane_number, last_BPTS):\n bitplane = indata[:, bitplane_number % self.number_of_channels\n ] >> bitplane_number // self.number_of_channels & 1\n if not np.any(bitplane) and bitplane_number != last_BPTS:\n self.ignored_bps += 1\n else:\n bitplane = bitplane.astype(np.uint8)\n bitplane = np.packbits(bitplane)\n message = struct.pack(self.packet_format, self.ignored_bps,\n self.recorded_chunk_number, bitplane_number, self.\n received_bitplanes_per_chunk[(self.played_chunk_number + 1) %\n self.cells_in_buffer] + 1, *bitplane)\n self.sending_sock.sendto(message, (self.destination_IP_addr,\n self.destination_port))\n self.ignored_bps = 0\n\n def send(self, indata):\n signs = indata & 32768\n magnitudes = abs(indata)\n indata = signs | magnitudes\n self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB)\n self.NOBPTS += 1\n if self.NOBPTS > self.max_NOBPTS:\n self.NOBPTS = self.max_NOBPTS\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\n self.send_bitplane(indata, self.max_NOBPTS - 1, last_BPTS)\n self.send_bitplane(indata, self.max_NOBPTS - 2, last_BPTS)\n for bitplane_number in range(self.max_NOBPTS - 3, last_BPTS, -1):\n self.send_bitplane(indata, bitplane_number, last_BPTS)\n self.recorded_chunk_number = (self.recorded_chunk_number + 1\n ) % self.MAX_CHUNK_NUMBER\n\n\nif __name__ == '__main__':\n intercom = Intercom_empty()\n parser = intercom.add_args()\n args = parser.parse_args()\n intercom.init(args)\n intercom.run()\n",
"<import token>\n<code token>\n\n\nclass Intercom_empty(Intercom_DFC):\n\n def init(self, args):\n Intercom_DFC.init(self, args)\n self.ignored_bps = 0\n self.packet_format = f'!BHBB{self.frames_per_chunk // 8}B'\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n\n def send_bitplane(self, indata, bitplane_number, last_BPTS):\n bitplane = indata[:, bitplane_number % self.number_of_channels\n ] >> bitplane_number // self.number_of_channels & 1\n if not np.any(bitplane) and bitplane_number != last_BPTS:\n self.ignored_bps += 1\n else:\n bitplane = bitplane.astype(np.uint8)\n bitplane = np.packbits(bitplane)\n message = struct.pack(self.packet_format, self.ignored_bps,\n self.recorded_chunk_number, bitplane_number, self.\n received_bitplanes_per_chunk[(self.played_chunk_number + 1) %\n self.cells_in_buffer] + 1, *bitplane)\n self.sending_sock.sendto(message, (self.destination_IP_addr,\n self.destination_port))\n self.ignored_bps = 0\n\n def send(self, indata):\n signs = indata & 32768\n magnitudes = abs(indata)\n indata = signs | magnitudes\n self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB)\n self.NOBPTS += 1\n if self.NOBPTS > self.max_NOBPTS:\n self.NOBPTS = self.max_NOBPTS\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\n self.send_bitplane(indata, self.max_NOBPTS - 1, last_BPTS)\n self.send_bitplane(indata, self.max_NOBPTS - 2, last_BPTS)\n for bitplane_number in range(self.max_NOBPTS - 3, last_BPTS, -1):\n self.send_bitplane(indata, bitplane_number, last_BPTS)\n self.recorded_chunk_number = (self.recorded_chunk_number + 1\n ) % self.MAX_CHUNK_NUMBER\n\n\n<code token>\n",
"<import token>\n<code token>\n\n\nclass Intercom_empty(Intercom_DFC):\n <function token>\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n\n def send_bitplane(self, indata, bitplane_number, last_BPTS):\n bitplane = indata[:, bitplane_number % self.number_of_channels\n ] >> bitplane_number // self.number_of_channels & 1\n if not np.any(bitplane) and bitplane_number != last_BPTS:\n self.ignored_bps += 1\n else:\n bitplane = bitplane.astype(np.uint8)\n bitplane = np.packbits(bitplane)\n message = struct.pack(self.packet_format, self.ignored_bps,\n self.recorded_chunk_number, bitplane_number, self.\n received_bitplanes_per_chunk[(self.played_chunk_number + 1) %\n self.cells_in_buffer] + 1, *bitplane)\n self.sending_sock.sendto(message, (self.destination_IP_addr,\n self.destination_port))\n self.ignored_bps = 0\n\n def send(self, indata):\n signs = indata & 32768\n magnitudes = abs(indata)\n indata = signs | magnitudes\n self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB)\n self.NOBPTS += 1\n if self.NOBPTS > self.max_NOBPTS:\n self.NOBPTS = self.max_NOBPTS\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\n self.send_bitplane(indata, self.max_NOBPTS - 1, last_BPTS)\n self.send_bitplane(indata, self.max_NOBPTS - 2, last_BPTS)\n for bitplane_number in range(self.max_NOBPTS - 3, last_BPTS, -1):\n self.send_bitplane(indata, bitplane_number, last_BPTS)\n self.recorded_chunk_number = (self.recorded_chunk_number + 1\n ) % self.MAX_CHUNK_NUMBER\n\n\n<code token>\n",
"<import token>\n<code token>\n\n\nclass Intercom_empty(Intercom_DFC):\n <function token>\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n <function token>\n\n def send(self, indata):\n signs = indata & 32768\n magnitudes = abs(indata)\n indata = signs | magnitudes\n self.NOBPTS = int(0.75 * self.NOBPTS + 0.25 * self.NORB)\n self.NOBPTS += 1\n if self.NOBPTS > self.max_NOBPTS:\n self.NOBPTS = self.max_NOBPTS\n last_BPTS = self.max_NOBPTS - self.NOBPTS - 1\n self.send_bitplane(indata, self.max_NOBPTS - 1, last_BPTS)\n self.send_bitplane(indata, self.max_NOBPTS - 2, last_BPTS)\n for bitplane_number in range(self.max_NOBPTS - 3, last_BPTS, -1):\n self.send_bitplane(indata, bitplane_number, last_BPTS)\n self.recorded_chunk_number = (self.recorded_chunk_number + 1\n ) % self.MAX_CHUNK_NUMBER\n\n\n<code token>\n",
"<import token>\n<code token>\n\n\nclass Intercom_empty(Intercom_DFC):\n <function token>\n\n def receive_and_buffer(self):\n message, source_address = self.receiving_sock.recvfrom(Intercom.\n MAX_MESSAGE_SIZE)\n (ig_bps, received_chunk_number, received_bitplane_number, self.NORB,\n *bitplane) = struct.unpack(self.packet_format, message)\n bitplane = np.asarray(bitplane, dtype=np.uint8)\n bitplane = np.unpackbits(bitplane)\n bitplane = bitplane.astype(np.uint16)\n self._buffer[received_chunk_number % self.cells_in_buffer][:, \n received_bitplane_number % self.number_of_channels\n ] |= bitplane << received_bitplane_number // self.number_of_channels\n self.received_bitplanes_per_chunk[received_chunk_number % self.\n cells_in_buffer] += 1 + ig_bps\n return received_chunk_number\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<code token>\n\n\nclass Intercom_empty(Intercom_DFC):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n<code token>\n<class token>\n<code token>\n"
] | false |
99,780 | 8b8738d0e54bbba25af5a73d4ffa03d5e9f74789 | import random
from words import word_list
def get_word():
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 5
print("Laten we galgje spelen!")
print('De regels:')
lijst = [
'-na een ingevoerde letter op enter drukken.',
'-na vijf foute antwoorden ben je af.'
]
for item in lijst:
print(item)
print(display_hangman(tries))
print(word_completion)
print("\n")
print('het woord heeft', len(word), 'letters')
if tries == 5:
print('je hebt nog 5 beurten over')
while not guessed and tries > 0:
guess = input("Typ een letter of een woord:").upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("Deze letter heb je al geraden.", guess)
elif guess not in word:
print(guess, "zit niet in het woord.")
tries -= 1
print('je verliest een beurt, nog', (tries), 'beurten over')
print('je hebt de letters', guessed_letters, 'al geprobeerd')
guessed_letters.append(guess)
else:
print("Goed bezig,", guess, "zit in het woord!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [
i for i, letter in enumerate(word) if letter == guess
]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
elif len(guess) == len(word) and guess.isalpha():
if guess in guessed_words:
print("Je hebt het woord al geraden", guess)
elif guess != word:
print(guess, "is niet het woord.")
tries -= 1
print('je verliest een beurt, nog', (tries), 'beurten over')
guessed_words.append(guess)
used_letters.append(guess)
else:
guessed = True
word_completion = word
else:
print("Geen geldige invoer.")
tries -= 1
print('je verliest een beurt, nog', (tries), 'beurten over')
print(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("Gefeliciteerd, je hebt het woord geraden! je wint!")
else:
print("Sorry, je hebt geen beurten meer. Het woord was " + word +
". Volgende keer beter!")
def display_hangman(tries):
stages = [
"""
--------
| |
| O
| \\|/
| |
| / \\
-
""", """
--------
| |
| O
| \\|/
| |
| /
-
""", """
--------
| |
| O
| \\|/
| |
|
-
""", """
--------
| |
| O
| \\|
| |
|
-
""", """
--------
| |
| O
| |
| |
|
-
""", """
--------
| |
| O
|
|
|
-
"""
]
return stages[tries]
def main():
word = get_word()
play(word)
while input("Nog een keer spelen? (J/N) ").upper() == "J":
word = get_word()
play(word)
if __name__ == "__main__":
main()
| [
"import random\nfrom words import word_list\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = \"_\" * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print(\"Laten we galgje spelen!\")\n print('De regels:')\n lijst = [\n '-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.'\n ]\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print(\"\\n\")\n print('het woord heeft', len(word), 'letters')\n\n if tries == 5:\n print('je hebt nog 5 beurten over')\n\n while not guessed and tries > 0:\n guess = input(\"Typ een letter of een woord:\").upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print(\"Deze letter heb je al geraden.\", guess)\n elif guess not in word:\n print(guess, \"zit niet in het woord.\")\n tries -= 1\n print('je verliest een beurt, nog', (tries), 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print(\"Goed bezig,\", guess, \"zit in het woord!\")\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [\n i for i, letter in enumerate(word) if letter == guess\n ]\n for index in indices:\n word_as_list[index] = guess\n word_completion = \"\".join(word_as_list)\n if \"_\" not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print(\"Je hebt het woord al geraden\", guess)\n elif guess != word:\n print(guess, \"is niet het woord.\")\n tries -= 1\n print('je verliest een beurt, nog', (tries), 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print(\"Geen geldige invoer.\")\n tries -= 1\n print('je verliest een beurt, nog', (tries), 'beurten over')\n\n print(display_hangman(tries))\n print(word_completion)\n print(\"\\n\")\n if guessed:\n print(\"Gefeliciteerd, je hebt het woord geraden! je wint!\")\n else:\n print(\"Sorry, je hebt geen beurten meer. Het woord was \" + word +\n \". Volgende keer beter!\")\n\n\ndef display_hangman(tries):\n stages = [\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | / \\\\\n -\n \"\"\", \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | /\n -\n \"\"\", \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | \n -\n \"\"\", \"\"\"\n --------\n | |\n | O\n | \\\\|\n | |\n | \n -\n \"\"\", \"\"\"\n --------\n | |\n | O\n | |\n | |\n | \n -\n \"\"\", \"\"\"\n --------\n | |\n | O\n | \n | \n | \n -\n \"\"\"\n ]\n return stages[tries]\n\n\ndef main():\n word = get_word()\n play(word)\n while input(\"Nog een keer spelen? (J/N) \").upper() == \"J\":\n word = get_word()\n play(word)\n\n\nif __name__ == \"__main__\":\n main()\n",
"import random\nfrom words import word_list\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = '_' * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print('Laten we galgje spelen!')\n print('De regels:')\n lijst = ['-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.']\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n print('het woord heeft', len(word), 'letters')\n if tries == 5:\n print('je hebt nog 5 beurten over')\n while not guessed and tries > 0:\n guess = input('Typ een letter of een woord:').upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print('Deze letter heb je al geraden.', guess)\n elif guess not in word:\n print(guess, 'zit niet in het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print('Goed bezig,', guess, 'zit in het woord!')\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [i for i, letter in enumerate(word) if letter ==\n guess]\n for index in indices:\n word_as_list[index] = guess\n word_completion = ''.join(word_as_list)\n if '_' not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print('Je hebt het woord al geraden', guess)\n elif guess != word:\n print(guess, 'is niet het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print('Geen geldige invoer.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n if guessed:\n print('Gefeliciteerd, je hebt het woord geraden! je wint!')\n else:\n print('Sorry, je hebt geen beurten meer. Het woord was ' + word +\n '. Volgende keer beter!')\n\n\ndef display_hangman(tries):\n stages = [\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | / \\\\\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | /\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | |\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \n | \n | \n -\n \"\"\"\n ]\n return stages[tries]\n\n\ndef main():\n word = get_word()\n play(word)\n while input('Nog een keer spelen? (J/N) ').upper() == 'J':\n word = get_word()\n play(word)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = '_' * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print('Laten we galgje spelen!')\n print('De regels:')\n lijst = ['-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.']\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n print('het woord heeft', len(word), 'letters')\n if tries == 5:\n print('je hebt nog 5 beurten over')\n while not guessed and tries > 0:\n guess = input('Typ een letter of een woord:').upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print('Deze letter heb je al geraden.', guess)\n elif guess not in word:\n print(guess, 'zit niet in het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print('Goed bezig,', guess, 'zit in het woord!')\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [i for i, letter in enumerate(word) if letter ==\n guess]\n for index in indices:\n word_as_list[index] = guess\n word_completion = ''.join(word_as_list)\n if '_' not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print('Je hebt het woord al geraden', guess)\n elif guess != word:\n print(guess, 'is niet het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print('Geen geldige invoer.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n if guessed:\n print('Gefeliciteerd, je hebt het woord geraden! je wint!')\n else:\n print('Sorry, je hebt geen beurten meer. Het woord was ' + word +\n '. Volgende keer beter!')\n\n\ndef display_hangman(tries):\n stages = [\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | / \\\\\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | /\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | |\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \n | \n | \n -\n \"\"\"\n ]\n return stages[tries]\n\n\ndef main():\n word = get_word()\n play(word)\n while input('Nog een keer spelen? (J/N) ').upper() == 'J':\n word = get_word()\n play(word)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = '_' * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print('Laten we galgje spelen!')\n print('De regels:')\n lijst = ['-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.']\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n print('het woord heeft', len(word), 'letters')\n if tries == 5:\n print('je hebt nog 5 beurten over')\n while not guessed and tries > 0:\n guess = input('Typ een letter of een woord:').upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print('Deze letter heb je al geraden.', guess)\n elif guess not in word:\n print(guess, 'zit niet in het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print('Goed bezig,', guess, 'zit in het woord!')\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [i for i, letter in enumerate(word) if letter ==\n guess]\n for index in indices:\n word_as_list[index] = guess\n word_completion = ''.join(word_as_list)\n if '_' not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print('Je hebt het woord al geraden', guess)\n elif guess != word:\n print(guess, 'is niet het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print('Geen geldige invoer.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n if guessed:\n print('Gefeliciteerd, je hebt het woord geraden! je wint!')\n else:\n print('Sorry, je hebt geen beurten meer. Het woord was ' + word +\n '. Volgende keer beter!')\n\n\ndef display_hangman(tries):\n stages = [\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | / \\\\\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | /\n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|/\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \\\\|\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | |\n | |\n | \n -\n \"\"\"\n ,\n \"\"\"\n --------\n | |\n | O\n | \n | \n | \n -\n \"\"\"\n ]\n return stages[tries]\n\n\ndef main():\n word = get_word()\n play(word)\n while input('Nog een keer spelen? (J/N) ').upper() == 'J':\n word = get_word()\n play(word)\n\n\n<code token>\n",
"<import token>\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = '_' * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print('Laten we galgje spelen!')\n print('De regels:')\n lijst = ['-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.']\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n print('het woord heeft', len(word), 'letters')\n if tries == 5:\n print('je hebt nog 5 beurten over')\n while not guessed and tries > 0:\n guess = input('Typ een letter of een woord:').upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print('Deze letter heb je al geraden.', guess)\n elif guess not in word:\n print(guess, 'zit niet in het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print('Goed bezig,', guess, 'zit in het woord!')\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [i for i, letter in enumerate(word) if letter ==\n guess]\n for index in indices:\n word_as_list[index] = guess\n word_completion = ''.join(word_as_list)\n if '_' not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print('Je hebt het woord al geraden', guess)\n elif guess != word:\n print(guess, 'is niet het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print('Geen geldige invoer.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n if guessed:\n print('Gefeliciteerd, je hebt het woord geraden! je wint!')\n else:\n print('Sorry, je hebt geen beurten meer. Het woord was ' + word +\n '. Volgende keer beter!')\n\n\n<function token>\n\n\ndef main():\n word = get_word()\n play(word)\n while input('Nog een keer spelen? (J/N) ').upper() == 'J':\n word = get_word()\n play(word)\n\n\n<code token>\n",
"<import token>\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\ndef play(word):\n word_completion = '_' * len(word)\n guessed = False\n guessed_letters = []\n guessed_words = []\n tries = 5\n print('Laten we galgje spelen!')\n print('De regels:')\n lijst = ['-na een ingevoerde letter op enter drukken.',\n '-na vijf foute antwoorden ben je af.']\n for item in lijst:\n print(item)\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n print('het woord heeft', len(word), 'letters')\n if tries == 5:\n print('je hebt nog 5 beurten over')\n while not guessed and tries > 0:\n guess = input('Typ een letter of een woord:').upper()\n if len(guess) == 1 and guess.isalpha():\n if guess in guessed_letters:\n print('Deze letter heb je al geraden.', guess)\n elif guess not in word:\n print(guess, 'zit niet in het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print('je hebt de letters', guessed_letters, 'al geprobeerd')\n guessed_letters.append(guess)\n else:\n print('Goed bezig,', guess, 'zit in het woord!')\n guessed_letters.append(guess)\n word_as_list = list(word_completion)\n indices = [i for i, letter in enumerate(word) if letter ==\n guess]\n for index in indices:\n word_as_list[index] = guess\n word_completion = ''.join(word_as_list)\n if '_' not in word_completion:\n guessed = True\n elif len(guess) == len(word) and guess.isalpha():\n if guess in guessed_words:\n print('Je hebt het woord al geraden', guess)\n elif guess != word:\n print(guess, 'is niet het woord.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n guessed_words.append(guess)\n used_letters.append(guess)\n else:\n guessed = True\n word_completion = word\n else:\n print('Geen geldige invoer.')\n tries -= 1\n print('je verliest een beurt, nog', tries, 'beurten over')\n print(display_hangman(tries))\n print(word_completion)\n print('\\n')\n if guessed:\n print('Gefeliciteerd, je hebt het woord geraden! je wint!')\n else:\n print('Sorry, je hebt geen beurten meer. Het woord was ' + word +\n '. Volgende keer beter!')\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n\n\ndef get_word():\n word = random.choice(word_list)\n return word.upper()\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,781 | 9a612c5bff9e9184d0d360f3057305b7a5616b50 | #!/usr/bin/env python
#
# Copyright (C) 2012 W. Trevor King <[email protected]>
#
# This file is part of pycomedi.
#
# pycomedi is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 2 of the License, or (at your option) any later
# version.
#
# pycomedi is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# pycomedi. If not, see <http://www.gnu.org/licenses/>.
"""Output a series of data files using an analog output Comedi subdevice.
"""
import os.path as _os_path
import numpy as _numpy
# from scipy.io import wavfile as _wavfile
try:
import pycomedi.constant
except:
pass
from pycomedi.device import Device as _Device
from pycomedi.subdevice import StreamingSubdevice as _StreamingSubdevice
from pycomedi.channel import AnalogChannel as _AnalogChannel
from pycomedi import constant as _constant
from pycomedi import utility as _utility
NUMPY_FREQ = 5e5
LOADER = { # frequency,raw_signal = LOADER[extension](filename)
'.npy': lambda filename: (NUMPY_FREQ, _numpy.load(filename)),
'.wav':None,
}
def setup_device(filename, subdevice, channels, range, aref):
"""Open the Comedi device at filename and setup analog output channels.
"""
device = _Device(filename=filename)
device.open()
if subdevice is None:
ao_subdevice = device.find_subdevice_by_type(
_constant.SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)
else:
ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)
ao_channels = [
ao_subdevice.channel(i, factory=_AnalogChannel, range=range, aref=aref)
for i in channels]
return (device, ao_subdevice, ao_channels)
def load(filename):
"""Load a date file and return (frequency, unit_output_signal)
Values in unit_output_signal are scaled to the range [-1,1].
"""
root,ext = _os_path.splitext(filename)
loader = LOADER[ext]
frequency,raw_signal = loader(filename)
iinfo = _numpy.iinfo(raw_signal.dtype)
raw_signal_midpoint = (iinfo.max + iinfo.min)/2.
raw_signal_range = iinfo.max - raw_signal_midpoint
unit_output_signal = (raw_signal - raw_signal_midpoint)/raw_signal_range
return (frequency, unit_output_signal)
def generate_output_buffer(ao_subdevice, ao_channels, output_signal):
"""Setup an output buffer from unit_output_signal
The output signal in bits is scaled so that -1 in
unit_output_signal maps to the minimum output voltage for each
channel, and +1 in unit_output_signal maps to the maximum output
voltage for each channel.
"""
ao_dtype = ao_subdevice.get_dtype()
n_samps,n_chans = output_signal.shape
assert n_chans <= len(ao_channels), (
'need at least {0} channels but have only {1}'.format(
n_chans, ao_channels))
ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)
for i in range(n_chans):
range_ = ao_channels[i].range
midpoint = (range_.max + range_.min)/2
v_amp = range_.max - midpoint
v_amp = 1.0
converter = ao_channels[i].get_converter()
unit_output_signal=output_signal[:,i]
unit_output_signal = _numpy.divide(unit_output_signal.astype('float64'),_numpy.max(unit_output_signal))
volt_output_signal = unit_output_signal*v_amp + midpoint
# volt_output_signal[:] = 0
# ao_buffer[:,i] = converter.from_physical(volt_output_signal)
zero = (2**16)/2
unit = int(round(float(2**16)/(2*v_amp)))
# ao_buffer[:,i]=(volt_output_signal*unit+zero).astype(ao_dtype)
ao_buffer[:,i]= converter.from_physical(volt_output_signal)
# for k in range(volt_output_signal.shape[0]):
# print converter.from_physical(volt_output_signal[k])
# ao_buffer[k,i]=converter.from_physical(volt_output_signal[k])
# from matplotlib import pyplot as plt
# import ipdb; ipdb.set_trace()
return ao_buffer
def setup_command(ao_subdevice, ao_channels, frequency, output_buffer):
"""Setup ao_subdevice.cmd to output output_buffer using ao_channels
"""
scan_period_ns = int(1e9 / frequency)
n_chan = output_buffer.shape[1]
ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)
ao_cmd.start_src = _constant.TRIG_SRC.int
ao_cmd.start_arg = 0
ao_cmd.stop_src = _constant.TRIG_SRC.none
ao_cmd.stop_arg = 0
# ao_cmd.stop_src = _constant.TRIG_SRC.count
# ao_cmd.stop_arg = len(output_buffer)
ao_cmd.chanlist = ao_channels[:n_chan]
import ipdb; ipdb.set_trace()
ao_subdevice.cmd = ao_cmd
def run_command(device, ao_subdevice, output_buffer):
"""Write output_buffer using ao_subdevice
Blocks until the output is complete.
"""
ao_subdevice.command()
writer = _utility.Writer(
ao_subdevice, output_buffer,
preload=ao_subdevice.get_buffer_size()/output_buffer.itemsize,
block_while_running=False)
import ipdb; ipdb.set_trace()
writer.start()
device.do_insn(_utility.inttrig_insn(ao_subdevice))
import ipdb; ipdb.set_trace()
writer.join()
def run(filename, subdevice, channels, range, aref, mmap=False, files=[]):
import os
import tempfile
from numpy import arange, iinfo, int16, pi, save, sin, zeros
# Create temporary files for testing.
p = 5
time = arange(p*NUMPY_FREQ, dtype=float)/NUMPY_FREQ
f = 1e3
iint16 = iinfo(int16)
a = (iint16.max - iint16.min)/2.
one_chan = zeros(time.shape, dtype=int16)
one_chan[:] = a*sin(2*pi*f*time)
# fd,one_chan_path = tempfile.mkstemp(prefix='pycomedi-', suffix='.npy')
# fp = os.fdopen(fd, 'w')
# >>> save(fp, one_chan)
# >>> fp.close()
# two_chan = zeros((NUMPY_FREQ,2), dtype=int16)
# two_chan[:,0] = a*sin(f*time/(2*pi))
# two_chan[:,1] = a*sin(2*f*time/(2*pi))
# datadict = {'one_chan': one_chan, 'two_chan': two_chan}
datadict = {'one_chan': one_chan}
# >>> fd,two_chan_path = tempfile.mkstemp(prefix='pycomedi-', suffix='.npy')
# >>> fp = os.fdopen(fd, 'w')
# >>> save(fp, two_chan)
# >>> fp.close()
# >>> run(filename='/dev/comedi0', subdevice=None,
# ... channels=[0,1], range=0, aref=_constant.AREF.ground,
# ... files=[one_chan_path, two_chan_path])
# >>> os.remove(one_chan_path)
# >>> os.remove(two_chan_path)
device,ao_subdevice,ao_channels = setup_device(
filename=filename, subdevice=subdevice, channels=channels,
range=range, aref=aref)
for filename in datadict:
unit_output_signal=datadict[filename]
frequency = NUMPY_FREQ
# frequency,unit_output_signal = load(filename=filename)
if len(unit_output_signal.shape) == 1:
unit_output_signal.shape = (unit_output_signal.shape[0], 1)
output_buffer = generate_output_buffer(
ao_subdevice, ao_channels, unit_output_signal)
setup_command(ao_subdevice, ao_channels, frequency, output_buffer)
run_command(device, ao_subdevice, output_buffer)
device.close()
if __name__ == '__main__':
import pycomedi_demo_args
#
# pycomedi_demo_args.ARGUMENTS['files'] = (['files'], {'nargs': '+'})
# args = pycomedi_demo_args.parse_args(
# description=__doc__,
# argnames=[
# 'filename', 'subdevice', 'channels', 'range', 'aref', 'mmap',
# 'files', 'verbose'])
run(filename='/dev/comedi0', subdevice=1,
channels=[0, 1], range=0, aref=_constant.AREF.ground,
mmap=False)
# import time
# time.sleep(5)
| [
"#!/usr/bin/env python\n#\n# Copyright (C) 2012 W. Trevor King <[email protected]>\n#\n# This file is part of pycomedi.\n#\n# pycomedi is free software: you can redistribute it and/or modify it under the\n# terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 2 of the License, or (at your option) any later\n# version.\n#\n# pycomedi is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# pycomedi. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"Output a series of data files using an analog output Comedi subdevice.\n\"\"\"\n\nimport os.path as _os_path\n\nimport numpy as _numpy\n# from scipy.io import wavfile as _wavfile\ntry:\n import pycomedi.constant\nexcept:\n pass\nfrom pycomedi.device import Device as _Device\nfrom pycomedi.subdevice import StreamingSubdevice as _StreamingSubdevice\nfrom pycomedi.channel import AnalogChannel as _AnalogChannel\nfrom pycomedi import constant as _constant\nfrom pycomedi import utility as _utility\n\n\nNUMPY_FREQ = 5e5\nLOADER = { # frequency,raw_signal = LOADER[extension](filename)\n '.npy': lambda filename: (NUMPY_FREQ, _numpy.load(filename)),\n '.wav':None,\n }\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(\n _constant.SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [\n ao_subdevice.channel(i, factory=_AnalogChannel, range=range, aref=aref)\n for i in channels]\n return (device, ao_subdevice, ao_channels)\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root,ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency,raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min)/2.\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint)/raw_signal_range\n return (frequency, unit_output_signal)\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps,n_chans = output_signal.shape\n assert n_chans <= len(ao_channels), (\n 'need at least {0} channels but have only {1}'.format(\n n_chans, ao_channels))\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min)/2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal=output_signal[:,i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype('float64'),_numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal*v_amp + midpoint\n # volt_output_signal[:] = 0\n # ao_buffer[:,i] = converter.from_physical(volt_output_signal)\n zero = (2**16)/2\n unit = int(round(float(2**16)/(2*v_amp)))\n # ao_buffer[:,i]=(volt_output_signal*unit+zero).astype(ao_dtype)\n ao_buffer[:,i]= converter.from_physical(volt_output_signal)\n\n # for k in range(volt_output_signal.shape[0]):\n # print converter.from_physical(volt_output_signal[k])\n # ao_buffer[k,i]=converter.from_physical(volt_output_signal[k])\n # from matplotlib import pyplot as plt\n # import ipdb; ipdb.set_trace()\n return ao_buffer\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1e9 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n # ao_cmd.stop_src = _constant.TRIG_SRC.count\n # ao_cmd.stop_arg = len(output_buffer)\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb; ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(\n ao_subdevice, output_buffer,\n preload=ao_subdevice.get_buffer_size()/output_buffer.itemsize,\n block_while_running=False)\n import ipdb; ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb; ipdb.set_trace()\n writer.join()\n\ndef run(filename, subdevice, channels, range, aref, mmap=False, files=[]):\n\n import os\n import tempfile\n from numpy import arange, iinfo, int16, pi, save, sin, zeros\n\n # Create temporary files for testing.\n p = 5\n time = arange(p*NUMPY_FREQ, dtype=float)/NUMPY_FREQ\n f = 1e3\n iint16 = iinfo(int16)\n a = (iint16.max - iint16.min)/2.\n one_chan = zeros(time.shape, dtype=int16)\n one_chan[:] = a*sin(2*pi*f*time)\n # fd,one_chan_path = tempfile.mkstemp(prefix='pycomedi-', suffix='.npy')\n # fp = os.fdopen(fd, 'w')\n # >>> save(fp, one_chan)\n # >>> fp.close()\n\n # two_chan = zeros((NUMPY_FREQ,2), dtype=int16)\n # two_chan[:,0] = a*sin(f*time/(2*pi))\n # two_chan[:,1] = a*sin(2*f*time/(2*pi))\n # datadict = {'one_chan': one_chan, 'two_chan': two_chan}\n datadict = {'one_chan': one_chan}\n # >>> fd,two_chan_path = tempfile.mkstemp(prefix='pycomedi-', suffix='.npy')\n # >>> fp = os.fdopen(fd, 'w')\n # >>> save(fp, two_chan)\n # >>> fp.close()\n\n # >>> run(filename='/dev/comedi0', subdevice=None,\n # ... channels=[0,1], range=0, aref=_constant.AREF.ground,\n # ... files=[one_chan_path, two_chan_path])\n\n # >>> os.remove(one_chan_path)\n # >>> os.remove(two_chan_path)\n \n device,ao_subdevice,ao_channels = setup_device(\n filename=filename, subdevice=subdevice, channels=channels,\n range=range, aref=aref)\n\n for filename in datadict:\n unit_output_signal=datadict[filename]\n frequency = NUMPY_FREQ\n # frequency,unit_output_signal = load(filename=filename)\n if len(unit_output_signal.shape) == 1:\n unit_output_signal.shape = (unit_output_signal.shape[0], 1)\n output_buffer = generate_output_buffer(\n ao_subdevice, ao_channels, unit_output_signal)\n setup_command(ao_subdevice, ao_channels, frequency, output_buffer)\n run_command(device, ao_subdevice, output_buffer)\n device.close()\n\n\nif __name__ == '__main__':\n import pycomedi_demo_args\n# \n # pycomedi_demo_args.ARGUMENTS['files'] = (['files'], {'nargs': '+'})\n # args = pycomedi_demo_args.parse_args(\n # description=__doc__,\n # argnames=[\n # 'filename', 'subdevice', 'channels', 'range', 'aref', 'mmap',\n # 'files', 'verbose'])\n\n run(filename='/dev/comedi0', subdevice=1,\n channels=[0, 1], range=0, aref=_constant.AREF.ground,\n mmap=False)\n # import time\n # time.sleep(5)\n",
"<docstring token>\nimport os.path as _os_path\nimport numpy as _numpy\ntry:\n import pycomedi.constant\nexcept:\n pass\nfrom pycomedi.device import Device as _Device\nfrom pycomedi.subdevice import StreamingSubdevice as _StreamingSubdevice\nfrom pycomedi.channel import AnalogChannel as _AnalogChannel\nfrom pycomedi import constant as _constant\nfrom pycomedi import utility as _utility\nNUMPY_FREQ = 500000.0\nLOADER = {'.npy': lambda filename: (NUMPY_FREQ, _numpy.load(filename)),\n '.wav': None}\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps, n_chans = output_signal.shape\n assert n_chans <= len(ao_channels\n ), 'need at least {0} channels but have only {1}'.format(n_chans,\n ao_channels)\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min) / 2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal = output_signal[:, i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype(\n 'float64'), _numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal * v_amp + midpoint\n zero = 2 ** 16 / 2\n unit = int(round(float(2 ** 16) / (2 * v_amp)))\n ao_buffer[:, i] = converter.from_physical(volt_output_signal)\n return ao_buffer\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\ndef run(filename, subdevice, channels, range, aref, mmap=False, files=[]):\n import os\n import tempfile\n from numpy import arange, iinfo, int16, pi, save, sin, zeros\n p = 5\n time = arange(p * NUMPY_FREQ, dtype=float) / NUMPY_FREQ\n f = 1000.0\n iint16 = iinfo(int16)\n a = (iint16.max - iint16.min) / 2.0\n one_chan = zeros(time.shape, dtype=int16)\n one_chan[:] = a * sin(2 * pi * f * time)\n datadict = {'one_chan': one_chan}\n device, ao_subdevice, ao_channels = setup_device(filename=filename,\n subdevice=subdevice, channels=channels, range=range, aref=aref)\n for filename in datadict:\n unit_output_signal = datadict[filename]\n frequency = NUMPY_FREQ\n if len(unit_output_signal.shape) == 1:\n unit_output_signal.shape = unit_output_signal.shape[0], 1\n output_buffer = generate_output_buffer(ao_subdevice, ao_channels,\n unit_output_signal)\n setup_command(ao_subdevice, ao_channels, frequency, output_buffer)\n run_command(device, ao_subdevice, output_buffer)\n device.close()\n\n\nif __name__ == '__main__':\n import pycomedi_demo_args\n run(filename='/dev/comedi0', subdevice=1, channels=[0, 1], range=0,\n aref=_constant.AREF.ground, mmap=False)\n",
"<docstring token>\n<import token>\ntry:\n import pycomedi.constant\nexcept:\n pass\n<import token>\nNUMPY_FREQ = 500000.0\nLOADER = {'.npy': lambda filename: (NUMPY_FREQ, _numpy.load(filename)),\n '.wav': None}\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps, n_chans = output_signal.shape\n assert n_chans <= len(ao_channels\n ), 'need at least {0} channels but have only {1}'.format(n_chans,\n ao_channels)\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min) / 2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal = output_signal[:, i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype(\n 'float64'), _numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal * v_amp + midpoint\n zero = 2 ** 16 / 2\n unit = int(round(float(2 ** 16) / (2 * v_amp)))\n ao_buffer[:, i] = converter.from_physical(volt_output_signal)\n return ao_buffer\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\ndef run(filename, subdevice, channels, range, aref, mmap=False, files=[]):\n import os\n import tempfile\n from numpy import arange, iinfo, int16, pi, save, sin, zeros\n p = 5\n time = arange(p * NUMPY_FREQ, dtype=float) / NUMPY_FREQ\n f = 1000.0\n iint16 = iinfo(int16)\n a = (iint16.max - iint16.min) / 2.0\n one_chan = zeros(time.shape, dtype=int16)\n one_chan[:] = a * sin(2 * pi * f * time)\n datadict = {'one_chan': one_chan}\n device, ao_subdevice, ao_channels = setup_device(filename=filename,\n subdevice=subdevice, channels=channels, range=range, aref=aref)\n for filename in datadict:\n unit_output_signal = datadict[filename]\n frequency = NUMPY_FREQ\n if len(unit_output_signal.shape) == 1:\n unit_output_signal.shape = unit_output_signal.shape[0], 1\n output_buffer = generate_output_buffer(ao_subdevice, ao_channels,\n unit_output_signal)\n setup_command(ao_subdevice, ao_channels, frequency, output_buffer)\n run_command(device, ao_subdevice, output_buffer)\n device.close()\n\n\nif __name__ == '__main__':\n import pycomedi_demo_args\n run(filename='/dev/comedi0', subdevice=1, channels=[0, 1], range=0,\n aref=_constant.AREF.ground, mmap=False)\n",
"<docstring token>\n<import token>\ntry:\n import pycomedi.constant\nexcept:\n pass\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps, n_chans = output_signal.shape\n assert n_chans <= len(ao_channels\n ), 'need at least {0} channels but have only {1}'.format(n_chans,\n ao_channels)\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min) / 2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal = output_signal[:, i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype(\n 'float64'), _numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal * v_amp + midpoint\n zero = 2 ** 16 / 2\n unit = int(round(float(2 ** 16) / (2 * v_amp)))\n ao_buffer[:, i] = converter.from_physical(volt_output_signal)\n return ao_buffer\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\ndef run(filename, subdevice, channels, range, aref, mmap=False, files=[]):\n import os\n import tempfile\n from numpy import arange, iinfo, int16, pi, save, sin, zeros\n p = 5\n time = arange(p * NUMPY_FREQ, dtype=float) / NUMPY_FREQ\n f = 1000.0\n iint16 = iinfo(int16)\n a = (iint16.max - iint16.min) / 2.0\n one_chan = zeros(time.shape, dtype=int16)\n one_chan[:] = a * sin(2 * pi * f * time)\n datadict = {'one_chan': one_chan}\n device, ao_subdevice, ao_channels = setup_device(filename=filename,\n subdevice=subdevice, channels=channels, range=range, aref=aref)\n for filename in datadict:\n unit_output_signal = datadict[filename]\n frequency = NUMPY_FREQ\n if len(unit_output_signal.shape) == 1:\n unit_output_signal.shape = unit_output_signal.shape[0], 1\n output_buffer = generate_output_buffer(ao_subdevice, ao_channels,\n unit_output_signal)\n setup_command(ao_subdevice, ao_channels, frequency, output_buffer)\n run_command(device, ao_subdevice, output_buffer)\n device.close()\n\n\nif __name__ == '__main__':\n import pycomedi_demo_args\n run(filename='/dev/comedi0', subdevice=1, channels=[0, 1], range=0,\n aref=_constant.AREF.ground, mmap=False)\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps, n_chans = output_signal.shape\n assert n_chans <= len(ao_channels\n ), 'need at least {0} channels but have only {1}'.format(n_chans,\n ao_channels)\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min) / 2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal = output_signal[:, i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype(\n 'float64'), _numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal * v_amp + midpoint\n zero = 2 ** 16 / 2\n unit = int(round(float(2 ** 16) / (2 * v_amp)))\n ao_buffer[:, i] = converter.from_physical(volt_output_signal)\n return ao_buffer\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\ndef run(filename, subdevice, channels, range, aref, mmap=False, files=[]):\n import os\n import tempfile\n from numpy import arange, iinfo, int16, pi, save, sin, zeros\n p = 5\n time = arange(p * NUMPY_FREQ, dtype=float) / NUMPY_FREQ\n f = 1000.0\n iint16 = iinfo(int16)\n a = (iint16.max - iint16.min) / 2.0\n one_chan = zeros(time.shape, dtype=int16)\n one_chan[:] = a * sin(2 * pi * f * time)\n datadict = {'one_chan': one_chan}\n device, ao_subdevice, ao_channels = setup_device(filename=filename,\n subdevice=subdevice, channels=channels, range=range, aref=aref)\n for filename in datadict:\n unit_output_signal = datadict[filename]\n frequency = NUMPY_FREQ\n if len(unit_output_signal.shape) == 1:\n unit_output_signal.shape = unit_output_signal.shape[0], 1\n output_buffer = generate_output_buffer(ao_subdevice, ao_channels,\n unit_output_signal)\n setup_command(ao_subdevice, ao_channels, frequency, output_buffer)\n run_command(device, ao_subdevice, output_buffer)\n device.close()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\ndef generate_output_buffer(ao_subdevice, ao_channels, output_signal):\n \"\"\"Setup an output buffer from unit_output_signal\n\n The output signal in bits is scaled so that -1 in\n unit_output_signal maps to the minimum output voltage for each\n channel, and +1 in unit_output_signal maps to the maximum output\n voltage for each channel.\n \"\"\"\n ao_dtype = ao_subdevice.get_dtype()\n n_samps, n_chans = output_signal.shape\n assert n_chans <= len(ao_channels\n ), 'need at least {0} channels but have only {1}'.format(n_chans,\n ao_channels)\n ao_buffer = _numpy.zeros((n_samps, n_chans), dtype=ao_dtype)\n for i in range(n_chans):\n range_ = ao_channels[i].range\n midpoint = (range_.max + range_.min) / 2\n v_amp = range_.max - midpoint\n v_amp = 1.0\n converter = ao_channels[i].get_converter()\n unit_output_signal = output_signal[:, i]\n unit_output_signal = _numpy.divide(unit_output_signal.astype(\n 'float64'), _numpy.max(unit_output_signal))\n volt_output_signal = unit_output_signal * v_amp + midpoint\n zero = 2 ** 16 / 2\n unit = int(round(float(2 ** 16) / (2 * v_amp)))\n ao_buffer[:, i] = converter.from_physical(volt_output_signal)\n return ao_buffer\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\ndef load(filename):\n \"\"\"Load a date file and return (frequency, unit_output_signal)\n\n Values in unit_output_signal are scaled to the range [-1,1].\n \"\"\"\n root, ext = _os_path.splitext(filename)\n loader = LOADER[ext]\n frequency, raw_signal = loader(filename)\n iinfo = _numpy.iinfo(raw_signal.dtype)\n raw_signal_midpoint = (iinfo.max + iinfo.min) / 2.0\n raw_signal_range = iinfo.max - raw_signal_midpoint\n unit_output_signal = (raw_signal - raw_signal_midpoint) / raw_signal_range\n return frequency, unit_output_signal\n\n\n<function token>\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\n<function token>\n<function token>\n\n\ndef setup_command(ao_subdevice, ao_channels, frequency, output_buffer):\n \"\"\"Setup ao_subdevice.cmd to output output_buffer using ao_channels\n \"\"\"\n scan_period_ns = int(1000000000.0 / frequency)\n n_chan = output_buffer.shape[1]\n ao_cmd = ao_subdevice.get_cmd_generic_timed(n_chan, scan_period_ns)\n ao_cmd.start_src = _constant.TRIG_SRC.int\n ao_cmd.start_arg = 0\n ao_cmd.stop_src = _constant.TRIG_SRC.none\n ao_cmd.stop_arg = 0\n ao_cmd.chanlist = ao_channels[:n_chan]\n import ipdb\n ipdb.set_trace()\n ao_subdevice.cmd = ao_cmd\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n\n\ndef setup_device(filename, subdevice, channels, range, aref):\n \"\"\"Open the Comedi device at filename and setup analog output channels.\n \"\"\"\n device = _Device(filename=filename)\n device.open()\n if subdevice is None:\n ao_subdevice = device.find_subdevice_by_type(_constant.\n SUBDEVICE_TYPE.ao, factory=_StreamingSubdevice)\n else:\n ao_subdevice = device.subdevice(subdevice, factory=_StreamingSubdevice)\n ao_channels = [ao_subdevice.channel(i, factory=_AnalogChannel, range=\n range, aref=aref) for i in channels]\n return device, ao_subdevice, ao_channels\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef run_command(device, ao_subdevice, output_buffer):\n \"\"\"Write output_buffer using ao_subdevice\n\n Blocks until the output is complete.\n \"\"\"\n ao_subdevice.command()\n writer = _utility.Writer(ao_subdevice, output_buffer, preload=\n ao_subdevice.get_buffer_size() / output_buffer.itemsize,\n block_while_running=False)\n import ipdb\n ipdb.set_trace()\n writer.start()\n device.do_insn(_utility.inttrig_insn(ao_subdevice))\n import ipdb\n ipdb.set_trace()\n writer.join()\n\n\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,782 | 76f59b8202c5ac63f5a1f500ab57436b19cb950b | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class HindiSongArtist(models.Model):
artist = models.TextField()
artist_type = models.TextField();
def __unicode__(self):
return self.artist
class HindiSongAlbum(models.Model):
album = models.TextField()
album_type = models.TextField();
def __unicode__(self):
return self.album
class HindiSong(models.Model):
song_name = models.TextField()
song_url = models.TextField()
album = models.ForeignKey(HindiSongAlbum,null=True)
artist = models.ManyToManyField(HindiSongArtist)
def __unicode__(self):
return self.song_name
| [
"from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nclass HindiSongArtist(models.Model):\n\tartist = models.TextField()\n\tartist_type = models.TextField(); \n\tdef __unicode__(self):\n\t\treturn self.artist \n\nclass HindiSongAlbum(models.Model):\n\talbum = models.TextField()\n\talbum_type = models.TextField();\n\tdef __unicode__(self):\n\t\treturn self.album \n\nclass HindiSong(models.Model):\n\tsong_name = models.TextField()\n\tsong_url = models.TextField()\n\talbum = models.ForeignKey(HindiSongAlbum,null=True)\n\tartist = models.ManyToManyField(HindiSongArtist)\n\tdef __unicode__(self):\n\t\treturn self.song_name\n",
"from __future__ import unicode_literals\nfrom django.db import models\n\n\nclass HindiSongArtist(models.Model):\n artist = models.TextField()\n artist_type = models.TextField()\n\n def __unicode__(self):\n return self.artist\n\n\nclass HindiSongAlbum(models.Model):\n album = models.TextField()\n album_type = models.TextField()\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n\n\nclass HindiSongArtist(models.Model):\n artist = models.TextField()\n artist_type = models.TextField()\n\n def __unicode__(self):\n return self.artist\n\n\nclass HindiSongAlbum(models.Model):\n album = models.TextField()\n album_type = models.TextField()\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n\n\nclass HindiSongArtist(models.Model):\n <assignment token>\n <assignment token>\n\n def __unicode__(self):\n return self.artist\n\n\nclass HindiSongAlbum(models.Model):\n album = models.TextField()\n album_type = models.TextField()\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n\n\nclass HindiSongArtist(models.Model):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass HindiSongAlbum(models.Model):\n album = models.TextField()\n album_type = models.TextField()\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n\n\nclass HindiSongAlbum(models.Model):\n album = models.TextField()\n album_type = models.TextField()\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n\n\nclass HindiSongAlbum(models.Model):\n <assignment token>\n <assignment token>\n\n def __unicode__(self):\n return self.album\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n\n\nclass HindiSongAlbum(models.Model):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n<class token>\n\n\nclass HindiSong(models.Model):\n song_name = models.TextField()\n song_url = models.TextField()\n album = models.ForeignKey(HindiSongAlbum, null=True)\n artist = models.ManyToManyField(HindiSongArtist)\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n<class token>\n\n\nclass HindiSong(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __unicode__(self):\n return self.song_name\n",
"<import token>\n<class token>\n<class token>\n\n\nclass HindiSong(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,783 | 7a52ef56baa09d96e629e47c05f9e5abc069df61 | from graph import loadGraphml, AttrSpec, aggregateClassAttr
a = loadGraphml('data/teste.graphml', relationAttr='class')
nodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'class', 'class', ['dias'],
['weight'])
b = a.spawnFromClassAttributes(nodeClassAttr='class',edgeClassAttr='class')
for spec in nodeSpecs:
b.addNodeAttrSpec(spec)
for spec in edgeSpecs:
b.addEdgeAttrSpec(spec)
for name, attrDict in nodeAttr.items():
b.setNodeAttrFromDict(name, attrDict)
for name, attrDict in edgeAttr.items():
b.setEdgeAttrFromDict(name, attrDict)
b.writeGraphml('data/b')
a.classifyNodesRegularEquivalence(classAttr='regClass')
nodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'regClass', 'class', ['dias'],
['weight'])
b = a.spawnFromClassAttributes(nodeClassAttr='regClass',edgeClassAttr='class')
for spec in nodeSpecs:
b.addNodeAttrSpec(spec)
for spec in edgeSpecs:
b.addEdgeAttrSpec(spec)
for name, attrDict in nodeAttr.items():
b.setNodeAttrFromDict(name, attrDict)
for name, attrDict in edgeAttr.items():
b.setEdgeAttrFromDict(name, attrDict)
b.writeGraphml('data/c')
| [
"from graph import loadGraphml, AttrSpec, aggregateClassAttr\n\na = loadGraphml('data/teste.graphml', relationAttr='class')\n\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'class', 'class', ['dias'],\n['weight'])\n\nb = a.spawnFromClassAttributes(nodeClassAttr='class',edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\n\nb.writeGraphml('data/b')\n\na.classifyNodesRegularEquivalence(classAttr='regClass')\n\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'regClass', 'class', ['dias'],\n['weight'])\n\nb = a.spawnFromClassAttributes(nodeClassAttr='regClass',edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\n\nb.writeGraphml('data/c')\n",
"from graph import loadGraphml, AttrSpec, aggregateClassAttr\na = loadGraphml('data/teste.graphml', relationAttr='class')\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'class',\n 'class', ['dias'], ['weight'])\nb = a.spawnFromClassAttributes(nodeClassAttr='class', edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/b')\na.classifyNodesRegularEquivalence(classAttr='regClass')\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'regClass',\n 'class', ['dias'], ['weight'])\nb = a.spawnFromClassAttributes(nodeClassAttr='regClass', edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/c')\n",
"<import token>\na = loadGraphml('data/teste.graphml', relationAttr='class')\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'class',\n 'class', ['dias'], ['weight'])\nb = a.spawnFromClassAttributes(nodeClassAttr='class', edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/b')\na.classifyNodesRegularEquivalence(classAttr='regClass')\nnodeAttr, edgeAttr, nodeSpecs, edgeSpecs = aggregateClassAttr(a, 'regClass',\n 'class', ['dias'], ['weight'])\nb = a.spawnFromClassAttributes(nodeClassAttr='regClass', edgeClassAttr='class')\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/c')\n",
"<import token>\n<assignment token>\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/b')\na.classifyNodesRegularEquivalence(classAttr='regClass')\n<assignment token>\nfor spec in nodeSpecs:\n b.addNodeAttrSpec(spec)\nfor spec in edgeSpecs:\n b.addEdgeAttrSpec(spec)\nfor name, attrDict in nodeAttr.items():\n b.setNodeAttrFromDict(name, attrDict)\nfor name, attrDict in edgeAttr.items():\n b.setEdgeAttrFromDict(name, attrDict)\nb.writeGraphml('data/c')\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,784 | 1996360103b0b7a0a14c6a89a59b9ef97cc2b2c1 | #!/usr/bin/env python
# Name: Kimberley Boersma
# Student number: 11003464
"""
This script scrapes IMDB and outputs a CSV file with highest rated movies.
"""
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGET_URL = "https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc"
BACKUP_HTML = 'movies.html'
OUTPUT_CSV = 'movies.csv'
def find_div(html_dom):
movie_div = html_dom.find_all('div', class_ = 'lister-item-content')
return movie_div
def find_title(movie):
title = movie.h3.a.text
return title
def find_rating(movie):
rating = float(movie.strong.text)
return rating
def find_year(movie):
year = movie.h3.find('span', class_ = 'lister-item-year text-muted unbold')
year = year.text.strip('()')
if not year.isdigit():
year = year.split('(')
year = int(year[1])
return year
def find_actors(movie):
actors = movie.select('a[href*="adv_li_st_"]')
actors_movie = []
for actor in actors:
actors_movie.append(actor.text)
actors = (', '.join(actors_movie))
return actors
def find_runtime(movie):
runtime = movie.find('span', class_ = 'runtime')
runtime = runtime.text.strip(' min')
return runtime
def append_movie(title, rating, year, actors, runtime):
movie_list = []
movie_list.append(title)
movie_list.append(rating)
movie_list.append(year)
movie_list.append(actors)
movie_list.append(runtime)
return movie_list
def extract_movies(dom):
"""
Extract a list of highest rated movies from DOM (of IMDB page).
Each movie entry should contain the following fields:
- Title
- Rating
- Year of release (only a number!)
- Actors/actresses (comma separated if more than one)
- Runtime (only a number!)
"""
movie_csv = []
for movie in find_div(dom):
title = find_title(movie)
rating = find_rating(movie)
year = find_year(movie)
actors = find_actors(movie)
runtime = find_runtime(movie)
movie_list = append_movie(title, rating, year, actors, runtime)
movie_csv.append(movie_list)
return movie_csv # REPLACE THIS LINE AS WELL IF APPROPRIsATE
def save_csv(outfile, movies):
"""
Output a CSV file containing highest rated movies.
"""
writer = csv.writer(outfile)
writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])
for movie in movies:
writer.writerow(movie)
# ADD SOME CODE OF YOURSELF HERE TO WRITE THE MOVIES TO DISK
def simple_get(url):
"""
Attempts to get the content at `url` by making an HTTP GET request.
If the content-type of response is some kind of HTML/XML, return the
text content, otherwise return None
"""
try:
with closing(get(url, stream=True)) as resp:
if is_good_response(resp):
return resp.content
else:
return None
except RequestException as e:
print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e)))
return None
def is_good_response(resp):
"""
Returns true if the response seems to be HTML, false otherwise
"""
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('html') > -1)
if __name__ == "__main__":
# get HTML content at target URL
html = simple_get(TARGET_URL)
# save a copy to disk in the current directory, this serves as an backup
# of the original HTML, will be used in grading.
with open(BACKUP_HTML, 'wb') as f:
f.write(html)
# parse the HTML file into a DOM representation
dom = BeautifulSoup(html, 'html.parser')
# extract the movies (using the function you implemented)
movies = extract_movies(dom)
# write the CSV file to disk (including a header)
with open(OUTPUT_CSV, 'w', newline='') as output_file:
save_csv(output_file, movies)
| [
"#!/usr/bin/env python\n# Name: Kimberley Boersma\n# Student number: 11003464\n\"\"\"\nThis script scrapes IMDB and outputs a CSV file with highest rated movies.\n\"\"\"\n\nimport csv\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\n\nTARGET_URL = \"https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc\"\nBACKUP_HTML = 'movies.html'\nOUTPUT_CSV = 'movies.csv'\n\ndef find_div(html_dom):\n movie_div = html_dom.find_all('div', class_ = 'lister-item-content')\n return movie_div\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\ndef find_year(movie):\n year = movie.h3.find('span', class_ = 'lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = (', '.join(actors_movie))\n return actors\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_ = 'runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv # REPLACE THIS LINE AS WELL IF APPROPRIsATE\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n # ADD SOME CODE OF YOURSELF HERE TO WRITE THE MOVIES TO DISK\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)\n\nif __name__ == \"__main__\":\n\n # get HTML content at target URL\n html = simple_get(TARGET_URL)\n\n # save a copy to disk in the current directory, this serves as an backup\n # of the original HTML, will be used in grading.\n with open(BACKUP_HTML, 'wb') as f:\n f.write(html)\n\n # parse the HTML file into a DOM representation\n dom = BeautifulSoup(html, 'html.parser')\n\n # extract the movies (using the function you implemented)\n movies = extract_movies(dom)\n\n # write the CSV file to disk (including a header)\n with open(OUTPUT_CSV, 'w', newline='') as output_file:\n save_csv(output_file, movies)\n",
"<docstring token>\nimport csv\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nTARGET_URL = (\n 'https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc'\n )\nBACKUP_HTML = 'movies.html'\nOUTPUT_CSV = 'movies.csv'\n\n\ndef find_div(html_dom):\n movie_div = html_dom.find_all('div', class_='lister-item-content')\n return movie_div\n\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\nif __name__ == '__main__':\n html = simple_get(TARGET_URL)\n with open(BACKUP_HTML, 'wb') as f:\n f.write(html)\n dom = BeautifulSoup(html, 'html.parser')\n movies = extract_movies(dom)\n with open(OUTPUT_CSV, 'w', newline='') as output_file:\n save_csv(output_file, movies)\n",
"<docstring token>\n<import token>\nTARGET_URL = (\n 'https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc'\n )\nBACKUP_HTML = 'movies.html'\nOUTPUT_CSV = 'movies.csv'\n\n\ndef find_div(html_dom):\n movie_div = html_dom.find_all('div', class_='lister-item-content')\n return movie_div\n\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\nif __name__ == '__main__':\n html = simple_get(TARGET_URL)\n with open(BACKUP_HTML, 'wb') as f:\n f.write(html)\n dom = BeautifulSoup(html, 'html.parser')\n movies = extract_movies(dom)\n with open(OUTPUT_CSV, 'w', newline='') as output_file:\n save_csv(output_file, movies)\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef find_div(html_dom):\n movie_div = html_dom.find_all('div', class_='lister-item-content')\n return movie_div\n\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\nif __name__ == '__main__':\n html = simple_get(TARGET_URL)\n with open(BACKUP_HTML, 'wb') as f:\n f.write(html)\n dom = BeautifulSoup(html, 'html.parser')\n movies = extract_movies(dom)\n with open(OUTPUT_CSV, 'w', newline='') as output_file:\n save_csv(output_file, movies)\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef find_div(html_dom):\n movie_div = html_dom.find_all('div', class_='lister-item-content')\n return movie_div\n\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\ndef find_title(movie):\n title = movie.h3.a.text\n return title\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\ndef save_csv(outfile, movies):\n \"\"\"\n Output a CSV file containing highest rated movies.\n \"\"\"\n writer = csv.writer(outfile)\n writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])\n for movie in movies:\n writer.writerow(movie)\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n except RequestException as e:\n print(\n 'The following error occurred during HTTP GET request to {0} : {1}'\n .format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\ndef find_year(movie):\n year = movie.h3.find('span', class_='lister-item-year text-muted unbold')\n year = year.text.strip('()')\n if not year.isdigit():\n year = year.split('(')\n year = int(year[1])\n return year\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n<function token>\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\n<function token>\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\ndef find_runtime(movie):\n runtime = movie.find('span', class_='runtime')\n runtime = runtime.text.strip(' min')\n return runtime\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n<function token>\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\n<function token>\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\n<function token>\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n<function token>\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns true if the response seems to be HTML, false otherwise\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 and content_type is not None and \n content_type.find('html') > -1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\n<function token>\n\n\ndef find_actors(movie):\n actors = movie.select('a[href*=\"adv_li_st_\"]')\n actors_movie = []\n for actor in actors:\n actors_movie.append(actor.text)\n actors = ', '.join(actors_movie)\n return actors\n\n\n<function token>\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\ndef extract_movies(dom):\n \"\"\"\n Extract a list of highest rated movies from DOM (of IMDB page).\n Each movie entry should contain the following fields:\n - Title\n - Rating\n - Year of release (only a number!)\n - Actors/actresses (comma separated if more than one)\n - Runtime (only a number!)\n \"\"\"\n movie_csv = []\n for movie in find_div(dom):\n title = find_title(movie)\n rating = find_rating(movie)\n year = find_year(movie)\n actors = find_actors(movie)\n runtime = find_runtime(movie)\n movie_list = append_movie(title, rating, year, actors, runtime)\n movie_csv.append(movie_list)\n return movie_csv\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef find_rating(movie):\n rating = float(movie.strong.text)\n return rating\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef append_movie(title, rating, year, actors, runtime):\n movie_list = []\n movie_list.append(title)\n movie_list.append(rating)\n movie_list.append(year)\n movie_list.append(actors)\n movie_list.append(runtime)\n return movie_list\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,785 | 5f07fb926deeeac39241c16a7b9298390e88a93d | # -*- coding: utf-8 -*-
# Copyright (c) 2013 Adrian Taylor
# Inspired by equivalent node.js code by Felix Geisendörfer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Splits a stream of PNGs into individual files.
"""
import Image
import StringIO
import struct
"""
Usage: Call put_data repeatedly. An array of PNG files will be returned each time you call it.
"""
class PNGSplitter(object):
def __init__(self, listener):
self.buffer = ""
self.offset = 0;
self.pngStartOffset = None
self.state = self.handle_header
self.chunk = None
self.listener = listener
"""
Write some data.
"""
def write(self, data):
self.buffer += data
while True:
(found_png, made_progress) = self.state()
if found_png:
self.listener.image_ready(self.buffer[0:self.offset])
self.buffer = self.buffer[self.offset:]
self.offset = 0
self.state = self.handle_header
if not made_progress:
return
def handle_header(self):
self.pngStartOffset = self.offset
if self.fewer_remaining_than(8):
return (False, False)
self.offset += 8
self.state = self.handle_chunk_header
return (False, True)
def handle_chunk_header(self):
if self.fewer_remaining_than(8):
return (False, False)
self.state = self.handle_chunk_data
self.chunk = struct.unpack( ">I4s", self.buffer[self.offset:(self.offset + 8)])
self.offset += 8
return (False, True)
def handle_chunk_data(self):
chunk_size = self.chunk[0] + 4
if self.fewer_remaining_than(chunk_size):
return (False, False)
self.offset += chunk_size
if self.chunk[1] == "IEND":
return (True, True)
else:
self.state = self.handle_chunk_header
return (False, True)
def fewer_remaining_than(self, desired_size):
return len(self.buffer) < self.offset + desired_size
| [
"# -*- coding: utf-8 -*-\n# Copyright (c) 2013 Adrian Taylor\n# Inspired by equivalent node.js code by Felix Geisendörfer\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\n\"\"\"\nSplits a stream of PNGs into individual files.\n\"\"\"\n\nimport Image\nimport StringIO\nimport struct\n\n\"\"\"\nUsage: Call put_data repeatedly. An array of PNG files will be returned each time you call it.\n\"\"\"\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = \"\"\n self.offset = 0;\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n\n \"\"\"\n Write some data.\n \"\"\"\n def write(self, data):\n self.buffer += data\n\n while True:\n (found_png, made_progress) = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:] \n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n\n def handle_header(self):\n self.pngStartOffset = self.offset\n if self.fewer_remaining_than(8):\n return (False, False)\n self.offset += 8\n self.state = self.handle_chunk_header\n return (False, True)\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return (False, False)\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack( \">I4s\", self.buffer[self.offset:(self.offset + 8)])\n self.offset += 8\n return (False, True)\n\n def handle_chunk_data(self):\n chunk_size = self.chunk[0] + 4\n if self.fewer_remaining_than(chunk_size):\n return (False, False)\n self.offset += chunk_size\n if self.chunk[1] == \"IEND\":\n return (True, True)\n else:\n self.state = self.handle_chunk_header\n return (False, True)\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\nimport Image\nimport StringIO\nimport struct\n<docstring token>\n\n\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = ''\n self.offset = 0\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n \"\"\"\n Write some data.\n \"\"\"\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n\n def handle_header(self):\n self.pngStartOffset = self.offset\n if self.fewer_remaining_than(8):\n return False, False\n self.offset += 8\n self.state = self.handle_chunk_header\n return False, True\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n\n def handle_chunk_data(self):\n chunk_size = self.chunk[0] + 4\n if self.fewer_remaining_than(chunk_size):\n return False, False\n self.offset += chunk_size\n if self.chunk[1] == 'IEND':\n return True, True\n else:\n self.state = self.handle_chunk_header\n return False, True\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = ''\n self.offset = 0\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n \"\"\"\n Write some data.\n \"\"\"\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n\n def handle_header(self):\n self.pngStartOffset = self.offset\n if self.fewer_remaining_than(8):\n return False, False\n self.offset += 8\n self.state = self.handle_chunk_header\n return False, True\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n\n def handle_chunk_data(self):\n chunk_size = self.chunk[0] + 4\n if self.fewer_remaining_than(chunk_size):\n return False, False\n self.offset += chunk_size\n if self.chunk[1] == 'IEND':\n return True, True\n else:\n self.state = self.handle_chunk_header\n return False, True\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = ''\n self.offset = 0\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n\n def handle_header(self):\n self.pngStartOffset = self.offset\n if self.fewer_remaining_than(8):\n return False, False\n self.offset += 8\n self.state = self.handle_chunk_header\n return False, True\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n\n def handle_chunk_data(self):\n chunk_size = self.chunk[0] + 4\n if self.fewer_remaining_than(chunk_size):\n return False, False\n self.offset += chunk_size\n if self.chunk[1] == 'IEND':\n return True, True\n else:\n self.state = self.handle_chunk_header\n return False, True\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = ''\n self.offset = 0\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n <function token>\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n\n def handle_chunk_data(self):\n chunk_size = self.chunk[0] + 4\n if self.fewer_remaining_than(chunk_size):\n return False, False\n self.offset += chunk_size\n if self.chunk[1] == 'IEND':\n return True, True\n else:\n self.state = self.handle_chunk_header\n return False, True\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n\n def __init__(self, listener):\n self.buffer = ''\n self.offset = 0\n self.pngStartOffset = None\n self.state = self.handle_header\n self.chunk = None\n self.listener = listener\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n <function token>\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n <function token>\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n <function token>\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n <function token>\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n <function token>\n\n def fewer_remaining_than(self, desired_size):\n return len(self.buffer) < self.offset + desired_size\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n <function token>\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n <function token>\n\n def handle_chunk_header(self):\n if self.fewer_remaining_than(8):\n return False, False\n self.state = self.handle_chunk_data\n self.chunk = struct.unpack('>I4s', self.buffer[self.offset:self.\n offset + 8])\n self.offset += 8\n return False, True\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n <function token>\n <docstring token>\n\n def write(self, data):\n self.buffer += data\n while True:\n found_png, made_progress = self.state()\n if found_png:\n self.listener.image_ready(self.buffer[0:self.offset])\n self.buffer = self.buffer[self.offset:]\n self.offset = 0\n self.state = self.handle_header\n if not made_progress:\n return\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\nclass PNGSplitter(object):\n <function token>\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<docstring token>\n<class token>\n"
] | false |
99,786 | 302f81819110afc02afba428d3ee894c28a3051c | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from operator import itemgetter
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles import finders
from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.module_loading import import_string
from django.utils.text import capfirst
from django.core.checks import Warning
from templateselector.handlers import get_results_from_registry
from templateselector.widgets import TemplateSelector, AdminTemplateSelector
import re
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import MaxLengthValidator
from django.db.models import CharField
from django.forms import TypedChoiceField
from django.template import TemplateDoesNotExist, engines
from django.template.loader import get_template
from django.utils.encoding import force_text
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _
__all__ = ['TemplateField', 'TemplateChoiceField']
def get_templates_from_loaders():
for engine in engines.all():
# I only know how to search the DjangoTemplates yo...
engine = getattr(engine, 'engine')
loaders = engine.template_loaders
for result in get_results_from_registry(loaders):
yield result
def nice_display_name(template_path):
setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})
if template_path in setting.keys():
return setting[template_path]
to_space_re = re.compile(r'[^a-zA-Z0-9\-]+')
name = template_path.rpartition('/')[-1]
basename = name.rpartition('.')[0]
lastpart_spaces = to_space_re.sub(' ', basename)
return capfirst(_(lastpart_spaces))
@deconstructible
class TemplateExistsValidator(object):
__slots__ = ('regex', 'missing_template', 'wrong_pattern', '_constructor_args')
def __init__(self, regex):
self.regex = re.compile(regex)
self.missing_template = _('%(value)s is not a valid template')
self.wrong_pattern = _("%(value)s doesn't match the available template format")
def __call__(self, value):
if not self.regex.match(value):
raise ValidationError(self.wrong_pattern, params={'value': value})
try:
get_template(value)
except TemplateDoesNotExist:
raise ValidationError(self.missing_template, params={'value': value})
class TemplateField(CharField):
def __init__(self, match='^.*$', display_name='templateselector.fields.nice_display_name', *args, **kwargs):
if 'max_length' in kwargs:
raise ImproperlyConfigured(_("max_length is implicitly set to 191 internally"))
kwargs['max_length'] = 191 # in case of using mysql+utf8mb4 & indexing
super(TemplateField, self).__init__(*args, **kwargs)
if not match.startswith('^'):
raise ImproperlyConfigured("Missing required ^ at start")
if not match.endswith('$'):
raise ImproperlyConfigured("Missing required $ at end")
self.match = match
template_exists_validator = TemplateExistsValidator(self.match)
self.validators.append(template_exists_validator)
if isinstance(display_name, six.text_type) and '.' in display_name:
display_name = import_string(display_name)
if not callable(display_name):
raise ImproperlyConfigured(_("display_name= argument must be a callable which takes a single string"))
self.display_name = display_name
def deconstruct(self):
name, path, args, kwargs = super(TemplateField, self).deconstruct()
del kwargs["max_length"]
kwargs['match'] = self.match
kwargs['display_name'] = self.display_name
return name, path, args, kwargs
def formfield(self, **kwargs):
defaults = {
'form_class': TemplateChoiceField,
'match': self.match,
'display_name': self.display_name,
}
defaults.update(kwargs)
return super(TemplateField, self).formfield(**defaults)
def check(self, **kwargs):
errors = []
templates = (
'django/forms/widgets/template_selector.html',
'django/forms/widgets/template_selector_option.html'
)
missing = set()
for t in templates:
try:
get_template('django/forms/widgets/template_selector.html')
except TemplateDoesNotExist:
missing.add(t)
if missing:
msg = "Could not load templates: {}".format(missing)
hint = ("Add 'templateselector' to your INSTALLED_APPS,\n\t "
"OR create the templates yourself,\n\t "
"OR silence this warning and don't use the default TemplateSelector widget")
errors.append(
Warning(msg, hint=hint, obj=self, id='templateselector.W001')
)
css_files = (
'templateselector/widget.css',
'templateselector/admin_widget.css',
)
css_missing = set()
for css in css_files:
css_file = finders.find(css)
if css_file is None:
css_missing.add(css)
if css_missing:
msg = "Could not load staticfiles: {}".format(css_missing)
hint = ("Add 'templateselector' to your INSTALLED_APPS\n\t "
"OR create the file and necessary styles yourself")
errors.append(
Warning(msg, hint=hint, obj=self, id='templateselector.W002')
)
return errors
def contribute_to_class(self, cls, name, **kwargs):
super(TemplateField, self).contribute_to_class(cls, name, **kwargs)
display = curry(self.__get_FIELD_template_display, field=self)
display.short_description = self.verbose_name
display.admin_order_field = name
setattr(cls, 'get_%s_display' % self.name, display)
template_instance = curry(self.__get_FIELD_template_instance, field=self)
setattr(cls, 'get_%s_instance' % self.name, template_instance)
def __get_FIELD_template_display(self, cls, field):
value = getattr(cls, field.attname)
return self.display_name(value)
def __get_FIELD_template_instance(self, cls, field):
value = getattr(cls, field.attname)
return get_template(value)
class TemplateChoiceField(TypedChoiceField):
widget = TemplateSelector
def __init__(self, match='^.*$', display_name='templateselector.fields.nice_display_name', *args, **kwargs):
if 'coerce' in kwargs:
raise ImproperlyConfigured(_("Don't pass a coercion callable"))
kwargs['coerce'] = force_text
max_length = None
if 'max_length' in kwargs:
max_length = kwargs.pop('max_length')
if isinstance(display_name, six.text_type) and '.' in display_name:
display_name = import_string(display_name)
if not callable(display_name):
raise ImproperlyConfigured(_("display_name= argument must be a callable which takes a single string"))
super(TemplateChoiceField, self).__init__(*args, **kwargs)
if not match.startswith('^'):
raise ImproperlyConfigured("Missing required ^ at start")
if not match.endswith('$'):
raise ImproperlyConfigured("Missing required $ at end")
def lazysorted():
def filter_choices(regex_, namecaller_):
match_re = re.compile(regex_)
choices = get_templates_from_loaders()
for choice in choices:
if match_re.match(choice):
name = namecaller_(choice)
yield (choice, name)
results = filter_choices(regex_=match, namecaller_=display_name)
return sorted(set(results), key=itemgetter(1))
self.choices = lazysorted
self.max_length = max_length
if max_length is not None:
self.validators.append(MaxLengthValidator(int(max_length)))
def prepare_value(self, value):
"""
To avoid evaluating the lazysorted callable more than necessary to
establish a potential initial value for the field, we do it here.
If there's
- only one template choice, and
- the field is required, and
- there's no prior initial set (either by being bound or by being set
higher up the stack
then forcibly select the only "good" value as the default.
"""
if value is None and self.required:
choices =list(self.choices)
if len(choices) == 1:
value = choices[0][0]
return super(TemplateChoiceField, self).prepare_value(value)
# It doesn't matter wtf the formfield() method for our custom model field says
# because the admin looks at the MRO for the model field and tries to render
# it as a bloody text input.
admin.options.FORMFIELD_FOR_DBFIELD_DEFAULTS[TemplateField] = {'widget': AdminTemplateSelector}
| [
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, absolute_import\nfrom operator import itemgetter\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.contrib.staticfiles import finders\nfrom django.utils import six\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.module_loading import import_string\nfrom django.utils.text import capfirst\nfrom django.core.checks import Warning\nfrom templateselector.handlers import get_results_from_registry\nfrom templateselector.widgets import TemplateSelector, AdminTemplateSelector\nimport re\nfrom django.core.exceptions import ImproperlyConfigured, ValidationError\nfrom django.core.validators import MaxLengthValidator\nfrom django.db.models import CharField\nfrom django.forms import TypedChoiceField\nfrom django.template import TemplateDoesNotExist, engines\nfrom django.template.loader import get_template\nfrom django.utils.encoding import force_text\nfrom django.utils.functional import curry\nfrom django.utils.translation import ugettext_lazy as _\n\n\n__all__ = ['TemplateField', 'TemplateChoiceField']\n\n\ndef get_templates_from_loaders():\n for engine in engines.all():\n # I only know how to search the DjangoTemplates yo...\n engine = getattr(engine, 'engine')\n loaders = engine.template_loaders\n for result in get_results_from_registry(loaders):\n yield result\n\n\ndef nice_display_name(template_path):\n setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})\n if template_path in setting.keys():\n return setting[template_path]\n to_space_re = re.compile(r'[^a-zA-Z0-9\\-]+')\n name = template_path.rpartition('/')[-1]\n basename = name.rpartition('.')[0]\n lastpart_spaces = to_space_re.sub(' ', basename)\n return capfirst(_(lastpart_spaces))\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern', '_constructor_args')\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value': value})\n\n\nclass TemplateField(CharField):\n def __init__(self, match='^.*$', display_name='templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\"max_length is implicitly set to 191 internally\"))\n kwargs['max_length'] = 191 # in case of using mysql+utf8mb4 & indexing\n super(TemplateField, self).__init__(*args, **kwargs)\n\n if not match.startswith('^'):\n raise ImproperlyConfigured(\"Missing required ^ at start\")\n if not match.endswith('$'):\n raise ImproperlyConfigured(\"Missing required $ at end\")\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\"display_name= argument must be a callable which takes a single string\"))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs[\"max_length\"]\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {\n 'form_class': TemplateChoiceField,\n 'match': self.match,\n 'display_name': self.display_name,\n }\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = (\n 'django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html'\n )\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = \"Could not load templates: {}\".format(missing)\n hint = (\"Add 'templateselector' to your INSTALLED_APPS,\\n\\t \"\n \"OR create the templates yourself,\\n\\t \"\n \"OR silence this warning and don't use the default TemplateSelector widget\")\n errors.append(\n Warning(msg, hint=hint, obj=self, id='templateselector.W001')\n )\n css_files = (\n 'templateselector/widget.css',\n 'templateselector/admin_widget.css',\n )\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = \"Could not load staticfiles: {}\".format(css_missing)\n hint = (\"Add 'templateselector' to your INSTALLED_APPS\\n\\t \"\n \"OR create the file and necessary styles yourself\")\n errors.append(\n Warning(msg, hint=hint, obj=self, id='templateselector.W002')\n )\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field=self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name='templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\"display_name= argument must be a callable which takes a single string\"))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n\n if not match.startswith('^'):\n raise ImproperlyConfigured(\"Missing required ^ at start\")\n if not match.endswith('$'):\n raise ImproperlyConfigured(\"Missing required $ at end\")\n\n def lazysorted():\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield (choice, name)\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices =list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n# It doesn't matter wtf the formfield() method for our custom model field says\n# because the admin looks at the MRO for the model field and tries to render\n# it as a bloody text input.\nadmin.options.FORMFIELD_FOR_DBFIELD_DEFAULTS[TemplateField] = {'widget': AdminTemplateSelector}\n",
"from __future__ import unicode_literals, absolute_import\nfrom operator import itemgetter\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.contrib.staticfiles import finders\nfrom django.utils import six\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.module_loading import import_string\nfrom django.utils.text import capfirst\nfrom django.core.checks import Warning\nfrom templateselector.handlers import get_results_from_registry\nfrom templateselector.widgets import TemplateSelector, AdminTemplateSelector\nimport re\nfrom django.core.exceptions import ImproperlyConfigured, ValidationError\nfrom django.core.validators import MaxLengthValidator\nfrom django.db.models import CharField\nfrom django.forms import TypedChoiceField\nfrom django.template import TemplateDoesNotExist, engines\nfrom django.template.loader import get_template\nfrom django.utils.encoding import force_text\nfrom django.utils.functional import curry\nfrom django.utils.translation import ugettext_lazy as _\n__all__ = ['TemplateField', 'TemplateChoiceField']\n\n\ndef get_templates_from_loaders():\n for engine in engines.all():\n engine = getattr(engine, 'engine')\n loaders = engine.template_loaders\n for result in get_results_from_registry(loaders):\n yield result\n\n\ndef nice_display_name(template_path):\n setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})\n if template_path in setting.keys():\n return setting[template_path]\n to_space_re = re.compile('[^a-zA-Z0-9\\\\-]+')\n name = template_path.rpartition('/')[-1]\n basename = name.rpartition('.')[0]\n lastpart_spaces = to_space_re.sub(' ', basename)\n return capfirst(_(lastpart_spaces))\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern',\n '_constructor_args')\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\nadmin.options.FORMFIELD_FOR_DBFIELD_DEFAULTS[TemplateField] = {'widget':\n AdminTemplateSelector}\n",
"<import token>\n__all__ = ['TemplateField', 'TemplateChoiceField']\n\n\ndef get_templates_from_loaders():\n for engine in engines.all():\n engine = getattr(engine, 'engine')\n loaders = engine.template_loaders\n for result in get_results_from_registry(loaders):\n yield result\n\n\ndef nice_display_name(template_path):\n setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})\n if template_path in setting.keys():\n return setting[template_path]\n to_space_re = re.compile('[^a-zA-Z0-9\\\\-]+')\n name = template_path.rpartition('/')[-1]\n basename = name.rpartition('.')[0]\n lastpart_spaces = to_space_re.sub(' ', basename)\n return capfirst(_(lastpart_spaces))\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern',\n '_constructor_args')\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\nadmin.options.FORMFIELD_FOR_DBFIELD_DEFAULTS[TemplateField] = {'widget':\n AdminTemplateSelector}\n",
"<import token>\n<assignment token>\n\n\ndef get_templates_from_loaders():\n for engine in engines.all():\n engine = getattr(engine, 'engine')\n loaders = engine.template_loaders\n for result in get_results_from_registry(loaders):\n yield result\n\n\ndef nice_display_name(template_path):\n setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})\n if template_path in setting.keys():\n return setting[template_path]\n to_space_re = re.compile('[^a-zA-Z0-9\\\\-]+')\n name = template_path.rpartition('/')[-1]\n basename = name.rpartition('.')[0]\n lastpart_spaces = to_space_re.sub(' ', basename)\n return capfirst(_(lastpart_spaces))\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern',\n '_constructor_args')\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\ndef nice_display_name(template_path):\n setting = getattr(settings, 'TEMPLATESELECTOR_DISPLAY_NAMES', {})\n if template_path in setting.keys():\n return setting[template_path]\n to_space_re = re.compile('[^a-zA-Z0-9\\\\-]+')\n name = template_path.rpartition('/')[-1]\n basename = name.rpartition('.')[0]\n lastpart_spaces = to_space_re.sub(' ', basename)\n return capfirst(_(lastpart_spaces))\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern',\n '_constructor_args')\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n __slots__ = ('regex', 'missing_template', 'wrong_pattern',\n '_constructor_args')\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n <assignment token>\n\n def __init__(self, regex):\n self.regex = re.compile(regex)\n self.missing_template = _('%(value)s is not a valid template')\n self.wrong_pattern = _(\n \"%(value)s doesn't match the available template format\")\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n <assignment token>\n <function token>\n\n def __call__(self, value):\n if not self.regex.match(value):\n raise ValidationError(self.wrong_pattern, params={'value': value})\n try:\n get_template(value)\n except TemplateDoesNotExist:\n raise ValidationError(self.missing_template, params={'value':\n value})\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n\n\n@deconstructible\nclass TemplateExistsValidator(object):\n <assignment token>\n <function token>\n <function token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n\n def contribute_to_class(self, cls, name, **kwargs):\n super(TemplateField, self).contribute_to_class(cls, name, **kwargs)\n display = curry(self.__get_FIELD_template_display, field=self)\n display.short_description = self.verbose_name\n display.admin_order_field = name\n setattr(cls, 'get_%s_display' % self.name, display)\n template_instance = curry(self.__get_FIELD_template_instance, field\n =self)\n setattr(cls, 'get_%s_instance' % self.name, template_instance)\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n\n def check(self, **kwargs):\n errors = []\n templates = ('django/forms/widgets/template_selector.html',\n 'django/forms/widgets/template_selector_option.html')\n missing = set()\n for t in templates:\n try:\n get_template('django/forms/widgets/template_selector.html')\n except TemplateDoesNotExist:\n missing.add(t)\n if missing:\n msg = 'Could not load templates: {}'.format(missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS,\n\t OR create the templates yourself,\n\t OR silence this warning and don't use the default TemplateSelector widget\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W001'))\n css_files = ('templateselector/widget.css',\n 'templateselector/admin_widget.css')\n css_missing = set()\n for css in css_files:\n css_file = finders.find(css)\n if css_file is None:\n css_missing.add(css)\n if css_missing:\n msg = 'Could not load staticfiles: {}'.format(css_missing)\n hint = \"\"\"Add 'templateselector' to your INSTALLED_APPS\n\t OR create the file and necessary styles yourself\"\"\"\n errors.append(Warning(msg, hint=hint, obj=self, id=\n 'templateselector.W002'))\n return errors\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n <function token>\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n\n def __get_FIELD_template_instance(self, cls, field):\n value = getattr(cls, field.attname)\n return get_template(value)\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n\n def deconstruct(self):\n name, path, args, kwargs = super(TemplateField, self).deconstruct()\n del kwargs['max_length']\n kwargs['match'] = self.match\n kwargs['display_name'] = self.display_name\n return name, path, args, kwargs\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n <function token>\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n <function token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n <function token>\n\n def formfield(self, **kwargs):\n defaults = {'form_class': TemplateChoiceField, 'match': self.match,\n 'display_name': self.display_name}\n defaults.update(kwargs)\n return super(TemplateField, self).formfield(**defaults)\n <function token>\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n <function token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'max_length' in kwargs:\n raise ImproperlyConfigured(_(\n 'max_length is implicitly set to 191 internally'))\n kwargs['max_length'] = 191\n super(TemplateField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n self.match = match\n template_exists_validator = TemplateExistsValidator(self.match)\n self.validators.append(template_exists_validator)\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n self.display_name = display_name\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n <function token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __get_FIELD_template_display(self, cls, field):\n value = getattr(cls, field.attname)\n return self.display_name(value)\n <function token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n\n\nclass TemplateField(CharField):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n widget = TemplateSelector\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n <assignment token>\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n\n def prepare_value(self, value):\n \"\"\"\n To avoid evaluating the lazysorted callable more than necessary to\n establish a potential initial value for the field, we do it here.\n\n If there's\n - only one template choice, and\n - the field is required, and\n - there's no prior initial set (either by being bound or by being set\n higher up the stack\n then forcibly select the only \"good\" value as the default.\n \"\"\"\n if value is None and self.required:\n choices = list(self.choices)\n if len(choices) == 1:\n value = choices[0][0]\n return super(TemplateChoiceField, self).prepare_value(value)\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n <assignment token>\n\n def __init__(self, match='^.*$', display_name=\n 'templateselector.fields.nice_display_name', *args, **kwargs):\n if 'coerce' in kwargs:\n raise ImproperlyConfigured(_(\"Don't pass a coercion callable\"))\n kwargs['coerce'] = force_text\n max_length = None\n if 'max_length' in kwargs:\n max_length = kwargs.pop('max_length')\n if isinstance(display_name, six.text_type) and '.' in display_name:\n display_name = import_string(display_name)\n if not callable(display_name):\n raise ImproperlyConfigured(_(\n 'display_name= argument must be a callable which takes a single string'\n ))\n super(TemplateChoiceField, self).__init__(*args, **kwargs)\n if not match.startswith('^'):\n raise ImproperlyConfigured('Missing required ^ at start')\n if not match.endswith('$'):\n raise ImproperlyConfigured('Missing required $ at end')\n\n def lazysorted():\n\n def filter_choices(regex_, namecaller_):\n match_re = re.compile(regex_)\n choices = get_templates_from_loaders()\n for choice in choices:\n if match_re.match(choice):\n name = namecaller_(choice)\n yield choice, name\n results = filter_choices(regex_=match, namecaller_=display_name)\n return sorted(set(results), key=itemgetter(1))\n self.choices = lazysorted\n self.max_length = max_length\n if max_length is not None:\n self.validators.append(MaxLengthValidator(int(max_length)))\n <function token>\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n<class token>\n\n\nclass TemplateChoiceField(TypedChoiceField):\n <assignment token>\n <function token>\n <function token>\n\n\n<assignment token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n"
] | false |
99,787 | fe8285ed80c6c86ff1b4479fac6dbaf3b047dc73 | from __future__ import absolute_import, division, print_function
from builtins import (
bytes, str, open, super, range, zip, round, input, int, pow, object
)
from sqlalchemy import create_engine, MetaData, Table, text
from geoalchemy2 import Geometry
import fiona
import geopandas
try:
import osr
except ImportError:
from osgeo import osr
from gaia.filters import filter_postgis
from gaia.geo.gdal_functions import gdal_reproject
from gaia.util import GaiaException, sqlengines
class GaiaDataObject(object):
def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):
self._data = None
self._metadata = None
self._reader = reader
self._datatype = None
self._dataformat = dataFormat
self._epsg = epsg
def get_metadata(self):
if not self._metadata:
self._reader.load_metadata(self)
return self._metadata
def set_metadata(self, metadata):
self._metadata = metadata
def get_data(self):
if self._data is None:
self._reader.load_data(self)
return self._data
def set_data(self, data):
self._data = data
def get_epsg(self):
return self._epsg
def reproject(self, epsg):
repro = geopandas.GeoDataFrame.copy(self.get_data())
repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)
repro.crs = fiona.crs.from_epsg(epsg)
self._data = repro
self._epsg = epsg
# Recompute bounds
geometry = repro['geometry']
geopandas_bounds = geometry.total_bounds
xmin, ymin, xmax, ymax = geopandas_bounds
coords = [[
[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]
]]
metadata = self.get_metadata()
bounds = metadata.get('bounds', {})
bounds['coordinates'] = coords
metadata['bounds'] = bounds
self.set_metadata(metadata)
def _getdatatype(self):
if not self._datatype:
self.get_metadata()
if not self._datatype:
self._datatype = self._metadata.get('type_', 'unknown')
return self._datatype
def _setdatatype(self, value):
self._datatype = value
datatype = property(_getdatatype, _setdatatype)
def _getdataformat(self):
if not self._dataformat:
self.get_metadata()
return self._dataformat
def _setdataformat(self, value):
self._dataformat = value
dataformat = property(_getdataformat, _setdataformat)
class GDALDataObject(GaiaDataObject):
def __init__(self, reader=None, **kwargs):
super(GDALDataObject, self).__init__(**kwargs)
self._reader = reader
self._epsgComputed = False
def get_epsg(self):
if not self._epsgComputed:
if not self._data:
self.get_data()
projection = self._data.GetProjection()
data_crs = osr.SpatialReference(wkt=projection)
try:
self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))
self._epsgComputed = True
except KeyError:
raise GaiaException("EPSG code coud not be determined")
return self.epsg
def reproject(self, epsg):
self._data = gdal_reproject(self._data, '', epsg=epsg)
self.epsg = epsg
class PostgisDataObject(GaiaDataObject):
def __init__(self, reader=None, **kwargs):
super(PostgisDataObject, self).__init__(**kwargs)
self._reader = reader
self._table = None
self._hostname = None
self._dbname = None
self._user = None
self._password = None
self._columns = []
self._filters = None
self._geom_column = 'the_geom'
self._epsg = None
self._meta = None
self._table_obj = None
# Define table property
def _settable(self, table):
self._table = table
def _gettable(self):
return self._table
table = property(_gettable, _settable)
# Define hostname property
def _sethostname(self, hostname):
self._hostname = hostname
def _gethostname(self):
return self._hostname
hostname = property(_gethostname, _sethostname)
# Define db property
def _setdbname(self, dbname):
self._dbname = dbname
def _getdbname(self):
return self._dbname
dbname = property(_getdbname, _setdbname)
# Define user property
def _setuser(self, user):
self._user = user
def _getuser(self):
return self._user
user = property(_getuser, _setuser)
# Define password property
def _setpassword(self, password):
self._password = password
def _getpassword(self):
return self._password
password = property(_getpassword, _setpassword)
# Define epsg property
def _setepsg(self, epsg):
self._epsg = epsg
def _getepsg(self):
return self._epsg
epsg = property(_getepsg, _setepsg)
# Define filters property
def _setfilters(self, filters):
self._filters = filters
def _getfilters(self):
return self._filters
filters = property(_getfilters, _setfilters)
# Define geom_column property
def _setgeom_column(self, geom_column):
self._geom_column = geom_column
def _getgeom_column(self):
return self._geom_column
geom_column = property(_getgeom_column, _setgeom_column)
# Define engine property
def _setengine(self, engine):
self._engine = engine
def _getengine(self):
return self._engine
engine = property(_getengine, _setengine)
# etc...
def initialize_engine(self):
self._engine = self.get_engine(self.get_connection_string())
self.get_table_info()
self.verify()
# methods additional in PostgisIO
def get_engine(self, connection_string):
"""
Create and return a SQLAlchemy engine object
:param connection_string: Database connection string
:return: SQLAlchemy Engine object
"""
if connection_string not in sqlengines:
sqlengines[connection_string] = create_engine(
self.get_connection_string())
return sqlengines[connection_string]
def verify(self):
"""
Make sure that all PostgisIO columns exist in the actual table
"""
for col in self._columns:
if col not in self._table_obj.columns.keys():
raise GaiaException('{} column not found in {}'.format(
col, self._table_obj))
def get_connection_string(self):
"""
Get connection string based on host, dbname, username, password
:return: Postgres connection string for SQLAlchemy
"""
auth = ''
if self._user:
auth = self._user
if self._password:
auth = auth + ':' + self._password
if auth:
auth += '@'
conn_string = 'postgresql://{auth}{host}/{dbname}'.format(
auth=auth, host=self._hostname, dbname=self._dbname)
return conn_string
def get_epsg(self):
"""
Get the EPSG code of the data
:return: EPSG code
"""
return self._epsg
def get_table_info(self):
"""
Use SQLALchemy reflection to gather data on the table, including the
geometry column, geometry type, and EPSG code, and assign to the
PostgisIO object's attributes.
"""
epsg = None
meta = MetaData()
table_obj = Table(self._table, meta,
autoload=True, autoload_with=self._engine)
if not self._columns:
self._columns = table_obj.columns.keys()
geo_cols = [(col.name, col.type) for col in table_obj.columns
if hasattr(col.type, 'srid')]
if geo_cols:
geo_col = geo_cols[0]
self._geom_column = geo_col[0]
geo_obj = geo_col[1]
if self._geom_column not in self._columns:
self._columns.append(self._geom_column)
if hasattr(geo_obj, 'srid'):
epsg = geo_obj.srid
if epsg == -1:
epsg = 4326
if hasattr(geo_obj, 'geometry_type'):
self._geometry_type = geo_obj.geometry_type
self._epsg = epsg
self._table_obj = table_obj
self._meta = meta
def get_geometry_type(self):
"""
Get the geometry type of the data
:return: Geometry type
"""
return self._geometry_type
def get_query(self):
"""
Formulate a query string and parameter list based on the
table name, columns, and filter
:return: Query string
"""
columns = ','.join(['"{}"'.format(x) for x in self._columns])
query = 'SELECT {} FROM "{}"'.format(columns, self._table)
filter_params = []
if self._filters:
filter_sql, filter_params = filter_postgis(self._filters)
query += ' WHERE {}'.format(filter_sql)
query += ';'
return str(text(query)), filter_params
| [
"from __future__ import absolute_import, division, print_function\nfrom builtins import (\n bytes, str, open, super, range, zip, round, input, int, pow, object\n)\n\nfrom sqlalchemy import create_engine, MetaData, Table, text\nfrom geoalchemy2 import Geometry\nimport fiona\nimport geopandas\ntry:\n import osr\nexcept ImportError:\n from osgeo import osr\n\nfrom gaia.filters import filter_postgis\nfrom gaia.geo.gdal_functions import gdal_reproject\nfrom gaia.util import GaiaException, sqlengines\n\n\nclass GaiaDataObject(object):\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n\n # Recompute bounds\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[\n [xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]\n ]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n\n datatype = property(_getdatatype, _setdatatype)\n\n def _getdataformat(self):\n if not self._dataformat:\n self.get_metadata()\n\n return self._dataformat\n\n def _setdataformat(self, value):\n self._dataformat = value\n\n dataformat = property(_getdataformat, _setdataformat)\n\n\nclass GDALDataObject(GaiaDataObject):\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException(\"EPSG code coud not be determined\")\n\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n\n self._reader = reader\n\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n # Define table property\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n\n table = property(_gettable, _settable)\n\n # Define hostname property\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n\n hostname = property(_gethostname, _sethostname)\n\n # Define db property\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n\n dbname = property(_getdbname, _setdbname)\n\n # Define user property\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n\n user = property(_getuser, _setuser)\n\n # Define password property\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n\n password = property(_getpassword, _setpassword)\n\n # Define epsg property\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n\n epsg = property(_getepsg, _setepsg)\n\n # Define filters property\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n\n filters = property(_getfilters, _setfilters)\n\n # Define geom_column property\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n\n geom_column = property(_getgeom_column, _setgeom_column)\n\n # Define engine property\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n\n engine = property(_getengine, _setengine)\n\n # etc...\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n\n self.get_table_info()\n self.verify()\n\n # methods additional in PostgisIO\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(\n self.get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(\n col, self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(\n auth=auth, host=self._hostname, dbname=self._dbname)\n\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta,\n autoload=True, autoload_with=self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns\n if hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"from __future__ import absolute_import, division, print_function\nfrom builtins import bytes, str, open, super, range, zip, round, input, int, pow, object\nfrom sqlalchemy import create_engine, MetaData, Table, text\nfrom geoalchemy2 import Geometry\nimport fiona\nimport geopandas\ntry:\n import osr\nexcept ImportError:\n from osgeo import osr\nfrom gaia.filters import filter_postgis\nfrom gaia.geo.gdal_functions import gdal_reproject\nfrom gaia.util import GaiaException, sqlengines\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n datatype = property(_getdatatype, _setdatatype)\n\n def _getdataformat(self):\n if not self._dataformat:\n self.get_metadata()\n return self._dataformat\n\n def _setdataformat(self, value):\n self._dataformat = value\n dataformat = property(_getdataformat, _setdataformat)\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\ntry:\n import osr\nexcept ImportError:\n from osgeo import osr\n<import token>\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n datatype = property(_getdatatype, _setdatatype)\n\n def _getdataformat(self):\n if not self._dataformat:\n self.get_metadata()\n return self._dataformat\n\n def _setdataformat(self, value):\n self._dataformat = value\n dataformat = property(_getdataformat, _setdataformat)\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n datatype = property(_getdatatype, _setdatatype)\n\n def _getdataformat(self):\n if not self._dataformat:\n self.get_metadata()\n return self._dataformat\n\n def _setdataformat(self, value):\n self._dataformat = value\n dataformat = property(_getdataformat, _setdataformat)\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n\n def _getdataformat(self):\n if not self._dataformat:\n self.get_metadata()\n return self._dataformat\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def get_epsg(self):\n return self._epsg\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n\n def __init__(self, reader=None, dataFormat=None, epsg=None, **kwargs):\n self._data = None\n self._metadata = None\n self._reader = reader\n self._datatype = None\n self._dataformat = dataFormat\n self._epsg = epsg\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n\n def get_metadata(self):\n if not self._metadata:\n self._reader.load_metadata(self)\n return self._metadata\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n\n def set_data(self, data):\n self._data = data\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n\n def _setdatatype(self, value):\n self._datatype = value\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n <function token>\n <assignment token>\n <function token>\n\n def _setdataformat(self, value):\n self._dataformat = value\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n\n def set_metadata(self, metadata):\n self._metadata = metadata\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n <function token>\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n\n def _getdatatype(self):\n if not self._datatype:\n self.get_metadata()\n if not self._datatype:\n self._datatype = self._metadata.get('type_', 'unknown')\n return self._datatype\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n <function token>\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n\n def reproject(self, epsg):\n repro = geopandas.GeoDataFrame.copy(self.get_data())\n repro[repro.geometry.name] = repro.geometry.to_crs(epsg=epsg)\n repro.crs = fiona.crs.from_epsg(epsg)\n self._data = repro\n self._epsg = epsg\n geometry = repro['geometry']\n geopandas_bounds = geometry.total_bounds\n xmin, ymin, xmax, ymax = geopandas_bounds\n coords = [[[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]]\n metadata = self.get_metadata()\n bounds = metadata.get('bounds', {})\n bounds['coordinates'] = coords\n metadata['bounds'] = bounds\n self.set_metadata(metadata)\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n <function token>\n\n def get_data(self):\n if self._data is None:\n self._reader.load_data(self)\n return self._data\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n\n\nclass GaiaDataObject(object):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n\n def get_epsg(self):\n if not self._epsgComputed:\n if not self._data:\n self.get_data()\n projection = self._data.GetProjection()\n data_crs = osr.SpatialReference(wkt=projection)\n try:\n self.epsg = int(data_crs.GetAttrValue('AUTHORITY', 1))\n self._epsgComputed = True\n except KeyError:\n raise GaiaException('EPSG code coud not be determined')\n return self.epsg\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n <function token>\n\n def reproject(self, epsg):\n self._data = gdal_reproject(self._data, '', epsg=epsg)\n self.epsg = epsg\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n\n\nclass GDALDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(GDALDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._epsgComputed = False\n <function token>\n <function token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n\n\nclass GDALDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n table = property(_gettable, _settable)\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n hostname = property(_gethostname, _sethostname)\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n dbname = property(_getdbname, _setdbname)\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n user = property(_getuser, _setuser)\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n password = property(_getpassword, _setpassword)\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n epsg = property(_getepsg, _setepsg)\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n filters = property(_getfilters, _setfilters)\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n geom_column = property(_getgeom_column, _setgeom_column)\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n engine = property(_getengine, _setengine)\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n\n def initialize_engine(self):\n self._engine = self.get_engine(self.get_connection_string())\n self.get_table_info()\n self.verify()\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n\n def _getuser(self):\n return self._user\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n\n def _gettable(self):\n return self._table\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n\n def get_query(self):\n \"\"\"\n Formulate a query string and parameter list based on the\n table name, columns, and filter\n\n :return: Query string\n \"\"\"\n columns = ','.join(['\"{}\"'.format(x) for x in self._columns])\n query = 'SELECT {} FROM \"{}\"'.format(columns, self._table)\n filter_params = []\n if self._filters:\n filter_sql, filter_params = filter_postgis(self._filters)\n query += ' WHERE {}'.format(filter_sql)\n query += ';'\n return str(text(query)), filter_params\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n\n def _getdbname(self):\n return self._dbname\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n\n def _getepsg(self):\n return self._epsg\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n\n def _getengine(self):\n return self._engine\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n\n def get_engine(self, connection_string):\n \"\"\"\n Create and return a SQLAlchemy engine object\n\n :param connection_string: Database connection string\n :return: SQLAlchemy Engine object\n \"\"\"\n if connection_string not in sqlengines:\n sqlengines[connection_string] = create_engine(self.\n get_connection_string())\n return sqlengines[connection_string]\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n\n def _sethostname(self, hostname):\n self._hostname = hostname\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n\n def _settable(self, table):\n self._table = table\n <function token>\n <assignment token>\n <function token>\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _gethostname(self):\n return self._hostname\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n\n def _setuser(self, user):\n self._user = user\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n\n def _setepsg(self, epsg):\n self._epsg = epsg\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n\n def _setgeom_column(self, geom_column):\n self._geom_column = geom_column\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setpassword(self, password):\n self._password = password\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n\n def get_geometry_type(self):\n \"\"\"\n Get the geometry type of the data\n\n :return: Geometry type\n \"\"\"\n return self._geometry_type\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n\n def _setengine(self, engine):\n self._engine = engine\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n\n def verify(self):\n \"\"\"\n Make sure that all PostgisIO columns exist in the actual table\n \"\"\"\n for col in self._columns:\n if col not in self._table_obj.columns.keys():\n raise GaiaException('{} column not found in {}'.format(col,\n self._table_obj))\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _getpassword(self):\n return self._password\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n\n def __init__(self, reader=None, **kwargs):\n super(PostgisDataObject, self).__init__(**kwargs)\n self._reader = reader\n self._table = None\n self._hostname = None\n self._dbname = None\n self._user = None\n self._password = None\n self._columns = []\n self._filters = None\n self._geom_column = 'the_geom'\n self._epsg = None\n self._meta = None\n self._table_obj = None\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n\n def _getgeom_column(self):\n return self._geom_column\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n\n def get_table_info(self):\n \"\"\"\n Use SQLALchemy reflection to gather data on the table, including the\n geometry column, geometry type, and EPSG code, and assign to the\n PostgisIO object's attributes.\n \"\"\"\n epsg = None\n meta = MetaData()\n table_obj = Table(self._table, meta, autoload=True, autoload_with=\n self._engine)\n if not self._columns:\n self._columns = table_obj.columns.keys()\n geo_cols = [(col.name, col.type) for col in table_obj.columns if\n hasattr(col.type, 'srid')]\n if geo_cols:\n geo_col = geo_cols[0]\n self._geom_column = geo_col[0]\n geo_obj = geo_col[1]\n if self._geom_column not in self._columns:\n self._columns.append(self._geom_column)\n if hasattr(geo_obj, 'srid'):\n epsg = geo_obj.srid\n if epsg == -1:\n epsg = 4326\n if hasattr(geo_obj, 'geometry_type'):\n self._geometry_type = geo_obj.geometry_type\n self._epsg = epsg\n self._table_obj = table_obj\n self._meta = meta\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setfilters(self, filters):\n self._filters = filters\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n def _getfilters(self):\n return self._filters\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n\n def _setdbname(self, dbname):\n self._dbname = dbname\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n\n def get_epsg(self):\n \"\"\"\n Get the EPSG code of the data\n\n :return: EPSG code\n \"\"\"\n return self._epsg\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def get_connection_string(self):\n \"\"\"\n Get connection string based on host, dbname, username, password\n\n :return: Postgres connection string for SQLAlchemy\n \"\"\"\n auth = ''\n if self._user:\n auth = self._user\n if self._password:\n auth = auth + ':' + self._password\n if auth:\n auth += '@'\n conn_string = 'postgresql://{auth}{host}/{dbname}'.format(auth=auth,\n host=self._hostname, dbname=self._dbname)\n return conn_string\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n\n\nclass PostgisDataObject(GaiaDataObject):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<import token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,788 | 3d8c1c21ae849a0999099ef26b9b0e8b64e000e9 | lista = []
par = []
impar = []
while True:
n = int(input('Digite um valor:'))
lista.append(n)
p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]
while p not in 'NS':
p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]
if p == 'N':
break
for n in lista:
if n % 2 == 0:
par.append(n)
if n % 2 != 0:
impar.append(n)
print(f'Os valores digitados foram {lista}')
print(f'Os valores pares digitados foram {par}')
print(f'Os valores impares digitados foram {impar}')
| [
"lista = []\npar = []\nimpar = []\nwhile True:\n n = int(input('Digite um valor:'))\n lista.append(n)\n p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]\n while p not in 'NS':\n p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]\n if p == 'N':\n break\nfor n in lista:\n if n % 2 == 0:\n par.append(n)\n if n % 2 != 0:\n impar.append(n)\nprint(f'Os valores digitados foram {lista}')\nprint(f'Os valores pares digitados foram {par}')\nprint(f'Os valores impares digitados foram {impar}')\n",
"<assignment token>\nwhile True:\n n = int(input('Digite um valor:'))\n lista.append(n)\n p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]\n while p not in 'NS':\n p = str(input('Quer continuar?: [S/N]')).strip().upper()[0]\n if p == 'N':\n break\nfor n in lista:\n if n % 2 == 0:\n par.append(n)\n if n % 2 != 0:\n impar.append(n)\nprint(f'Os valores digitados foram {lista}')\nprint(f'Os valores pares digitados foram {par}')\nprint(f'Os valores impares digitados foram {impar}')\n",
"<assignment token>\n<code token>\n"
] | false |
99,789 | acefb6db2f95b0dcc5da1d266dc5f867aa2fdc4f |
# Useful name for output columns
NUM_VEHICLE = "number_vehilce"
TOTAL_DISTANCE = "total_distance"
DIST_PER_VEHICLE = "dist_per_vehi"
INPUT_FILE = "input_file"
STOPS_PER_VEHICLE = "stops_per_vehicle"
ALL_STOPS_ID = "all_stops_ID"
CLUSTERING_METHOD = "clustering_method"
CAPACITY_CST = "capacity_cst"
TIME_CST = "time_cst"
# Usefule names for features
DEMAND = "demand"
NB_STOPS = "number_stops"
NB_STOPS_BEFORE = "number_stops_due_"
DISTANCE = "distance"
DEPOT = "depot"
OVERALP = "overlap"
DIAMETER = "diameter"
DENSE = "dense"
SPARSE = "sparse"
TSP = "TSP"
| [
"\n# Useful name for output columns\nNUM_VEHICLE = \"number_vehilce\"\nTOTAL_DISTANCE = \"total_distance\"\nDIST_PER_VEHICLE = \"dist_per_vehi\"\nINPUT_FILE = \"input_file\"\nSTOPS_PER_VEHICLE = \"stops_per_vehicle\"\nALL_STOPS_ID = \"all_stops_ID\"\n\nCLUSTERING_METHOD = \"clustering_method\"\n\nCAPACITY_CST = \"capacity_cst\"\nTIME_CST = \"time_cst\"\n\n\n\n# Usefule names for features\nDEMAND = \"demand\"\nNB_STOPS = \"number_stops\"\nNB_STOPS_BEFORE = \"number_stops_due_\"\nDISTANCE = \"distance\"\nDEPOT = \"depot\"\nOVERALP = \"overlap\"\nDIAMETER = \"diameter\"\nDENSE = \"dense\"\nSPARSE = \"sparse\"\nTSP = \"TSP\"\n\n\n",
"NUM_VEHICLE = 'number_vehilce'\nTOTAL_DISTANCE = 'total_distance'\nDIST_PER_VEHICLE = 'dist_per_vehi'\nINPUT_FILE = 'input_file'\nSTOPS_PER_VEHICLE = 'stops_per_vehicle'\nALL_STOPS_ID = 'all_stops_ID'\nCLUSTERING_METHOD = 'clustering_method'\nCAPACITY_CST = 'capacity_cst'\nTIME_CST = 'time_cst'\nDEMAND = 'demand'\nNB_STOPS = 'number_stops'\nNB_STOPS_BEFORE = 'number_stops_due_'\nDISTANCE = 'distance'\nDEPOT = 'depot'\nOVERALP = 'overlap'\nDIAMETER = 'diameter'\nDENSE = 'dense'\nSPARSE = 'sparse'\nTSP = 'TSP'\n",
"<assignment token>\n"
] | false |
99,790 | 20ac1f57b384a38b26419acb62690117af01f45d | import logging
import sys
from rtree import index
from api.models import Address, Building
from commands.util import Timer
EPSILON = 0.000001
logger = logging.Logger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
def generate_buildings(region):
for b in Building.all(region):
minx, miny, maxx, maxy = b.bbox
yield (b.idx, (minx, miny, maxx, maxy), b)
def generate_addresses(region):
for a in Address.all(region):
minx, miny = a.center
yield(a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a)
if __name__ == "__main__":
region = sys.argv[1]
with Timer("Generating index from buildings"):
b_rtree = index.Index(f"buildings_{region}_rtree", generate_buildings(region))
with Timer("Generating index from addresses"):
a_rtree = index.Index(f"addresses_{region}_rtree", generate_addresses(region))
| [
"import logging\nimport sys\n\nfrom rtree import index\n\nfrom api.models import Address, Building\nfrom commands.util import Timer\n\nEPSILON = 0.000001\n\nlogger = logging.Logger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield (b.idx, (minx, miny, maxx, maxy), b)\n\ndef generate_addresses(region):\n for a in Address.all(region):\n minx, miny = a.center\n yield(a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a)\n\nif __name__ == \"__main__\":\n region = sys.argv[1]\n with Timer(\"Generating index from buildings\"):\n b_rtree = index.Index(f\"buildings_{region}_rtree\", generate_buildings(region))\n with Timer(\"Generating index from addresses\"):\n a_rtree = index.Index(f\"addresses_{region}_rtree\", generate_addresses(region))\n",
"import logging\nimport sys\nfrom rtree import index\nfrom api.models import Address, Building\nfrom commands.util import Timer\nEPSILON = 1e-06\nlogger = logging.Logger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield b.idx, (minx, miny, maxx, maxy), b\n\n\ndef generate_addresses(region):\n for a in Address.all(region):\n minx, miny = a.center\n yield a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a\n\n\nif __name__ == '__main__':\n region = sys.argv[1]\n with Timer('Generating index from buildings'):\n b_rtree = index.Index(f'buildings_{region}_rtree',\n generate_buildings(region))\n with Timer('Generating index from addresses'):\n a_rtree = index.Index(f'addresses_{region}_rtree',\n generate_addresses(region))\n",
"<import token>\nEPSILON = 1e-06\nlogger = logging.Logger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield b.idx, (minx, miny, maxx, maxy), b\n\n\ndef generate_addresses(region):\n for a in Address.all(region):\n minx, miny = a.center\n yield a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a\n\n\nif __name__ == '__main__':\n region = sys.argv[1]\n with Timer('Generating index from buildings'):\n b_rtree = index.Index(f'buildings_{region}_rtree',\n generate_buildings(region))\n with Timer('Generating index from addresses'):\n a_rtree = index.Index(f'addresses_{region}_rtree',\n generate_addresses(region))\n",
"<import token>\n<assignment token>\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield b.idx, (minx, miny, maxx, maxy), b\n\n\ndef generate_addresses(region):\n for a in Address.all(region):\n minx, miny = a.center\n yield a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a\n\n\nif __name__ == '__main__':\n region = sys.argv[1]\n with Timer('Generating index from buildings'):\n b_rtree = index.Index(f'buildings_{region}_rtree',\n generate_buildings(region))\n with Timer('Generating index from addresses'):\n a_rtree = index.Index(f'addresses_{region}_rtree',\n generate_addresses(region))\n",
"<import token>\n<assignment token>\n<code token>\n\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield b.idx, (minx, miny, maxx, maxy), b\n\n\ndef generate_addresses(region):\n for a in Address.all(region):\n minx, miny = a.center\n yield a.idx, (minx, miny, minx + EPSILON, miny + EPSILON), a\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n\n\ndef generate_buildings(region):\n for b in Building.all(region):\n minx, miny, maxx, maxy = b.bbox\n yield b.idx, (minx, miny, maxx, maxy), b\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,791 | c29f585ee97592ac4dd279d90eb2b9d6f4ad2f80 | #!/usr/bin/python3
# test_square.py
# Carlos Barros <[email protected]>
"""Defines unittests for square.py."""
import unittest
import io
import sys
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class TestSquare_instantiation(unittest.TestCase):
"""Unittests for testing instantiation of the Square class."""
def test_is_base(self):
self.assertIsInstance(Square(10), Base)
def test_is_rectangle(self):
self.assertIsInstance(Square(4), Rectangle)
def test_no_args(self):
with self.assertRaises(TypeError):
Square()
def test_3_values(self):
s1 = Square(1, 2)
s2 = Square(2, 7)
s3 = Square(10, 2, 16)
self.assertEqual(s1.id, s3.id - 2)
def test_4_values(self):
s1 = Square(1, 2)
s2 = Square(2, 7)
s3 = Square(10, 2, 16)
s4 = Square(6, 4, 54)
self.assertEqual(s1.id, s4.id - 3)
def test_one_line(self):
self.assertEqual(4, Square(1, 2, 6, 4).id)
def test_id_str(self):
self.assertEqual("Holberton", Square(1, 2, 6, "Holberton").id)
def test_size_getter(self):
self.assertEqual(6, Square(6, 2, 3, 9).size)
def test_size_getter_1(self):
s = Square(6, 2, 3, 9)
s.update(size=43)
self.assertEqual(43, s.size)
def test_x_getter(self):
self.assertEqual(2, Square(6, 2, 3, 9).x)
def test_x_getter_1(self):
s = Square(6, 2, 3, 9)
s.update(x=23)
self.assertEqual(23, s.x)
def test_y_getter(self):
self.assertEqual(3, Square(6, 2, 3, 9).y)
def test_y_getter_1(self):
s = Square(6, 2, 3, 9)
s.update(y=57)
self.assertEqual(57, s.y)
def test_zero_x_y(self):
s = Square(1)
self.assertTrue(s.y == 0 and s.x == 0)
def test_zero_x_y(self):
s = Square(1, 5, 6, 0)
self.assertTrue(s.y == 6 and s.x == 5 and
s.id == 0 and s.size == 1)
def test_zero_x_y(self):
s = Square(75, 54, 32, -52)
self.assertTrue(s.id == -52)
def test_update_all(self):
s = Square(6, 2, 3, 9)
s.update(y=57, id=4, x=79, size=76)
self.assertTrue(s.x == 79 and s.id == 4 and
s.y == 57 and s.size == 76)
def test_none_size(self):
with self.assertRaises(TypeError):
Square(None, 2)
def test_y_id(self):
with self.assertRaises(TypeError):
Square(10, 2, "Hello", 5)
def test_float_all(self):
with self.assertRaises(TypeError):
Square(3.0, 5.0, 4.0, 62.0)
def test_six_arg(self):
with self.assertRaises(TypeError):
Square(10, 2, 16, 4, 4, "Holberton")
class TestSquare_size(unittest.TestCase):
"""Unittests for testing instantiation of the Square size attribute."""
def test_size_none(self):
with self.assertRaises(TypeError):
Square(None)
def test_size_none_2(self):
with self.assertRaises(TypeError):
Square(None, 6, 7)
def test_size_float(self):
with self.assertRaises(TypeError):
Square(5.0, 32, 63, 554.0)
def test_size_n(self):
with self.assertRaises(ValueError):
Square(-75, 52, 53, 543)
def test_size_string(self):
with self.assertRaises(TypeError):
Square("Hello", 52, 53, 543)
def test_size_zero(self):
with self.assertRaises(ValueError):
Square(0, 52, 53, 543)
def test_size_float_inf(self):
with self.assertRaises(TypeError):
Square(float('inf'), 52, 53, 543)
def test_size_float_nan(self):
with self.assertRaises(TypeError):
Square(float('nan'), 52, 53, 543)
def test_size_complex(self):
with self.assertRaises(TypeError):
Square(complex(5), 52, 53, 543)
class TestSquare_x(unittest.TestCase):
"""Unittests for testing instantiation of the Square x attribute."""
def test_x_none(self):
with self.assertRaises(TypeError):
Square(x=None)
def test_x_none_2(self):
with self.assertRaises(TypeError):
Square(4, None, 7)
def test_x_float(self):
with self.assertRaises(TypeError):
Square(5, 32.43, 63)
def test_x_n(self):
with self.assertRaises(ValueError):
Square(75, -52, 53, 543)
def test_x_string(self):
with self.assertRaises(TypeError):
Square(4, "Betty", 53, 543)
def test_x_float_inf(self):
with self.assertRaises(TypeError):
Square(4, float('inf'), 53, 543)
def test_x_float_nan(self):
with self.assertRaises(TypeError):
Square(97, float('nan'), 53, 543)
def test_x_complex(self):
with self.assertRaises(TypeError):
Square(5, complex(5), 53, 543)
class TestSquare_y(unittest.TestCase):
"""Unittests for testing instantiation of the Square y attribute."""
def test_y_none(self):
with self.assertRaises(TypeError):
Square(y=None)
def test_y_none_2(self):
with self.assertRaises(TypeError):
Square(4, 5, None, 7)
def test_y_float(self):
with self.assertRaises(TypeError):
Square(5, 4, 32.43, 4)
def test_y_n(self):
with self.assertRaises(ValueError):
Square(75, 54, -52, 543)
def test_y_string(self):
with self.assertRaises(TypeError):
Square(4, 6, "Betty", 543)
def test_y_float_inf(self):
with self.assertRaises(TypeError):
Square(4, 36, float('inf'), 543)
def test_y_float_nan(self):
with self.assertRaises(TypeError):
Square(97, 51, float('nan'), 543)
def test_y_complex(self):
with self.assertRaises(TypeError):
Square(5, 75, complex(5), 543)
class TestSquare_id(unittest.TestCase):
"""Unittests for testing instantiation of the Square id attribute."""
def test_id_none(self):
with self.assertRaises(TypeError):
Square(id=None)
def test_id_float(self):
s = Square(5, 4, 5, 32.43)
self.assertEqual(32.43, s.id)
def test_id_n(self):
s = Square(75, 54, 32, -52)
self.assertEqual(-52, s.id)
def test_id_float_inf(self):
s = Square(4, 36, 434, float('inf'))
self.assertEqual(float('inf'), s.id)
def test_id_complex(self):
s = Square(5, 75, 434, complex(5))
self.assertEqual(complex(5), s.id)
class TestSquare_order_of_initialization(unittest.TestCase):
"""Unittests for testing order of Square attribute initialization."""
def test_size_before_x(self):
with self.assertRaisesRegex(TypeError, "width must be an integer"):
Square("invalid size", "invalid x")
def test_size_before_y(self):
with self.assertRaisesRegex(TypeError, "width must be an integer"):
Square("invalid size", 1, "invalid y")
def test_x_before_y(self):
with self.assertRaisesRegex(TypeError, "x must be an integer"):
Square(1, "invalid x", "invalid y")
class TestSquare_area(unittest.TestCase):
"""Unittests for testing the area method of the Square class."""
def test_area_small(self):
self.assertEqual(100, Square(10, 0, 0, 1).area())
def test_area_large(self):
s = Square(999999999999999999, 0, 0, 1)
self.assertEqual(999999999999999998000000000000000001, s.area())
def test_area_changed_attributes(self):
s = Square(2, 0, 0, 1)
s.size = 7
self.assertEqual(49, s.area())
def test_area_changed_number_n(self):
s = Square(2, 0, 0, 1)
with self.assertRaises(TypeError):
s.area(None, 5)
def test_area_one_arg(self):
s = Square(2, 10, 1, 1)
with self.assertRaises(TypeError):
s.area(1)
def test_area_one_complex_arg(self):
s = Square(2, 10, 1, 1)
with self.assertRaises(TypeError):
s.area(1, complex(5))
def test_area_one_complex_arg_2(self):
s = Square(2, 10, 1, 1)
with self.assertRaises(TypeError):
s.area(complex(41), 5)
def test_area_one_complex_arg_2(self):
s = Square(2, 10, 1, 1)
with self.assertRaises(TypeError):
s.area(4, "Holberton")
class TestSquare_stdout(unittest.TestCase):
"""Unittests for testing __str__ and display methods of Square class."""
@staticmethod
def capture_stdout(sq, method):
"""Captures and returns text printed to stdout.
Args:
sq (Square): The Square ot print to stdout.
method (str): The method to run on sq.
Returns:
The text printed to stdout by calling method on sq.
"""
capture = io.StringIO()
sys.stdout = capture
if method == "print":
print(sq)
else:
sq.display()
sys.stdout = sys.__stdout__
return capture
def test_print_size(self):
s = Square(4)
capture = TestSquare_stdout.capture_stdout(s, "print")
correct = "[Square] ({}) 0/0 - 4\n".format(s.id)
self.assertEqual(correct, capture.getvalue())
def test_size_x(self):
s = Square(5, 43)
correct = "[Square] ({}) 43/0 - 5".format(s.id)
self.assertEqual(correct, s.__str__())
def test_size_x_y(self):
s = Square(7, 4, 22)
correct = "[Square] ({}) 4/22 - 7".format(s.id)
self.assertEqual(correct, str(s))
def test_size_x_y_id(self):
s = Square(2, 88, 4, 19)
self.assertEqual("[Square] (19) 88/4 - 2", str(s))
def test_changed_attributes(self):
s = Square(7, 5, 34, [4])
s.size = 15
s.x = 8
s.y = 10
self.assertEqual("[Square] ([4]) 8/10 - 15", str(s))
def test_str_method_one_arg(self):
s = Square(1, 2, 3, 4)
with self.assertRaises(TypeError):
s.__str__(1)
# Test display method
def test_display_size(self):
s = Square(2, 2, 0, 53)
capture = TestSquare_stdout.capture_stdout(s, "display")
self.assertEqual(" ##\n ##\n", capture.getvalue())
def test_display_size_x(self):
s = Square(4, 1, 0, 18)
capture = TestSquare_stdout.capture_stdout(s, "display")
self.assertEqual(" ####\n ####\n ####\n ####\n", capture.getvalue())
def test_display_size_y(self):
s = Square(4, 0, 1, 12)
capture = TestSquare_stdout.capture_stdout(s, "display")
display = "\n####\n####\n####\n####\n"
self.assertEqual(display, capture.getvalue())
def test_display_size_x_y(self):
s = Square(2, 3, 2, 1)
capture = TestSquare_stdout.capture_stdout(s, "display")
display = "\n\n ##\n ##\n"
self.assertEqual(display, capture.getvalue())
def test_display_one_arg(self):
s = Square(3, 4, 5, 2)
with self.assertRaises(TypeError):
s.display(1)
class TestSquare_update_args(unittest.TestCase):
"""Unittests for testing update args method of the Square class."""
def test_update_args_zero(self):
s = Square(10, 10, 10, 10)
s.update()
self.assertEqual("[Square] (10) 10/10 - 10", str(s))
def test_update_one_arg(self):
s = Square(10, 10, 10, 10)
s.update(13)
self.assertEqual("[Square] (13) 10/10 - 10", str(s))
def test_update_x_arg(self):
s = Square(10, 3, 10, 10)
s.update(x=13)
self.assertEqual("[Square] (10) 13/10 - 10", str(s))
def test_update_y_arg(self):
s = Square(10, 10, 3, 4)
s.update(13)
s.y = 53
s.update(5)
self.assertEqual("[Square] (5) 10/53 - 10", str(s))
def test_update_args_two(self):
s = Square(10, 10, 10, 10)
s.update(89, 2)
self.assertEqual("[Square] (89) 10/10 - 2", str(s))
def test_update_args_three(self):
s = Square(10, 10, 10, 10)
s.update(89, 2, 3)
self.assertEqual("[Square] (89) 3/10 - 2", str(s))
def test_update_args_four(self):
s = Square(10, 10, 10, 10)
s.update(89, 2, 3, 4)
self.assertEqual("[Square] (89) 3/4 - 2", str(s))
def test_update_args_more_than_four(self):
s = Square(10, 10, 10, 10)
s.update(89, 2, 3, 4, 5)
self.assertEqual("[Square] (89) 3/4 - 2", str(s))
def test_update_args_width_setter(self):
s = Square(10, 10, 10, 10)
s.update(89, 2)
self.assertEqual(2, s.width)
def test_update_args_height_setter(self):
s = Square(10, 10, 10, 10)
s.update(89, 2)
self.assertEqual(2, s.height)
def test_update_args_none_id(self):
s = Square(10, 10, 10, 10)
s.update(None)
correct = "[Square] ({}) 10/10 - 10".format(s.id)
self.assertEqual(correct, str(s))
def test_update_args_None_id_and_more(self):
s = Square(10, 10, 10, 10)
s.update(None, 4, 5)
correct = "[Square] ({}) 5/10 - 4".format(s.id)
self.assertEqual(correct, str(s))
def test_update_args_twice(self):
s = Square(10, 10, 10, 10)
s.update(89, 2, 3, 4)
s.update(4, 3, 2, 89)
self.assertEqual("[Square] (4) 2/89 - 3", str(s))
def test_update_args_invalid_size_type(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s.update(89, "invalid")
def test_update_args_size_zero(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s.update(89, 0)
def test_update_args_size_negative(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s.update(89, -4)
def test_update_args_invalid_x(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s.update(89, 1, "invalid")
def test_update_args_x_negative(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "x must be >= 0"):
s.update(98, 1, -4)
def test_update_args_invalid_y(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s.update(89, 1, 2, "invalid")
def test_update_args_y_negative(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "y must be >= 0"):
s.update(98, 1, 2, -4)
def test_update_args_size_before_x(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s.update(89, "invalid", "invalid")
def test_update_args_size_before_y(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s.update(89, "invalid", 2, "invalid")
def test_update_args_x_before_y(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s.update(89, 1, "invalid", "invalid")
class TestSquare_update_kwargs(unittest.TestCase):
"""Unittests for testing update kwargs method of Square class."""
def test_update_kwargs_one(self):
s = Square(10, 10, 10, 10)
s.update(id=1)
self.assertEqual("[Square] (1) 10/10 - 10", str(s))
def test_update_kwargs_two(self):
s = Square(10, 10, 10, 10)
s.update(size=1, id=2)
self.assertEqual("[Square] (2) 10/10 - 1", str(s))
def test_update_kwargs_three(self):
s = Square(10, 10, 10, 10)
s.update(y=1, size=3, id=89)
self.assertEqual("[Square] (89) 10/1 - 3", str(s))
def test_update_kwargs_four(self):
s = Square(10, 10, 10, 10)
s.update(id=89, x=1, y=3, size=4)
self.assertEqual("[Square] (89) 1/3 - 4", str(s))
def test_update_kwargs_width_setter(self):
s = Square(10, 10, 10, 10)
s.update(id=89, size=8)
self.assertEqual(8, s.width)
def test_update_kwargs_height_setter(self):
s = Square(10, 10, 10, 10)
s.update(id=89, size=9)
self.assertEqual(9, s.height)
def test_update_kwargs_None_id(self):
s = Square(10, 10, 10, 10)
s.update(id=None)
correct = "[Square] ({}) 10/10 - 10".format(s.id)
self.assertEqual(correct, str(s))
def test_update_kwargs_None_id_and_more(self):
s = Square(10, 10, 10, 10)
s.update(id=None, size=7, x=18)
correct = "[Square] ({}) 18/10 - 7".format(s.id)
self.assertEqual(correct, str(s))
def test_update_kwargs_twice(self):
s = Square(10, 10, 10, 10)
s.update(id=89, x=1)
s.update(y=3, x=15, size=2)
self.assertEqual("[Square] (89) 15/3 - 2", str(s))
def test_update_kwargs_invalid_size(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "width must be an integer"):
s.update(size="invalid")
def test_update_kwargs_size_zero(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s.update(size=0)
def test_update_kwargs_size_negative(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "width must be > 0"):
s.update(size=-3)
def test_update_kwargs_invalid_x(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "x must be an integer"):
s.update(x="invalid")
def test_update_kwargs_x_negative(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(ValueError, "x must be >= 0"):
s.update(x=-5)
def test_update_kwargs_invalid_y(self):
s = Square(10, 10, 10, 10)
with self.assertRaisesRegex(TypeError, "y must be an integer"):
s.update(y="invalid")
class TestSquare_to_dictionary(unittest.TestCase):
"""Unittests for testing to_dictionary method of the Square class."""
def test_to_dictionary_output(self):
s = Square(10, 2, 1, 1)
correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}
self.assertDictEqual(correct, s.to_dictionary())
def test_to_dictionary_no_object_changes(self):
s1 = Square(10, 2, 1, 2)
s2 = Square(1, 2, 10)
s2.update(**s1.to_dictionary())
self.assertNotEqual(s1, s2)
def test_to_dictionary_arg(self):
s = Square(10, 10, 10, 10)
with self.assertRaises(TypeError):
s.to_dictionary(1)
if __name__ == "__main__":
unittest.main()
| [
"#!/usr/bin/python3\n# test_square.py\n# Carlos Barros <[email protected]>\n\"\"\"Defines unittests for square.py.\"\"\"\nimport unittest\nimport io\nimport sys\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square class.\"\"\"\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual(\"Holberton\", Square(1, 2, 6, \"Holberton\").id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n\n def test_size_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(size=43)\n self.assertEqual(43, s.size)\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and\n s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and\n s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, \"Hello\", 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, \"Holberton\")\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square(\"Hello\", 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, \"Betty\", 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, \"Betty\", 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n Square(\"invalid size\", \"invalid x\")\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n Square(\"invalid size\", 1, \"invalid y\")\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, \"x must be an integer\"):\n Square(1, \"invalid x\", \"invalid y\")\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, \"Holberton\")\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == \"print\":\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, \"print\")\n correct = \"[Square] ({}) 0/0 - 4\\n\".format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = \"[Square] ({}) 43/0 - 5\".format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = \"[Square] ({}) 4/22 - 7\".format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual(\"[Square] (19) 88/4 - 2\", str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual(\"[Square] ([4]) 8/10 - 15\", str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n # Test display method\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, \"display\")\n self.assertEqual(\" ##\\n ##\\n\", capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, \"display\")\n self.assertEqual(\" ####\\n ####\\n ####\\n ####\\n\", capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, \"display\")\n display = \"\\n####\\n####\\n####\\n####\\n\"\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, \"display\")\n display = \"\\n\\n ##\\n ##\\n\"\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual(\"[Square] (10) 10/10 - 10\", str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual(\"[Square] (13) 10/10 - 10\", str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual(\"[Square] (10) 13/10 - 10\", str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual(\"[Square] (5) 10/53 - 10\", str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(\"[Square] (89) 10/10 - 2\", str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual(\"[Square] (89) 3/10 - 2\", str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual(\"[Square] (89) 3/4 - 2\", str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual(\"[Square] (89) 3/4 - 2\", str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = \"[Square] ({}) 10/10 - 10\".format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = \"[Square] ({}) 5/10 - 4\".format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual(\"[Square] (4) 2/89 - 3\", str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n s.update(89, \"invalid\")\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"x must be an integer\"):\n s.update(89, 1, \"invalid\")\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"x must be >= 0\"):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"y must be an integer\"):\n s.update(89, 1, 2, \"invalid\")\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"y must be >= 0\"):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n s.update(89, \"invalid\", \"invalid\")\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n s.update(89, \"invalid\", 2, \"invalid\")\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"x must be an integer\"):\n s.update(89, 1, \"invalid\", \"invalid\")\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual(\"[Square] (1) 10/10 - 10\", str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual(\"[Square] (2) 10/10 - 1\", str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual(\"[Square] (89) 10/1 - 3\", str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual(\"[Square] (89) 1/3 - 4\", str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = \"[Square] ({}) 10/10 - 10\".format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = \"[Square] ({}) 18/10 - 7\".format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual(\"[Square] (89) 15/3 - 2\", str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"width must be an integer\"):\n s.update(size=\"invalid\")\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"width must be > 0\"):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"x must be an integer\"):\n s.update(x=\"invalid\")\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, \"x must be >= 0\"):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, \"y must be an integer\"):\n s.update(y=\"invalid\")\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"<docstring token>\nimport unittest\nimport io\nimport sys\nfrom models.base import Base\nfrom models.rectangle import Rectangle\nfrom models.square import Square\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square class.\"\"\"\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n\n def test_size_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(size=43)\n self.assertEqual(43, s.size)\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square class.\"\"\"\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n\n def test_size_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(size=43)\n self.assertEqual(43, s.size)\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square class.\"\"\"\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n\n def test_size_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(size=43)\n self.assertEqual(43, s.size)\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n\n def test_size_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(size=43)\n self.assertEqual(43, s.size)\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n\n def test_none_size(self):\n with self.assertRaises(TypeError):\n Square(None, 2)\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n\n def test_y_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57)\n self.assertEqual(57, s.y)\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1)\n self.assertTrue(s.y == 0 and s.x == 0)\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n\n def test_size_getter(self):\n self.assertEqual(6, Square(6, 2, 3, 9).size)\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n\n def test_id_str(self):\n self.assertEqual('Holberton', Square(1, 2, 6, 'Holberton').id)\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n\n def test_one_line(self):\n self.assertEqual(4, Square(1, 2, 6, 4).id)\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n\n def test_is_base(self):\n self.assertIsInstance(Square(10), Base)\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n\n def test_float_all(self):\n with self.assertRaises(TypeError):\n Square(3.0, 5.0, 4.0, 62.0)\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_is_rectangle(self):\n self.assertIsInstance(Square(4), Rectangle)\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n\n def test_4_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n s4 = Square(6, 4, 54)\n self.assertEqual(s1.id, s4.id - 3)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter(self):\n self.assertEqual(2, Square(6, 2, 3, 9).x)\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n\n def test_y_getter(self):\n self.assertEqual(3, Square(6, 2, 3, 9).y)\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n\n def test_3_values(self):\n s1 = Square(1, 2)\n s2 = Square(2, 7)\n s3 = Square(10, 2, 16)\n self.assertEqual(s1.id, s3.id - 2)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_no_args(self):\n with self.assertRaises(TypeError):\n Square()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n\n def test_update_all(self):\n s = Square(6, 2, 3, 9)\n s.update(y=57, id=4, x=79, size=76)\n self.assertTrue(s.x == 79 and s.id == 4 and s.y == 57 and s.size == 76)\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n <function token>\n <function token>\n\n def test_y_id(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 'Hello', 5)\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_six_arg(self):\n with self.assertRaises(TypeError):\n Square(10, 2, 16, 4, 4, 'Holberton')\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n\n def test_zero_x_y(self):\n s = Square(75, 54, 32, -52)\n self.assertTrue(s.id == -52)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n\n def test_zero_x_y(self):\n s = Square(1, 5, 6, 0)\n self.assertTrue(s.y == 6 and s.x == 5 and s.id == 0 and s.size == 1)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_getter_1(self):\n s = Square(6, 2, 3, 9)\n s.update(x=23)\n self.assertEqual(23, s.x)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\nclass TestSquare_instantiation(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square size attribute.\"\"\"\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n\n def test_size_n(self):\n with self.assertRaises(ValueError):\n Square(-75, 52, 53, 543)\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n\n def test_size_none_2(self):\n with self.assertRaises(TypeError):\n Square(None, 6, 7)\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n <function token>\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n <function token>\n\n def test_size_float(self):\n with self.assertRaises(TypeError):\n Square(5.0, 32, 63, 554.0)\n <function token>\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n <function token>\n <function token>\n <function token>\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n\n def test_size_zero(self):\n with self.assertRaises(ValueError):\n Square(0, 52, 53, 543)\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n <function token>\n <function token>\n <function token>\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n <function token>\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n\n def test_size_complex(self):\n with self.assertRaises(TypeError):\n Square(complex(5), 52, 53, 543)\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n <function token>\n <function token>\n <function token>\n\n def test_size_string(self):\n with self.assertRaises(TypeError):\n Square('Hello', 52, 53, 543)\n <function token>\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n <function token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n\n def test_size_none(self):\n with self.assertRaises(TypeError):\n Square(None)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n <function token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_float_inf(self):\n with self.assertRaises(TypeError):\n Square(float('inf'), 52, 53, 543)\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n <function token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_float_nan(self):\n with self.assertRaises(TypeError):\n Square(float('nan'), 52, 53, 543)\n <function token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n\n\nclass TestSquare_size(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square x attribute.\"\"\"\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n\n def test_x_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, float('inf'), 53, 543)\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n\n def test_x_float(self):\n with self.assertRaises(TypeError):\n Square(5, 32.43, 63)\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n <function token>\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n\n def test_x_complex(self):\n with self.assertRaises(TypeError):\n Square(5, complex(5), 53, 543)\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n <function token>\n\n def test_x_n(self):\n with self.assertRaises(ValueError):\n Square(75, -52, 53, 543)\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n\n def test_x_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, None, 7)\n <function token>\n <function token>\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n\n def test_x_none(self):\n with self.assertRaises(TypeError):\n Square(x=None)\n <function token>\n <function token>\n <function token>\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_string(self):\n with self.assertRaises(TypeError):\n Square(4, 'Betty', 53, 543)\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_x_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, float('nan'), 53, 543)\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n\n\nclass TestSquare_x(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square y attribute.\"\"\"\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n\n def test_y_n(self):\n with self.assertRaises(ValueError):\n Square(75, 54, -52, 543)\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n\n def test_y_complex(self):\n with self.assertRaises(TypeError):\n Square(5, 75, complex(5), 543)\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n\n def test_y_none(self):\n with self.assertRaises(TypeError):\n Square(y=None)\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n\n def test_y_float_inf(self):\n with self.assertRaises(TypeError):\n Square(4, 36, float('inf'), 543)\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n\n def test_y_string(self):\n with self.assertRaises(TypeError):\n Square(4, 6, 'Betty', 543)\n <function token>\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n <function token>\n <function token>\n\n def test_y_float_nan(self):\n with self.assertRaises(TypeError):\n Square(97, 51, float('nan'), 543)\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_y_none_2(self):\n with self.assertRaises(TypeError):\n Square(4, 5, None, 7)\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_y_float(self):\n with self.assertRaises(TypeError):\n Square(5, 4, 32.43, 4)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_y(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n \"\"\"Unittests for testing instantiation of the Square id attribute.\"\"\"\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n\n def test_id_none(self):\n with self.assertRaises(TypeError):\n Square(id=None)\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n\n def test_id_float_inf(self):\n s = Square(4, 36, 434, float('inf'))\n self.assertEqual(float('inf'), s.id)\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n <function token>\n\n def test_id_complex(self):\n s = Square(5, 75, 434, complex(5))\n self.assertEqual(complex(5), s.id)\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_id_float(self):\n s = Square(5, 4, 5, 32.43)\n self.assertEqual(32.43, s.id)\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n <function token>\n <function token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_id_n(self):\n s = Square(75, 54, 32, -52)\n self.assertEqual(-52, s.id)\n <function token>\n <function token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_id(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n \"\"\"Unittests for testing order of Square attribute initialization.\"\"\"\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n <docstring token>\n\n def test_size_before_x(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 'invalid x')\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_size_before_y(self):\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n Square('invalid size', 1, 'invalid y')\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_x_before_y(self):\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n Square(1, 'invalid x', 'invalid y')\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_order_of_initialization(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n \"\"\"Unittests for testing the area method of the Square class.\"\"\"\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n\n def test_area_small(self):\n self.assertEqual(100, Square(10, 0, 0, 1).area())\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n\n def test_area_one_complex_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1, complex(5))\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n\n def test_area_changed_number_n(self):\n s = Square(2, 0, 0, 1)\n with self.assertRaises(TypeError):\n s.area(None, 5)\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n\n def test_area_changed_attributes(self):\n s = Square(2, 0, 0, 1)\n s.size = 7\n self.assertEqual(49, s.area())\n <function token>\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n <function token>\n <function token>\n\n def test_area_one_arg(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(1)\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_area_large(self):\n s = Square(999999999999999999, 0, 0, 1)\n self.assertEqual(999999999999999998000000000000000001, s.area())\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(4, 'Holberton')\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_area_one_complex_arg_2(self):\n s = Square(2, 10, 1, 1)\n with self.assertRaises(TypeError):\n s.area(complex(41), 5)\n <function token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_area(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n \"\"\"Unittests for testing __str__ and display methods of Square class.\"\"\"\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n\n def test_changed_attributes(self):\n s = Square(7, 5, 34, [4])\n s.size = 15\n s.x = 8\n s.y = 10\n self.assertEqual('[Square] ([4]) 8/10 - 15', str(s))\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n\n @staticmethod\n def capture_stdout(sq, method):\n \"\"\"Captures and returns text printed to stdout.\n Args:\n sq (Square): The Square ot print to stdout.\n method (str): The method to run on sq.\n Returns:\n The text printed to stdout by calling method on sq.\n \"\"\"\n capture = io.StringIO()\n sys.stdout = capture\n if method == 'print':\n print(sq)\n else:\n sq.display()\n sys.stdout = sys.__stdout__\n return capture\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n\n def test_size_x(self):\n s = Square(5, 43)\n correct = '[Square] ({}) 43/0 - 5'.format(s.id)\n self.assertEqual(correct, s.__str__())\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n <function token>\n\n def test_size_x_y(self):\n s = Square(7, 4, 22)\n correct = '[Square] ({}) 4/22 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_print_size(self):\n s = Square(4)\n capture = TestSquare_stdout.capture_stdout(s, 'print')\n correct = '[Square] ({}) 0/0 - 4\\n'.format(s.id)\n self.assertEqual(correct, capture.getvalue())\n <function token>\n <function token>\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n\n def test_display_size(self):\n s = Square(2, 2, 0, 53)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ##\\n ##\\n', capture.getvalue())\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n\n def test_str_method_one_arg(self):\n s = Square(1, 2, 3, 4)\n with self.assertRaises(TypeError):\n s.__str__(1)\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_size_x_y_id(self):\n s = Square(2, 88, 4, 19)\n self.assertEqual('[Square] (19) 88/4 - 2', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_size_x_y(self):\n s = Square(2, 3, 2, 1)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n\\n ##\\n ##\\n'\n self.assertEqual(display, capture.getvalue())\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n <function token>\n\n def test_display_one_arg(self):\n s = Square(3, 4, 5, 2)\n with self.assertRaises(TypeError):\n s.display(1)\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n\n def test_display_size_y(self):\n s = Square(4, 0, 1, 12)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n display = '\\n####\\n####\\n####\\n####\\n'\n self.assertEqual(display, capture.getvalue())\n <function token>\n <function token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_display_size_x(self):\n s = Square(4, 1, 0, 18)\n capture = TestSquare_stdout.capture_stdout(s, 'display')\n self.assertEqual(' ####\\n ####\\n ####\\n ####\\n', capture.getvalue())\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_stdout(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n \"\"\"Unittests for testing update args method of the Square class.\"\"\"\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n\n def test_update_args_none_id(self):\n s = Square(10, 10, 10, 10)\n s.update(None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_args_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n s.update(4, 3, 2, 89)\n self.assertEqual('[Square] (4) 2/89 - 3', str(s))\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n\n def test_update_args_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, -4)\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n\n def test_update_args_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(98, 1, -4)\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n\n def test_update_args_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(89, 0)\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n\n def test_update_args_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n <function token>\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n\n def test_update_args_x_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid', 'invalid')\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n <function token>\n\n def test_update_args_more_than_four(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3, 4, 5)\n self.assertEqual('[Square] (89) 3/4 - 2', str(s))\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n <function token>\n <function token>\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n\n def test_update_args_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(89, 1, 'invalid')\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n\n def test_update_args_three(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2, 3)\n self.assertEqual('[Square] (89) 3/10 - 2', str(s))\n <function token>\n <function token>\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n\n def test_update_args_zero(self):\n s = Square(10, 10, 10, 10)\n s.update()\n self.assertEqual('[Square] (10) 10/10 - 10', str(s))\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n\n def test_update_args_size_before_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 2, 'invalid')\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_update_args_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.width)\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual(2, s.height)\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n\n def test_update_args_y_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'y must be >= 0'):\n s.update(98, 1, 2, -4)\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(89, 1, 2, 'invalid')\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_one_arg(self):\n s = Square(10, 10, 10, 10)\n s.update(13)\n self.assertEqual('[Square] (13) 10/10 - 10', str(s))\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n\n def test_update_args_two(self):\n s = Square(10, 10, 10, 10)\n s.update(89, 2)\n self.assertEqual('[Square] (89) 10/10 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_x_arg(self):\n s = Square(10, 3, 10, 10)\n s.update(x=13)\n self.assertEqual('[Square] (10) 13/10 - 10', str(s))\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n\n def test_update_args_invalid_size_type(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(None, 4, 5)\n correct = '[Square] ({}) 5/10 - 4'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_args_size_before_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(89, 'invalid', 'invalid')\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def test_update_y_arg(self):\n s = Square(10, 10, 3, 4)\n s.update(13)\n s.y = 53\n s.update(5)\n self.assertEqual('[Square] (5) 10/53 - 10', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_args(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n \"\"\"Unittests for testing update kwargs method of Square class.\"\"\"\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n\n def test_update_kwargs_invalid_x(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'x must be an integer'):\n s.update(x='invalid')\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n\n def test_update_kwargs_size_zero(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=0)\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n\n def test_update_kwargs_one(self):\n s = Square(10, 10, 10, 10)\n s.update(id=1)\n self.assertEqual('[Square] (1) 10/10 - 10', str(s))\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n\n def test_update_kwargs_height_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=9)\n self.assertEqual(9, s.height)\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n\n def test_update_kwargs_width_setter(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, size=8)\n self.assertEqual(8, s.width)\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n\n def test_update_kwargs_invalid_y(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'y must be an integer'):\n s.update(y='invalid')\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_update_kwargs_two(self):\n s = Square(10, 10, 10, 10)\n s.update(size=1, id=2)\n self.assertEqual('[Square] (2) 10/10 - 1', str(s))\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n\n def test_update_kwargs_size_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'width must be > 0'):\n s.update(size=-3)\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n <function token>\n <function token>\n\n def test_update_kwargs_x_negative(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(ValueError, 'x must be >= 0'):\n s.update(x=-5)\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n\n def test_update_kwargs_invalid_size(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaisesRegex(TypeError, 'width must be an integer'):\n s.update(size='invalid')\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n\n def test_update_kwargs_four(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1, y=3, size=4)\n self.assertEqual('[Square] (89) 1/3 - 4', str(s))\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_twice(self):\n s = Square(10, 10, 10, 10)\n s.update(id=89, x=1)\n s.update(y=3, x=15, size=2)\n self.assertEqual('[Square] (89) 15/3 - 2', str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_update_kwargs_three(self):\n s = Square(10, 10, 10, 10)\n s.update(y=1, size=3, id=89)\n self.assertEqual('[Square] (89) 10/1 - 3', str(s))\n <function token>\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_kwargs_None_id(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None)\n correct = '[Square] ({}) 10/10 - 10'.format(s.id)\n self.assertEqual(correct, str(s))\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_update_kwargs_None_id_and_more(self):\n s = Square(10, 10, 10, 10)\n s.update(id=None, size=7, x=18)\n correct = '[Square] ({}) 18/10 - 7'.format(s.id)\n self.assertEqual(correct, str(s))\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_update_kwargs(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n \"\"\"Unittests for testing to_dictionary method of the Square class.\"\"\"\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n <docstring token>\n\n def test_to_dictionary_output(self):\n s = Square(10, 2, 1, 1)\n correct = {'id': 1, 'x': 2, 'size': 10, 'y': 1}\n self.assertDictEqual(correct, s.to_dictionary())\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n\n def test_to_dictionary_arg(self):\n s = Square(10, 10, 10, 10)\n with self.assertRaises(TypeError):\n s.to_dictionary(1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n <docstring token>\n <function token>\n\n def test_to_dictionary_no_object_changes(self):\n s1 = Square(10, 2, 1, 2)\n s2 = Square(1, 2, 10)\n s2.update(**s1.to_dictionary())\n self.assertNotEqual(s1, s2)\n <function token>\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestSquare_to_dictionary(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<code token>\n"
] | false |
99,792 | 4819f43d2afb94a0a85e6e2993831caed55f0677 | import pandas as pd
a = [1, 7, 2]
# Modificando o Index na matriz
myVar = pd.Series(a, index = ['x', 'y', 'z'])
print(myVar) | [
"import pandas as pd\n\na = [1, 7, 2]\n\n# Modificando o Index na matriz\nmyVar = pd.Series(a, index = ['x', 'y', 'z'])\n\nprint(myVar)",
"import pandas as pd\na = [1, 7, 2]\nmyVar = pd.Series(a, index=['x', 'y', 'z'])\nprint(myVar)\n",
"<import token>\na = [1, 7, 2]\nmyVar = pd.Series(a, index=['x', 'y', 'z'])\nprint(myVar)\n",
"<import token>\n<assignment token>\nprint(myVar)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,793 | d69d2d74b85452fbaa3eeddd2ba834f3dcb9cb41 | ##########################################################################
#################### This class is for evaluating a trained model ######
##########################################################################
# import libraries
import numpy as np
import pandas as pd
import os
from sklearn.metrics import confusion_matrix, roc_curve, auc, mean_absolute_error, mean_squared_error, classification_report, accuracy_score
from utils.data_manager import DataManager
from utils.plot_data import PlotData
from keras.models import model_from_json
from keras import backend as K
K.set_image_dim_ordering('tf')
# Model type
model_type = 'wow_128_10'
# Images width, height, channels
img_height = 128
img_width = 128
# number of test samples in the dataset
num_of_test_samples = 800
# for confusion matrix plotting
cm_plot_labels = ['cover', 'stego']
# test dataset
model_test_dataset = 'dataset_' + model_type
# path to saved model files
saved_model_weights_path = './trained_for_pred/' + \
model_type + '/model/Best-weights.h5'
saved_model_arch_path = './trained_for_pred/' + \
model_type + '/model/scratch_model.json'
test_data_dir = './datasets/' + model_test_dataset + '/test'
# paths to save outputs
save_plt_cm = './trained_for_pred/' + model_type + '/stats/scratch_model_cm.png'
save_plt_normalized_cm = './trained_for_pred/' + \
model_type + '/stats/scratch_model_norm_cm.png'
save_plt_roc = './trained_for_pred/' + \
model_type + '/stats/scratch_model_roc.png'
save_eval_report = './trained_for_pred/' + \
model_type + '/stats/eval_report.txt'
train_log_data_path = './trained_for_pred/' + \
model_type + '/model/log/model_train.csv'
save_plt_accuracy = './trained_for_pred/' + \
model_type + '/stats/model_accuracy.png'
save_plt_loss = './trained_for_pred/' + \
model_type + '/stats/model_loss.png'
save_plt_learning = './trained_for_pred/' + \
model_type + '/stats/model_learning.eps'
# Cost function
model_loss_function = 'binary_crossentropy'
# define optimizers
model_optimizer_rmsprop = 'rmsprop'
# model metrics to evaluate training
model_metrics = ["accuracy"]
# batch size
batch_size = 16
# Load architecture and weights of the model
def load_model():
json_file = open(saved_model_arch_path, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights(saved_model_weights_path)
return loaded_model
def delete_file(filename):
if os.path.exists(filename):
os.remove(filename)
pass
def main():
# init DataManager class
dataManager = DataManager(img_height, img_width)
# init PlotData class
plotData = PlotData()
# load model
print("===================== load model =========================")
model = load_model()
# get test data
print("===================== load data =========================")
test_data = dataManager.get_test_data(test_data_dir)
# start the eval process
print("===================== start eval =========================")
y_true = test_data.classes
# Confution Matrix and Classification Report
Y_pred = model.predict_generator(test_data, num_of_test_samples // batch_size)
y_pred = np.argmax(Y_pred, axis=1)
# plot confusion matrix
cm = confusion_matrix(y_true, y_pred)
plotData.plot_confusion_matrix(
cm, cm_plot_labels, save_plt_cm, title='Confusion Matrix')
plotData.plot_confusion_matrix(
cm, cm_plot_labels, save_plt_normalized_cm, normalize=True, title='Normalized Confusion Matrix')
# Compute ROC curve and ROC area for each class
roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)
mae = mean_absolute_error(y_true, y_pred)
mse = mean_squared_error(y_true, y_pred)
accuracy = accuracy_score(y_true, y_pred)
print('mean absolute error: ' + str(mae))
print('mean squared error: ' + str(mse))
print('Area Under the Curve (AUC): ' + str(roc_auc))
c_report = classification_report(
y_true, y_pred, target_names=cm_plot_labels)
print(c_report)
delete_file(save_eval_report)
with open(save_eval_report, 'a') as f:
f.write('\n\n')
f.write('******************************************************\n')
f.write('************** Evalaluation Report ***************\n')
f.write('******************************************************\n')
f.write('\n\n')
f.write('- Accuracy Score: ' + str(accuracy))
f.write('\n\n')
f.write('- Mean Absolute Error (MAE): ' + str(mae))
f.write('\n\n')
f.write('- Mean Squared Error (MSE): ' + str(mse))
f.write('\n\n')
f.write('- Area Under the Curve (AUC): ' + str(roc_auc))
f.write('\n\n')
f.write('- Confusion Matrix:\n')
f.write(str(cm))
f.write('\n\n')
f.write('- Normalized Confusion Matrix:\n')
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
f.write(str(cm))
f.write('\n\n')
f.write('- Classification report:\n')
f.write(str(c_report))
f.close()
train_validation = ['train', 'validation']
data = pd.read_csv(train_log_data_path)
acc = data['acc'].values
val_acc = data['val_acc'].values
loss = data['loss'].values
val_loss = data['val_loss'].values
# plot metrics to the stats dir
plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy',
'Model Accuracy', train_validation, save_plt_accuracy)
plotData.plot_2d(loss, val_loss, 'epoch', 'loss',
'Model Loss', train_validation, save_plt_loss)
plotData.plot_model_bis(data, save_plt_learning)
'''
# evalute model
# compile the model
print("==================== compile model ========================")
model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)
score = model.evaluate_generator(test_data, num_of_test_samples)
print('Test Loss:', score[0])
print('Test accuracy:', score[1])
'''
if __name__ == "__main__":
main()
| [
"##########################################################################\n#################### This class is for evaluating a trained model ######\n##########################################################################\n\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc, mean_absolute_error, mean_squared_error, classification_report, accuracy_score\nfrom utils.data_manager import DataManager\nfrom utils.plot_data import PlotData\nfrom keras.models import model_from_json\nfrom keras import backend as K\nK.set_image_dim_ordering('tf')\n\n# Model type\nmodel_type = 'wow_128_10'\n\n# Images width, height, channels\nimg_height = 128\nimg_width = 128\n# number of test samples in the dataset\nnum_of_test_samples = 800\n\n# for confusion matrix plotting\ncm_plot_labels = ['cover', 'stego']\n\n# test dataset\nmodel_test_dataset = 'dataset_' + model_type\n\n# path to saved model files\nsaved_model_weights_path = './trained_for_pred/' + \\\n model_type + '/model/Best-weights.h5'\nsaved_model_arch_path = './trained_for_pred/' + \\\n model_type + '/model/scratch_model.json'\ntest_data_dir = './datasets/' + model_test_dataset + '/test'\n\n# paths to save outputs\nsave_plt_cm = './trained_for_pred/' + model_type + '/stats/scratch_model_cm.png'\nsave_plt_normalized_cm = './trained_for_pred/' + \\\n model_type + '/stats/scratch_model_norm_cm.png'\nsave_plt_roc = './trained_for_pred/' + \\\n model_type + '/stats/scratch_model_roc.png'\nsave_eval_report = './trained_for_pred/' + \\\n model_type + '/stats/eval_report.txt'\n\ntrain_log_data_path = './trained_for_pred/' + \\\n model_type + '/model/log/model_train.csv'\n\nsave_plt_accuracy = './trained_for_pred/' + \\\n model_type + '/stats/model_accuracy.png'\n\nsave_plt_loss = './trained_for_pred/' + \\\n model_type + '/stats/model_loss.png'\n\nsave_plt_learning = './trained_for_pred/' + \\\n model_type + '/stats/model_learning.eps'\n# Cost function\nmodel_loss_function = 'binary_crossentropy'\n\n\n# define optimizers\nmodel_optimizer_rmsprop = 'rmsprop'\n\n# model metrics to evaluate training\nmodel_metrics = [\"accuracy\"]\n\n# batch size\nbatch_size = 16\n\n# Load architecture and weights of the model\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n # load weights into new model\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\ndef delete_file(filename):\n if os.path.exists(filename):\n os.remove(filename)\n pass\n\n\ndef main():\n # init DataManager class\n dataManager = DataManager(img_height, img_width)\n # init PlotData class\n plotData = PlotData()\n # load model\n print(\"===================== load model =========================\")\n model = load_model()\n # get test data\n print(\"===================== load data =========================\")\n test_data = dataManager.get_test_data(test_data_dir)\n # start the eval process\n print(\"===================== start eval =========================\")\n y_true = test_data.classes\n # Confution Matrix and Classification Report\n Y_pred = model.predict_generator(test_data, num_of_test_samples // batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n # plot confusion matrix\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(\n cm, cm_plot_labels, save_plt_cm, title='Confusion Matrix')\n plotData.plot_confusion_matrix(\n cm, cm_plot_labels, save_plt_normalized_cm, normalize=True, title='Normalized Confusion Matrix')\n # Compute ROC curve and ROC area for each class\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(\n y_true, y_pred, target_names=cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n\n f.close()\n\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n\n \n # plot metrics to the stats dir\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy',\n 'Model Accuracy', train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss',\n 'Model Loss', train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \n '''\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n '''\n\n\nif __name__ == \"__main__\":\n main()\n",
"import numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc, mean_absolute_error, mean_squared_error, classification_report, accuracy_score\nfrom utils.data_manager import DataManager\nfrom utils.plot_data import PlotData\nfrom keras.models import model_from_json\nfrom keras import backend as K\nK.set_image_dim_ordering('tf')\nmodel_type = 'wow_128_10'\nimg_height = 128\nimg_width = 128\nnum_of_test_samples = 800\ncm_plot_labels = ['cover', 'stego']\nmodel_test_dataset = 'dataset_' + model_type\nsaved_model_weights_path = ('./trained_for_pred/' + model_type +\n '/model/Best-weights.h5')\nsaved_model_arch_path = ('./trained_for_pred/' + model_type +\n '/model/scratch_model.json')\ntest_data_dir = './datasets/' + model_test_dataset + '/test'\nsave_plt_cm = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_cm.png')\nsave_plt_normalized_cm = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_norm_cm.png')\nsave_plt_roc = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_roc.png')\nsave_eval_report = ('./trained_for_pred/' + model_type +\n '/stats/eval_report.txt')\ntrain_log_data_path = ('./trained_for_pred/' + model_type +\n '/model/log/model_train.csv')\nsave_plt_accuracy = ('./trained_for_pred/' + model_type +\n '/stats/model_accuracy.png')\nsave_plt_loss = './trained_for_pred/' + model_type + '/stats/model_loss.png'\nsave_plt_learning = ('./trained_for_pred/' + model_type +\n '/stats/model_learning.eps')\nmodel_loss_function = 'binary_crossentropy'\nmodel_optimizer_rmsprop = 'rmsprop'\nmodel_metrics = ['accuracy']\nbatch_size = 16\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\ndef delete_file(filename):\n if os.path.exists(filename):\n os.remove(filename)\n pass\n\n\ndef main():\n dataManager = DataManager(img_height, img_width)\n plotData = PlotData()\n print('===================== load model =========================')\n model = load_model()\n print('===================== load data =========================')\n test_data = dataManager.get_test_data(test_data_dir)\n print('===================== start eval =========================')\n y_true = test_data.classes\n Y_pred = model.predict_generator(test_data, num_of_test_samples //\n batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(cm, cm_plot_labels, save_plt_cm, title=\n 'Confusion Matrix')\n plotData.plot_confusion_matrix(cm, cm_plot_labels,\n save_plt_normalized_cm, normalize=True, title=\n 'Normalized Confusion Matrix')\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(y_true, y_pred, target_names=\n cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n f.close()\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy', 'Model Accuracy',\n train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss', 'Model Loss',\n train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \"\"\"\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n \"\"\"\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\nK.set_image_dim_ordering('tf')\nmodel_type = 'wow_128_10'\nimg_height = 128\nimg_width = 128\nnum_of_test_samples = 800\ncm_plot_labels = ['cover', 'stego']\nmodel_test_dataset = 'dataset_' + model_type\nsaved_model_weights_path = ('./trained_for_pred/' + model_type +\n '/model/Best-weights.h5')\nsaved_model_arch_path = ('./trained_for_pred/' + model_type +\n '/model/scratch_model.json')\ntest_data_dir = './datasets/' + model_test_dataset + '/test'\nsave_plt_cm = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_cm.png')\nsave_plt_normalized_cm = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_norm_cm.png')\nsave_plt_roc = ('./trained_for_pred/' + model_type +\n '/stats/scratch_model_roc.png')\nsave_eval_report = ('./trained_for_pred/' + model_type +\n '/stats/eval_report.txt')\ntrain_log_data_path = ('./trained_for_pred/' + model_type +\n '/model/log/model_train.csv')\nsave_plt_accuracy = ('./trained_for_pred/' + model_type +\n '/stats/model_accuracy.png')\nsave_plt_loss = './trained_for_pred/' + model_type + '/stats/model_loss.png'\nsave_plt_learning = ('./trained_for_pred/' + model_type +\n '/stats/model_learning.eps')\nmodel_loss_function = 'binary_crossentropy'\nmodel_optimizer_rmsprop = 'rmsprop'\nmodel_metrics = ['accuracy']\nbatch_size = 16\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\ndef delete_file(filename):\n if os.path.exists(filename):\n os.remove(filename)\n pass\n\n\ndef main():\n dataManager = DataManager(img_height, img_width)\n plotData = PlotData()\n print('===================== load model =========================')\n model = load_model()\n print('===================== load data =========================')\n test_data = dataManager.get_test_data(test_data_dir)\n print('===================== start eval =========================')\n y_true = test_data.classes\n Y_pred = model.predict_generator(test_data, num_of_test_samples //\n batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(cm, cm_plot_labels, save_plt_cm, title=\n 'Confusion Matrix')\n plotData.plot_confusion_matrix(cm, cm_plot_labels,\n save_plt_normalized_cm, normalize=True, title=\n 'Normalized Confusion Matrix')\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(y_true, y_pred, target_names=\n cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n f.close()\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy', 'Model Accuracy',\n train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss', 'Model Loss',\n train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \"\"\"\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n \"\"\"\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\nK.set_image_dim_ordering('tf')\n<assignment token>\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\ndef delete_file(filename):\n if os.path.exists(filename):\n os.remove(filename)\n pass\n\n\ndef main():\n dataManager = DataManager(img_height, img_width)\n plotData = PlotData()\n print('===================== load model =========================')\n model = load_model()\n print('===================== load data =========================')\n test_data = dataManager.get_test_data(test_data_dir)\n print('===================== start eval =========================')\n y_true = test_data.classes\n Y_pred = model.predict_generator(test_data, num_of_test_samples //\n batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(cm, cm_plot_labels, save_plt_cm, title=\n 'Confusion Matrix')\n plotData.plot_confusion_matrix(cm, cm_plot_labels,\n save_plt_normalized_cm, normalize=True, title=\n 'Normalized Confusion Matrix')\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(y_true, y_pred, target_names=\n cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n f.close()\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy', 'Model Accuracy',\n train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss', 'Model Loss',\n train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \"\"\"\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n \"\"\"\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n<code token>\n<assignment token>\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\ndef delete_file(filename):\n if os.path.exists(filename):\n os.remove(filename)\n pass\n\n\ndef main():\n dataManager = DataManager(img_height, img_width)\n plotData = PlotData()\n print('===================== load model =========================')\n model = load_model()\n print('===================== load data =========================')\n test_data = dataManager.get_test_data(test_data_dir)\n print('===================== start eval =========================')\n y_true = test_data.classes\n Y_pred = model.predict_generator(test_data, num_of_test_samples //\n batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(cm, cm_plot_labels, save_plt_cm, title=\n 'Confusion Matrix')\n plotData.plot_confusion_matrix(cm, cm_plot_labels,\n save_plt_normalized_cm, normalize=True, title=\n 'Normalized Confusion Matrix')\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(y_true, y_pred, target_names=\n cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n f.close()\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy', 'Model Accuracy',\n train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss', 'Model Loss',\n train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \"\"\"\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n \"\"\"\n\n\n<code token>\n",
"<import token>\n<code token>\n<assignment token>\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\n<function token>\n\n\ndef main():\n dataManager = DataManager(img_height, img_width)\n plotData = PlotData()\n print('===================== load model =========================')\n model = load_model()\n print('===================== load data =========================')\n test_data = dataManager.get_test_data(test_data_dir)\n print('===================== start eval =========================')\n y_true = test_data.classes\n Y_pred = model.predict_generator(test_data, num_of_test_samples //\n batch_size)\n y_pred = np.argmax(Y_pred, axis=1)\n cm = confusion_matrix(y_true, y_pred)\n plotData.plot_confusion_matrix(cm, cm_plot_labels, save_plt_cm, title=\n 'Confusion Matrix')\n plotData.plot_confusion_matrix(cm, cm_plot_labels,\n save_plt_normalized_cm, normalize=True, title=\n 'Normalized Confusion Matrix')\n roc_auc = plotData.plot_roc(y_true, y_pred, save_plt_roc)\n mae = mean_absolute_error(y_true, y_pred)\n mse = mean_squared_error(y_true, y_pred)\n accuracy = accuracy_score(y_true, y_pred)\n print('mean absolute error: ' + str(mae))\n print('mean squared error: ' + str(mse))\n print('Area Under the Curve (AUC): ' + str(roc_auc))\n c_report = classification_report(y_true, y_pred, target_names=\n cm_plot_labels)\n print(c_report)\n delete_file(save_eval_report)\n with open(save_eval_report, 'a') as f:\n f.write('\\n\\n')\n f.write('******************************************************\\n')\n f.write('************** Evalaluation Report ***************\\n')\n f.write('******************************************************\\n')\n f.write('\\n\\n')\n f.write('- Accuracy Score: ' + str(accuracy))\n f.write('\\n\\n')\n f.write('- Mean Absolute Error (MAE): ' + str(mae))\n f.write('\\n\\n')\n f.write('- Mean Squared Error (MSE): ' + str(mse))\n f.write('\\n\\n')\n f.write('- Area Under the Curve (AUC): ' + str(roc_auc))\n f.write('\\n\\n')\n f.write('- Confusion Matrix:\\n')\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Normalized Confusion Matrix:\\n')\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n f.write(str(cm))\n f.write('\\n\\n')\n f.write('- Classification report:\\n')\n f.write(str(c_report))\n f.close()\n train_validation = ['train', 'validation']\n data = pd.read_csv(train_log_data_path)\n acc = data['acc'].values\n val_acc = data['val_acc'].values\n loss = data['loss'].values\n val_loss = data['val_loss'].values\n plotData.plot_2d(acc, val_acc, 'epoch', 'accuracy', 'Model Accuracy',\n train_validation, save_plt_accuracy)\n plotData.plot_2d(loss, val_loss, 'epoch', 'loss', 'Model Loss',\n train_validation, save_plt_loss)\n plotData.plot_model_bis(data, save_plt_learning)\n \"\"\"\n # evalute model\n # compile the model\n print(\"==================== compile model ========================\")\n model.compile(loss=model_loss_function, optimizer=model_optimizer_rmsprop, metrics=model_metrics)\n \n \n score = model.evaluate_generator(test_data, num_of_test_samples)\n print('Test Loss:', score[0])\n print('Test accuracy:', score[1])\n \"\"\"\n\n\n<code token>\n",
"<import token>\n<code token>\n<assignment token>\n\n\ndef load_model():\n json_file = open(saved_model_arch_path, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(saved_model_weights_path)\n return loaded_model\n\n\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<code token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,794 | 64b83748490bada2637aa3be5c3be402ca7c0eaa | """Unit tests for reviewboard.reviews.views.DownloadRawDiffView."""
from __future__ import unicode_literals
from reviewboard.testing import TestCase
class DownloadRawDiffViewTests(TestCase):
"""Unit tests for reviewboard.reviews.views.DownloadRawDiffView."""
fixtures = ["test_users", "test_scmtools"]
def test_sends_correct_content_disposition(self):
"""Testing DownloadRawDiffView sends correct Content-Disposition"""
review_request = self.create_review_request(create_repository=True, publish=True)
self.create_diffset(review_request=review_request)
response = self.client.get("/r/%d/diff/raw/" % review_request.pk)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Content-Disposition"], "attachment; filename=diffset")
def test_normalize_commas_in_filename(self):
"""Testing DownloadRawDiffView removes commas in filename"""
review_request = self.create_review_request(create_repository=True, publish=True)
self.create_diffset(review_request=review_request, name="test, comma")
response = self.client.get("/r/%d/diff/raw/" % review_request.pk)
content_disposition = response["Content-Disposition"]
filename = content_disposition[len("attachment; filename=") :]
self.assertFalse("," in filename)
def test_with_commit_history(self):
"""Testing DiffParser.raw_diff with commit history contains only
cumulative diff
"""
review_request = self.create_review_request(create_repository=True, publish=True)
diffset = self.create_diffset(review_request=review_request)
self.create_diffcommit(diffset=diffset, commit_id="r1", parent_id="r0", diff_contents=(b"diff --git a/ABC b/ABC\n" b"index 94bdd3e..197009f 100644\n" b"--- ABC\n" b"+++ ABC\n" b"@@ -1,1 +1,1 @@\n" b"-line!\n" b"+line..\n"))
self.create_diffcommit(diffset=diffset, commit_id="r2", parent_id="r1", diff_contents=(b"diff --git a/README b/README\n" b"index 94bdd3e..197009f 100644\n" b"--- README\n" b"+++ README\n" b"@@ -1,1 +1,1 @@\n" b"-Hello, world!\n" b"+Hi, world!\n"))
self.create_diffcommit(diffset=diffset, commit_id="r4", parent_id="r3", diff_contents=(b"diff --git a/README b/README\n" b"index 197009f..87abad9 100644\n" b"--- README\n" b"+++ README\n" b"@@ -1,1 +1,1 @@\n" b"-Hi, world!\n" b"+Yo, world.\n"))
cumulative_diff = b"diff --git a/ABC b/ABC\n" b"index 94bdd3e..197009f 100644\n" b"--- ABC\n" b"+++ ABC\n" b"@@ -1,1 +1,1 @@\n" b"-line!\n" b"+line..\n" b"diff --git a/README b/README\n" b"index 94bdd3e..87abad9 100644\n" b"--- README\n" b"+++ README\n" b"@@ -1,1 +1,1 @@\n" b"-Hello, world!\n" b"+Yo, world.\n"
diffset.finalize_commit_series(cumulative_diff=cumulative_diff, validation_info=None, validate=False, save=True)
response = self.client.get("/r/%d/diff/raw/" % review_request.pk)
self.assertEqual(response.content, cumulative_diff) | [
"\"\"\"Unit tests for reviewboard.reviews.views.DownloadRawDiffView.\"\"\"\nfrom __future__ import unicode_literals\nfrom reviewboard.testing import TestCase\nclass DownloadRawDiffViewTests(TestCase):\n\t\"\"\"Unit tests for reviewboard.reviews.views.DownloadRawDiffView.\"\"\"\n\tfixtures = [\"test_users\", \"test_scmtools\"]\n\tdef test_sends_correct_content_disposition(self):\n\t\t\"\"\"Testing DownloadRawDiffView sends correct Content-Disposition\"\"\"\n\t\treview_request = self.create_review_request(create_repository=True, publish=True)\n\t\tself.create_diffset(review_request=review_request)\n\t\tresponse = self.client.get(\"/r/%d/diff/raw/\" % review_request.pk)\n\t\tself.assertEqual(response.status_code, 200)\n\t\tself.assertEqual(response[\"Content-Disposition\"], \"attachment; filename=diffset\")\n\tdef test_normalize_commas_in_filename(self):\n\t\t\"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n\t\treview_request = self.create_review_request(create_repository=True, publish=True)\n\t\tself.create_diffset(review_request=review_request, name=\"test, comma\")\n\t\tresponse = self.client.get(\"/r/%d/diff/raw/\" % review_request.pk)\n\t\tcontent_disposition = response[\"Content-Disposition\"]\n\t\tfilename = content_disposition[len(\"attachment; filename=\") :]\n\t\tself.assertFalse(\",\" in filename)\n\tdef test_with_commit_history(self):\n\t\t\"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n\t\treview_request = self.create_review_request(create_repository=True, publish=True)\n\t\tdiffset = self.create_diffset(review_request=review_request)\n\t\tself.create_diffcommit(diffset=diffset, commit_id=\"r1\", parent_id=\"r0\", diff_contents=(b\"diff --git a/ABC b/ABC\\n\" b\"index 94bdd3e..197009f 100644\\n\" b\"--- ABC\\n\" b\"+++ ABC\\n\" b\"@@ -1,1 +1,1 @@\\n\" b\"-line!\\n\" b\"+line..\\n\"))\n\t\tself.create_diffcommit(diffset=diffset, commit_id=\"r2\", parent_id=\"r1\", diff_contents=(b\"diff --git a/README b/README\\n\" b\"index 94bdd3e..197009f 100644\\n\" b\"--- README\\n\" b\"+++ README\\n\" b\"@@ -1,1 +1,1 @@\\n\" b\"-Hello, world!\\n\" b\"+Hi, world!\\n\"))\n\t\tself.create_diffcommit(diffset=diffset, commit_id=\"r4\", parent_id=\"r3\", diff_contents=(b\"diff --git a/README b/README\\n\" b\"index 197009f..87abad9 100644\\n\" b\"--- README\\n\" b\"+++ README\\n\" b\"@@ -1,1 +1,1 @@\\n\" b\"-Hi, world!\\n\" b\"+Yo, world.\\n\"))\n\t\tcumulative_diff = b\"diff --git a/ABC b/ABC\\n\" b\"index 94bdd3e..197009f 100644\\n\" b\"--- ABC\\n\" b\"+++ ABC\\n\" b\"@@ -1,1 +1,1 @@\\n\" b\"-line!\\n\" b\"+line..\\n\" b\"diff --git a/README b/README\\n\" b\"index 94bdd3e..87abad9 100644\\n\" b\"--- README\\n\" b\"+++ README\\n\" b\"@@ -1,1 +1,1 @@\\n\" b\"-Hello, world!\\n\" b\"+Yo, world.\\n\"\n\t\tdiffset.finalize_commit_series(cumulative_diff=cumulative_diff, validation_info=None, validate=False, save=True)\n\t\tresponse = self.client.get(\"/r/%d/diff/raw/\" % review_request.pk)\n\t\tself.assertEqual(response.content, cumulative_diff)",
"<docstring token>\nfrom __future__ import unicode_literals\nfrom reviewboard.testing import TestCase\n\n\nclass DownloadRawDiffViewTests(TestCase):\n \"\"\"Unit tests for reviewboard.reviews.views.DownloadRawDiffView.\"\"\"\n fixtures = ['test_users', 'test_scmtools']\n\n def test_sends_correct_content_disposition(self):\n \"\"\"Testing DownloadRawDiffView sends correct Content-Disposition\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response['Content-Disposition'],\n 'attachment; filename=diffset')\n\n def test_normalize_commas_in_filename(self):\n \"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request, name='test, comma')\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n content_disposition = response['Content-Disposition']\n filename = content_disposition[len('attachment; filename='):]\n self.assertFalse(',' in filename)\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n \"\"\"Unit tests for reviewboard.reviews.views.DownloadRawDiffView.\"\"\"\n fixtures = ['test_users', 'test_scmtools']\n\n def test_sends_correct_content_disposition(self):\n \"\"\"Testing DownloadRawDiffView sends correct Content-Disposition\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response['Content-Disposition'],\n 'attachment; filename=diffset')\n\n def test_normalize_commas_in_filename(self):\n \"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request, name='test, comma')\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n content_disposition = response['Content-Disposition']\n filename = content_disposition[len('attachment; filename='):]\n self.assertFalse(',' in filename)\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n <docstring token>\n fixtures = ['test_users', 'test_scmtools']\n\n def test_sends_correct_content_disposition(self):\n \"\"\"Testing DownloadRawDiffView sends correct Content-Disposition\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response['Content-Disposition'],\n 'attachment; filename=diffset')\n\n def test_normalize_commas_in_filename(self):\n \"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request, name='test, comma')\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n content_disposition = response['Content-Disposition']\n filename = content_disposition[len('attachment; filename='):]\n self.assertFalse(',' in filename)\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n <docstring token>\n <assignment token>\n\n def test_sends_correct_content_disposition(self):\n \"\"\"Testing DownloadRawDiffView sends correct Content-Disposition\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response['Content-Disposition'],\n 'attachment; filename=diffset')\n\n def test_normalize_commas_in_filename(self):\n \"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request, name='test, comma')\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n content_disposition = response['Content-Disposition']\n filename = content_disposition[len('attachment; filename='):]\n self.assertFalse(',' in filename)\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n <docstring token>\n <assignment token>\n <function token>\n\n def test_normalize_commas_in_filename(self):\n \"\"\"Testing DownloadRawDiffView removes commas in filename\"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n self.create_diffset(review_request=review_request, name='test, comma')\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n content_disposition = response['Content-Disposition']\n filename = content_disposition[len('attachment; filename='):]\n self.assertFalse(',' in filename)\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n <docstring token>\n <assignment token>\n <function token>\n <function token>\n\n def test_with_commit_history(self):\n \"\"\"Testing DiffParser.raw_diff with commit history contains only\n cumulative diff\n \"\"\"\n review_request = self.create_review_request(create_repository=True,\n publish=True)\n diffset = self.create_diffset(review_request=review_request)\n self.create_diffcommit(diffset=diffset, commit_id='r1', parent_id=\n 'r0', diff_contents=\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r2', parent_id=\n 'r1', diff_contents=\n b'diff --git a/README b/README\\nindex 94bdd3e..197009f 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Hi, world!\\n'\n )\n self.create_diffcommit(diffset=diffset, commit_id='r4', parent_id=\n 'r3', diff_contents=\n b'diff --git a/README b/README\\nindex 197009f..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hi, world!\\n+Yo, world.\\n'\n )\n cumulative_diff = (\n b'diff --git a/ABC b/ABC\\nindex 94bdd3e..197009f 100644\\n--- ABC\\n+++ ABC\\n@@ -1,1 +1,1 @@\\n-line!\\n+line..\\ndiff --git a/README b/README\\nindex 94bdd3e..87abad9 100644\\n--- README\\n+++ README\\n@@ -1,1 +1,1 @@\\n-Hello, world!\\n+Yo, world.\\n'\n )\n diffset.finalize_commit_series(cumulative_diff=cumulative_diff,\n validation_info=None, validate=False, save=True)\n response = self.client.get('/r/%d/diff/raw/' % review_request.pk)\n self.assertEqual(response.content, cumulative_diff)\n",
"<docstring token>\n<import token>\n\n\nclass DownloadRawDiffViewTests(TestCase):\n <docstring token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<class token>\n"
] | false |
99,795 | 6c3fadf1b68ab396058bdbc8eece895d99ab745f |
import keras
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten
from keras.models import Sequential
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(64,64,1), padding='same', activation='relu'))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Conv2D(128, (3,3), padding='same', activation='relu'))
model.add(Conv2D(128, (3,3), padding='same', activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Conv2D(256, (3,3), padding='same', activation='relu'))
model.add(Conv2D(256, (3,3), padding='same', activation='relu'))
model.add(Conv2D(256, (3,3), padding='same', activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(21, activation='softmax'))
model.summary()
model.load_weights('lenet5_32.h5')
import cv2
import numpy as np
img = cv2.imread('h2.png',0)
img = cv2.resize(img, (32,32))
img = np.reshape(img, (1,32,32,1))
img.shape
p = model.predict(img)
np.argmax(p)
if letter <= 9:
print(letter)
elif letter == 10:
print('অ')
elif letter == 11:
print('আ')
elif letter == 12:
print('ই')
elif letter == 13:
print('ঈ')
elif letter == 14:
print('উ')
elif letter == 15:
print('ঊ')
elif letter == 16:
print('ঋ')
elif letter == 17:
print('এ')
elif letter == 18:
print('ঐ')
elif letter == 19:
print('ও')
else:
print('ঔ')
| [
"\r\n\r\nimport keras\r\nfrom keras.layers import Dense, Conv2D, MaxPool2D, Flatten\r\nfrom keras.models import Sequential\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(32, (5, 5), input_shape=(64,64,1), padding='same', activation='relu'))\r\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\r\nmodel.add(MaxPooling2D((2,2), strides=(2,2)))\r\n\r\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\r\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\r\nmodel.add(MaxPooling2D((2,2), strides=(2,2)))\r\n\r\n\r\nmodel.add(Conv2D(128, (3,3), padding='same', activation='relu'))\r\nmodel.add(Conv2D(128, (3,3), padding='same', activation='relu'))\r\nmodel.add(MaxPooling2D((2,2), strides=(2,2)))\r\n\r\nmodel.add(Conv2D(256, (3,3), padding='same', activation='relu'))\r\nmodel.add(Conv2D(256, (3,3), padding='same', activation='relu'))\r\nmodel.add(Conv2D(256, (3,3), padding='same', activation='relu'))\r\nmodel.add(MaxPooling2D((2,2), strides=(2,2)))\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(64, activation='relu'))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(Dense(21, activation='softmax'))\r\n\r\nmodel.summary()\r\n\r\nmodel.load_weights('lenet5_32.h5')\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread('h2.png',0)\r\nimg = cv2.resize(img, (32,32))\r\nimg = np.reshape(img, (1,32,32,1))\r\nimg.shape\r\n\r\np = model.predict(img)\r\n\r\nnp.argmax(p)\r\n\r\nif letter <= 9:\r\n\tprint(letter)\r\nelif letter == 10:\r\n\tprint('অ')\r\nelif letter == 11:\r\n\tprint('আ')\r\nelif letter == 12:\r\n\tprint('ই')\r\nelif letter == 13:\r\n\tprint('ঈ')\r\nelif letter == 14:\r\n\tprint('উ')\r\nelif letter == 15:\r\n\tprint('ঊ')\r\nelif letter == 16:\r\n\tprint('ঋ')\r\nelif letter == 17:\r\n\tprint('এ')\r\nelif letter == 18:\r\n\tprint('ঐ')\r\nelif letter == 19:\r\n\tprint('ও')\r\nelse:\r\n\tprint('ঔ')\r\n\r\n",
"import keras\nfrom keras.layers import Dense, Conv2D, MaxPool2D, Flatten\nfrom keras.models import Sequential\nmodel = Sequential()\nmodel.add(Conv2D(32, (5, 5), input_shape=(64, 64, 1), padding='same',\n activation='relu'))\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(21, activation='softmax'))\nmodel.summary()\nmodel.load_weights('lenet5_32.h5')\nimport cv2\nimport numpy as np\nimg = cv2.imread('h2.png', 0)\nimg = cv2.resize(img, (32, 32))\nimg = np.reshape(img, (1, 32, 32, 1))\nimg.shape\np = model.predict(img)\nnp.argmax(p)\nif letter <= 9:\n print(letter)\nelif letter == 10:\n print('অ')\nelif letter == 11:\n print('আ')\nelif letter == 12:\n print('ই')\nelif letter == 13:\n print('ঈ')\nelif letter == 14:\n print('উ')\nelif letter == 15:\n print('ঊ')\nelif letter == 16:\n print('ঋ')\nelif letter == 17:\n print('এ')\nelif letter == 18:\n print('ঐ')\nelif letter == 19:\n print('ও')\nelse:\n print('ঔ')\n",
"<import token>\nmodel = Sequential()\nmodel.add(Conv2D(32, (5, 5), input_shape=(64, 64, 1), padding='same',\n activation='relu'))\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(21, activation='softmax'))\nmodel.summary()\nmodel.load_weights('lenet5_32.h5')\n<import token>\nimg = cv2.imread('h2.png', 0)\nimg = cv2.resize(img, (32, 32))\nimg = np.reshape(img, (1, 32, 32, 1))\nimg.shape\np = model.predict(img)\nnp.argmax(p)\nif letter <= 9:\n print(letter)\nelif letter == 10:\n print('অ')\nelif letter == 11:\n print('আ')\nelif letter == 12:\n print('ই')\nelif letter == 13:\n print('ঈ')\nelif letter == 14:\n print('উ')\nelif letter == 15:\n print('ঊ')\nelif letter == 16:\n print('ঋ')\nelif letter == 17:\n print('এ')\nelif letter == 18:\n print('ঐ')\nelif letter == 19:\n print('ও')\nelse:\n print('ঔ')\n",
"<import token>\n<assignment token>\nmodel.add(Conv2D(32, (5, 5), input_shape=(64, 64, 1), padding='same',\n activation='relu'))\nmodel.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(21, activation='softmax'))\nmodel.summary()\nmodel.load_weights('lenet5_32.h5')\n<import token>\n<assignment token>\nimg.shape\n<assignment token>\nnp.argmax(p)\nif letter <= 9:\n print(letter)\nelif letter == 10:\n print('অ')\nelif letter == 11:\n print('আ')\nelif letter == 12:\n print('ই')\nelif letter == 13:\n print('ঈ')\nelif letter == 14:\n print('উ')\nelif letter == 15:\n print('ঊ')\nelif letter == 16:\n print('ঋ')\nelif letter == 17:\n print('এ')\nelif letter == 18:\n print('ঐ')\nelif letter == 19:\n print('ও')\nelse:\n print('ঔ')\n",
"<import token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,796 | 35a314acf90f6b68e88b3518ee546d438ff90ccd | from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
planes = Image.open("a330-300.png")
im1 = planes.convert('L')
wc = Image.open("WC.png")
im2 = wc.convert('L')
width, height = im1.size
width1, height1 = im2.size
img = []
n = 0
plt.figure("图片列表")
for x in range(0, width, width1):
for y in range(0, height, height1):
box = (width, height, width + width1, height + height1)
roi = planes.crop(box)
n += 1
plt.subplot(204,10,n),plt.title(str(n))
plt.imshow(roi)
plt.show()
print(n)
# p = np.array(im1)
# # q = np.array(im2)
# print(im1.size,im2.size)
| [
"from PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplanes = Image.open(\"a330-300.png\")\nim1 = planes.convert('L')\nwc = Image.open(\"WC.png\")\nim2 = wc.convert('L')\nwidth, height = im1.size\nwidth1, height1 = im2.size\n\nimg = []\n\nn = 0\n\nplt.figure(\"图片列表\")\n\nfor x in range(0, width, width1):\n for y in range(0, height, height1):\n box = (width, height, width + width1, height + height1)\n roi = planes.crop(box)\n n += 1\n\n plt.subplot(204,10,n),plt.title(str(n))\n plt.imshow(roi)\nplt.show()\nprint(n)\n\n\n# p = np.array(im1)\n# # q = np.array(im2)\n# print(im1.size,im2.size)\n",
"from PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nplanes = Image.open('a330-300.png')\nim1 = planes.convert('L')\nwc = Image.open('WC.png')\nim2 = wc.convert('L')\nwidth, height = im1.size\nwidth1, height1 = im2.size\nimg = []\nn = 0\nplt.figure('图片列表')\nfor x in range(0, width, width1):\n for y in range(0, height, height1):\n box = width, height, width + width1, height + height1\n roi = planes.crop(box)\n n += 1\n plt.subplot(204, 10, n), plt.title(str(n))\n plt.imshow(roi)\nplt.show()\nprint(n)\n",
"<import token>\nplanes = Image.open('a330-300.png')\nim1 = planes.convert('L')\nwc = Image.open('WC.png')\nim2 = wc.convert('L')\nwidth, height = im1.size\nwidth1, height1 = im2.size\nimg = []\nn = 0\nplt.figure('图片列表')\nfor x in range(0, width, width1):\n for y in range(0, height, height1):\n box = width, height, width + width1, height + height1\n roi = planes.crop(box)\n n += 1\n plt.subplot(204, 10, n), plt.title(str(n))\n plt.imshow(roi)\nplt.show()\nprint(n)\n",
"<import token>\n<assignment token>\nplt.figure('图片列表')\nfor x in range(0, width, width1):\n for y in range(0, height, height1):\n box = width, height, width + width1, height + height1\n roi = planes.crop(box)\n n += 1\n plt.subplot(204, 10, n), plt.title(str(n))\n plt.imshow(roi)\nplt.show()\nprint(n)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,797 | ad579ebf240c1f0b357b5e4d4d0545001e638806 | from web3 import Web3
from pygame import mixer
w3 = Web3(Web3.HTTPProvider('https://rinkeby.infura.io/v3/a642f65a7de84bc19cc01c4da5b6a1bb'))
ABI = """[{"inputs":[],"stateMutability":"payable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"id","type":"string"}],"name":"NewSwitch","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"id","type":"string"}],"name":"SwitchOff","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"id","type":"string"}],"name":"SwitchOn","type":"event"},{"inputs":[{"internalType":"string","name":"id","type":"string"}],"name":"AmountToEnable","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"id","type":"string"}],"name":"CreateSwitch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"id","type":"string"}],"name":"IsOn","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"newOwner","type":"address"}],"name":"TransferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"id","type":"string"}],"name":"VoteOff","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"string","name":"id","type":"string"}],"name":"VoteOn","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"}]"""
contract = w3.eth.contract("0xD0d86636E4b9a789075fC579A737fAA39C37eb4d", abi=ABI)
isOn = True
isMusicPlaying = True
mixer.init()
mixer.music.load('audio.mp3')
mixer.music.play()
while True:
isOn = contract.functions.IsOn("c").call()
if isOn != isMusicPlaying:
if isOn:
mixer.music.play()
isMusicPlaying = True
else:
mixer.music.stop()
isMusicPlaying = False
| [
"from web3 import Web3\nfrom pygame import mixer\n\nw3 = Web3(Web3.HTTPProvider('https://rinkeby.infura.io/v3/a642f65a7de84bc19cc01c4da5b6a1bb'))\nABI = \"\"\"[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"NewSwitch\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOff\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOn\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"AmountToEnable\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"CreateSwitch\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"IsOn\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"TransferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOff\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOn\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address payable\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]\"\"\"\ncontract = w3.eth.contract(\"0xD0d86636E4b9a789075fC579A737fAA39C37eb4d\", abi=ABI)\n\nisOn = True\nisMusicPlaying = True\nmixer.init()\nmixer.music.load('audio.mp3')\nmixer.music.play()\nwhile True:\n isOn = contract.functions.IsOn(\"c\").call()\n if isOn != isMusicPlaying:\n\n if isOn:\n mixer.music.play()\n isMusicPlaying = True\n else:\n mixer.music.stop()\n isMusicPlaying = False\n",
"from web3 import Web3\nfrom pygame import mixer\nw3 = Web3(Web3.HTTPProvider(\n 'https://rinkeby.infura.io/v3/a642f65a7de84bc19cc01c4da5b6a1bb'))\nABI = (\n '[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"NewSwitch\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOff\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOn\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"AmountToEnable\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"CreateSwitch\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"IsOn\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"TransferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOff\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOn\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address payable\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]'\n )\ncontract = w3.eth.contract('0xD0d86636E4b9a789075fC579A737fAA39C37eb4d',\n abi=ABI)\nisOn = True\nisMusicPlaying = True\nmixer.init()\nmixer.music.load('audio.mp3')\nmixer.music.play()\nwhile True:\n isOn = contract.functions.IsOn('c').call()\n if isOn != isMusicPlaying:\n if isOn:\n mixer.music.play()\n isMusicPlaying = True\n else:\n mixer.music.stop()\n isMusicPlaying = False\n",
"<import token>\nw3 = Web3(Web3.HTTPProvider(\n 'https://rinkeby.infura.io/v3/a642f65a7de84bc19cc01c4da5b6a1bb'))\nABI = (\n '[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"NewSwitch\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOff\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"SwitchOn\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"AmountToEnable\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"CreateSwitch\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"IsOn\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"TransferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOff\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"VoteOn\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address payable\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]'\n )\ncontract = w3.eth.contract('0xD0d86636E4b9a789075fC579A737fAA39C37eb4d',\n abi=ABI)\nisOn = True\nisMusicPlaying = True\nmixer.init()\nmixer.music.load('audio.mp3')\nmixer.music.play()\nwhile True:\n isOn = contract.functions.IsOn('c').call()\n if isOn != isMusicPlaying:\n if isOn:\n mixer.music.play()\n isMusicPlaying = True\n else:\n mixer.music.stop()\n isMusicPlaying = False\n",
"<import token>\n<assignment token>\nmixer.init()\nmixer.music.load('audio.mp3')\nmixer.music.play()\nwhile True:\n isOn = contract.functions.IsOn('c').call()\n if isOn != isMusicPlaying:\n if isOn:\n mixer.music.play()\n isMusicPlaying = True\n else:\n mixer.music.stop()\n isMusicPlaying = False\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,798 | 04eea62b05ed74fed44a5546b5c75da275d9170e | #!/usr/bin/env python
# __author__ = 'mannea'
#
import sys
import os
if len(sys.argv) != 3:
print "fsplit <in file> <number of files>"
sys.exit(0)
in_file = sys.argv[1].strip()
split_lines = sys.argv[2].strip()
file_lines = sum(1 for line in open(in_file))
new_lines = (int(float(file_lines)) / int(float(split_lines)))
print('File: ' + in_file + 'New Lines per file: ' + str(new_lines))
os.system("split -d --verbose -l %s %s %s" % (new_lines, in_file, in_file + '.')) | [
"#!/usr/bin/env python\n# __author__ = 'mannea'\n#\nimport sys\nimport os\n\nif len(sys.argv) != 3:\n print \"fsplit <in file> <number of files>\"\n sys.exit(0)\n\nin_file = sys.argv[1].strip()\nsplit_lines = sys.argv[2].strip()\n\nfile_lines = sum(1 for line in open(in_file))\nnew_lines = (int(float(file_lines)) / int(float(split_lines)))\nprint('File: ' + in_file + 'New Lines per file: ' + str(new_lines))\nos.system(\"split -d --verbose -l %s %s %s\" % (new_lines, in_file, in_file + '.'))"
] | true |
99,799 | 6998c4df852ff981bc44c08600ddc38bcbf97d4f | import re
import subprocess
from glob import glob
from os.path import join
from typing import Dict, List, Optional
import cv2
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
def run_shell_script(file_name: str) -> None:
"""
A function run *.sh script. It assumes the file is in the current directory.
Args:
file_name: str
Returns:None
"""
cmd = ["./" + file_name]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b""):
print(">>> " + line.decode().rstrip())
def get_image_names(file_path: str) -> List:
"""
A function to read file that contain all the images and return the names in a list.
Args:
file_path: str
Returns: A List
"""
name_list = []
f = open(file_path, "r")
lines = f.readlines()
f.close()
for line in lines:
name = line.split("/")[-1].replace("\n", "")
name_list.append(name)
return name_list
def get_img_index(pred_result: List) -> List:
"""
A function to get the index of each image, so downstream function could split information accordingly.
Args:
pred_result: List
Returns: A list.
"""
img_index = []
for i, line in enumerate(pred_result):
match = re.search("\./test_pics/", line)
if match:
img_index.append(i)
if i == len(pred_result) - 1:
img_index.append(i)
return img_index
def find_bbox(pred_file_path: str, train_file_path: str) -> Dict:
"""
A function to
- Check if the number of testing images are equal to the number of prediction results.
- Loop through the output of Yolo prediction .txt file
- Create a dictionary for each image, use the image name as key and bbox information as value.
Args:
pred_file_path: str
train_file_path: str
Returns: A dictionary
"""
f_pred = open(pred_file_path, "r")
pred_result = f_pred.readlines()
f_pred.close()
img_index = get_img_index(pred_result)
img_names = get_image_names(train_file_path)
if len(img_index) - 1 != len(img_names):
return "There is mismatch between the number of predictions and the number of images."
# Create dictionary with the img name as the key and the bbox information as values.
target_labels = ["TableCaption", "TableBody", "TableFootnote", "Paragraph", "Table"]
result = {}
for i, name in enumerate(img_names):
key = name
start = img_index[i] + 1
end = img_index[i + 1]
unfiltered_value = pred_result[start:end]
filtered_value = [
v for v in unfiltered_value if v.split(":")[0] in target_labels
]
result[key] = filtered_value
return result
def create_train_file(img_folder_path: str, train_file_path: str) -> None:
"""
A function to find all the images in a directory and create a .txt file that contains all the images path in the
target directory (train_file_path).
Args:
img_folder_path: str
train_file_path: str
Returns: None
"""
files = []
for ext in ("*.gif", "*.png", "*.jpg", "*.bmp"):
img_path = glob(join(img_folder_path, ext))
if img_path:
files.extend(img_path)
write_to_train_file(files, train_file_path)
print("Training files are created in " + img_folder_path)
def write_to_train_file(files: List, train_file_path: str) -> None:
"""
A function to create files in the targe directory.
Args:
files:List
train_file_path:str
Returns: None
"""
f = open(train_file_path, "w")
text_to_save = ""
for i, img_path in enumerate(files):
img_path_stripped = img_path.replace("/darknet", "")
if i == len(files) - 1:
text_to_save += img_path_stripped
else:
text_to_save += img_path_stripped + "\n"
f.write(text_to_save)
f.close()
def draw_pic(img_path: str, bbox: List) -> None:
"""
A function to visualize bbox in an image.
Args:
img_path: str
bbox: list
Returns: None
"""
img = cv2.imread(img_path)
for v in bbox:
x, y, w, h = v[2]
cv2.rectangle(
img, (int(x), int(y)), (int(x) + int(w), int(y) + int(h)), (255, 0, 0), 2
)
figure(num=None, figsize=(20, 15))
plt.imshow(img)
plt.show()
def process_pred_list(pred_list: List) -> List:
"""
A function to convert the list of predictions to a list that contains specific data format for bbox visualization.
Args:
pred_list: list
Returns: list [label, confidence, bbox]
"""
result = []
for item in pred_list:
item_replace_special_char = item.replace("\n", "")
meta_data = item_replace_special_char.split(":")
label = meta_data[0]
confidence = float(meta_data[1].split("\t")[0].strip(" ").strip("%")) / 100
bbox_info = meta_data[2:]
bbox = get_bbox(bbox_info)
result.append([label, confidence, bbox])
return result
def get_bbox(meta_data: List) -> List:
"""
A function to get the coordinates of the bbox.
Args:
meta_data: A list
Returns: A list of [x, y, w, h]
"""
x = [v for v in meta_data[0].split(" ") if v][0]
y = [v for v in meta_data[1].split(" ") if v][0]
w = [v for v in meta_data[2].split(" ") if v][0]
h = meta_data[3].replace(")", "").strip(" ")
return [x, y, w, h]
def show_pred(
img_name: str,
pred_file_path: str,
train_file_path: str,
img_folder_path: str,
confidence: Optional[float] = None,
label: Optional[str] = None,
) -> None:
"""
A function to visualize predicted bbox in the original images.
Args:
img_name: str
pred_file_path: str
train_file_path: str
img_folder_path: str
confidence: float
label: str
Returns: None. Print images in notebook
"""
pred_result = find_bbox(pred_file_path, train_file_path)
pred_list = pred_result[img_name]
result = process_pred_list(pred_list)
img_path = img_folder_path + img_name
if confidence:
result = [v for v in result if v[1] > confidence]
if label:
result = [v for v in result if v[0].lower() == label.lower()]
draw_pic(img_path, result)
else:
draw_pic(img_path, result)
| [
"import re\nimport subprocess\nfrom glob import glob\nfrom os.path import join\nfrom typing import Dict, List, Optional\n\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom matplotlib.pyplot import figure\n\n\ndef run_shell_script(file_name: str) -> None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = [\"./\" + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n for line in iter(p.stdout.readline, b\"\"):\n print(\">>> \" + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) -> List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, \"r\")\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split(\"/\")[-1].replace(\"\\n\", \"\")\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) -> List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n\n for i, line in enumerate(pred_result):\n match = re.search(\"\\./test_pics/\", line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\ndef find_bbox(pred_file_path: str, train_file_path: str) -> Dict:\n \"\"\"\n A function to\n - Check if the number of testing images are equal to the number of prediction results.\n - Loop through the output of Yolo prediction .txt file\n - Create a dictionary for each image, use the image name as key and bbox information as value.\n\n Args:\n pred_file_path: str\n train_file_path: str\n\n Returns: A dictionary\n\n \"\"\"\n\n f_pred = open(pred_file_path, \"r\")\n pred_result = f_pred.readlines()\n f_pred.close()\n\n img_index = get_img_index(pred_result)\n\n img_names = get_image_names(train_file_path)\n\n if len(img_index) - 1 != len(img_names):\n return \"There is mismatch between the number of predictions and the number of images.\"\n\n # Create dictionary with the img name as the key and the bbox information as values.\n target_labels = [\"TableCaption\", \"TableBody\", \"TableFootnote\", \"Paragraph\", \"Table\"]\n result = {}\n for i, name in enumerate(img_names):\n key = name\n start = img_index[i] + 1\n end = img_index[i + 1]\n unfiltered_value = pred_result[start:end]\n filtered_value = [\n v for v in unfiltered_value if v.split(\":\")[0] in target_labels\n ]\n result[key] = filtered_value\n\n return result\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) -> None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in (\"*.gif\", \"*.png\", \"*.jpg\", \"*.bmp\"):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n\n write_to_train_file(files, train_file_path)\n\n print(\"Training files are created in \" + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) -> None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, \"w\")\n text_to_save = \"\"\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace(\"/darknet\", \"\")\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + \"\\n\"\n\n f.write(text_to_save)\n f.close()\n\n\ndef draw_pic(img_path: str, bbox: List) -> None:\n \"\"\"\n A function to visualize bbox in an image.\n Args:\n img_path: str\n bbox: list\n\n Returns: None\n\n \"\"\"\n img = cv2.imread(img_path)\n\n for v in bbox:\n x, y, w, h = v[2]\n cv2.rectangle(\n img, (int(x), int(y)), (int(x) + int(w), int(y) + int(h)), (255, 0, 0), 2\n )\n\n figure(num=None, figsize=(20, 15))\n plt.imshow(img)\n plt.show()\n\n\ndef process_pred_list(pred_list: List) -> List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace(\"\\n\", \"\")\n meta_data = item_replace_special_char.split(\":\")\n label = meta_data[0]\n confidence = float(meta_data[1].split(\"\\t\")[0].strip(\" \").strip(\"%\")) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\ndef get_bbox(meta_data: List) -> List:\n \"\"\"\n A function to get the coordinates of the bbox.\n Args:\n meta_data: A list\n\n Returns: A list of [x, y, w, h]\n\n \"\"\"\n\n x = [v for v in meta_data[0].split(\" \") if v][0]\n y = [v for v in meta_data[1].split(\" \") if v][0]\n w = [v for v in meta_data[2].split(\" \") if v][0]\n h = meta_data[3].replace(\")\", \"\").strip(\" \")\n\n return [x, y, w, h]\n\n\ndef show_pred(\n img_name: str,\n pred_file_path: str,\n train_file_path: str,\n img_folder_path: str,\n confidence: Optional[float] = None,\n label: Optional[str] = None,\n) -> None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n\n img_path = img_folder_path + img_name\n\n if confidence:\n result = [v for v in result if v[1] > confidence]\n\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"import re\nimport subprocess\nfrom glob import glob\nfrom os.path import join\nfrom typing import Dict, List, Optional\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom matplotlib.pyplot import figure\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\ndef find_bbox(pred_file_path: str, train_file_path: str) ->Dict:\n \"\"\"\n A function to\n - Check if the number of testing images are equal to the number of prediction results.\n - Loop through the output of Yolo prediction .txt file\n - Create a dictionary for each image, use the image name as key and bbox information as value.\n\n Args:\n pred_file_path: str\n train_file_path: str\n\n Returns: A dictionary\n\n \"\"\"\n f_pred = open(pred_file_path, 'r')\n pred_result = f_pred.readlines()\n f_pred.close()\n img_index = get_img_index(pred_result)\n img_names = get_image_names(train_file_path)\n if len(img_index) - 1 != len(img_names):\n return (\n 'There is mismatch between the number of predictions and the number of images.'\n )\n target_labels = ['TableCaption', 'TableBody', 'TableFootnote',\n 'Paragraph', 'Table']\n result = {}\n for i, name in enumerate(img_names):\n key = name\n start = img_index[i] + 1\n end = img_index[i + 1]\n unfiltered_value = pred_result[start:end]\n filtered_value = [v for v in unfiltered_value if v.split(':')[0] in\n target_labels]\n result[key] = filtered_value\n return result\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) ->None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in ('*.gif', '*.png', '*.jpg', '*.bmp'):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n write_to_train_file(files, train_file_path)\n print('Training files are created in ' + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\ndef draw_pic(img_path: str, bbox: List) ->None:\n \"\"\"\n A function to visualize bbox in an image.\n Args:\n img_path: str\n bbox: list\n\n Returns: None\n\n \"\"\"\n img = cv2.imread(img_path)\n for v in bbox:\n x, y, w, h = v[2]\n cv2.rectangle(img, (int(x), int(y)), (int(x) + int(w), int(y) + int\n (h)), (255, 0, 0), 2)\n figure(num=None, figsize=(20, 15))\n plt.imshow(img)\n plt.show()\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\ndef get_bbox(meta_data: List) ->List:\n \"\"\"\n A function to get the coordinates of the bbox.\n Args:\n meta_data: A list\n\n Returns: A list of [x, y, w, h]\n\n \"\"\"\n x = [v for v in meta_data[0].split(' ') if v][0]\n y = [v for v in meta_data[1].split(' ') if v][0]\n w = [v for v in meta_data[2].split(' ') if v][0]\n h = meta_data[3].replace(')', '').strip(' ')\n return [x, y, w, h]\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\ndef find_bbox(pred_file_path: str, train_file_path: str) ->Dict:\n \"\"\"\n A function to\n - Check if the number of testing images are equal to the number of prediction results.\n - Loop through the output of Yolo prediction .txt file\n - Create a dictionary for each image, use the image name as key and bbox information as value.\n\n Args:\n pred_file_path: str\n train_file_path: str\n\n Returns: A dictionary\n\n \"\"\"\n f_pred = open(pred_file_path, 'r')\n pred_result = f_pred.readlines()\n f_pred.close()\n img_index = get_img_index(pred_result)\n img_names = get_image_names(train_file_path)\n if len(img_index) - 1 != len(img_names):\n return (\n 'There is mismatch between the number of predictions and the number of images.'\n )\n target_labels = ['TableCaption', 'TableBody', 'TableFootnote',\n 'Paragraph', 'Table']\n result = {}\n for i, name in enumerate(img_names):\n key = name\n start = img_index[i] + 1\n end = img_index[i + 1]\n unfiltered_value = pred_result[start:end]\n filtered_value = [v for v in unfiltered_value if v.split(':')[0] in\n target_labels]\n result[key] = filtered_value\n return result\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) ->None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in ('*.gif', '*.png', '*.jpg', '*.bmp'):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n write_to_train_file(files, train_file_path)\n print('Training files are created in ' + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\ndef draw_pic(img_path: str, bbox: List) ->None:\n \"\"\"\n A function to visualize bbox in an image.\n Args:\n img_path: str\n bbox: list\n\n Returns: None\n\n \"\"\"\n img = cv2.imread(img_path)\n for v in bbox:\n x, y, w, h = v[2]\n cv2.rectangle(img, (int(x), int(y)), (int(x) + int(w), int(y) + int\n (h)), (255, 0, 0), 2)\n figure(num=None, figsize=(20, 15))\n plt.imshow(img)\n plt.show()\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\ndef get_bbox(meta_data: List) ->List:\n \"\"\"\n A function to get the coordinates of the bbox.\n Args:\n meta_data: A list\n\n Returns: A list of [x, y, w, h]\n\n \"\"\"\n x = [v for v in meta_data[0].split(' ') if v][0]\n y = [v for v in meta_data[1].split(' ') if v][0]\n w = [v for v in meta_data[2].split(' ') if v][0]\n h = meta_data[3].replace(')', '').strip(' ')\n return [x, y, w, h]\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\ndef find_bbox(pred_file_path: str, train_file_path: str) ->Dict:\n \"\"\"\n A function to\n - Check if the number of testing images are equal to the number of prediction results.\n - Loop through the output of Yolo prediction .txt file\n - Create a dictionary for each image, use the image name as key and bbox information as value.\n\n Args:\n pred_file_path: str\n train_file_path: str\n\n Returns: A dictionary\n\n \"\"\"\n f_pred = open(pred_file_path, 'r')\n pred_result = f_pred.readlines()\n f_pred.close()\n img_index = get_img_index(pred_result)\n img_names = get_image_names(train_file_path)\n if len(img_index) - 1 != len(img_names):\n return (\n 'There is mismatch between the number of predictions and the number of images.'\n )\n target_labels = ['TableCaption', 'TableBody', 'TableFootnote',\n 'Paragraph', 'Table']\n result = {}\n for i, name in enumerate(img_names):\n key = name\n start = img_index[i] + 1\n end = img_index[i + 1]\n unfiltered_value = pred_result[start:end]\n filtered_value = [v for v in unfiltered_value if v.split(':')[0] in\n target_labels]\n result[key] = filtered_value\n return result\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) ->None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in ('*.gif', '*.png', '*.jpg', '*.bmp'):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n write_to_train_file(files, train_file_path)\n print('Training files are created in ' + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\ndef get_bbox(meta_data: List) ->List:\n \"\"\"\n A function to get the coordinates of the bbox.\n Args:\n meta_data: A list\n\n Returns: A list of [x, y, w, h]\n\n \"\"\"\n x = [v for v in meta_data[0].split(' ') if v][0]\n y = [v for v in meta_data[1].split(' ') if v][0]\n w = [v for v in meta_data[2].split(' ') if v][0]\n h = meta_data[3].replace(')', '').strip(' ')\n return [x, y, w, h]\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\n<function token>\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) ->None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in ('*.gif', '*.png', '*.jpg', '*.bmp'):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n write_to_train_file(files, train_file_path)\n print('Training files are created in ' + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\ndef get_bbox(meta_data: List) ->List:\n \"\"\"\n A function to get the coordinates of the bbox.\n Args:\n meta_data: A list\n\n Returns: A list of [x, y, w, h]\n\n \"\"\"\n x = [v for v in meta_data[0].split(' ') if v][0]\n y = [v for v in meta_data[1].split(' ') if v][0]\n w = [v for v in meta_data[2].split(' ') if v][0]\n h = meta_data[3].replace(')', '').strip(' ')\n return [x, y, w, h]\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\n<function token>\n\n\ndef create_train_file(img_folder_path: str, train_file_path: str) ->None:\n \"\"\"\n A function to find all the images in a directory and create a .txt file that contains all the images path in the\n target directory (train_file_path).\n Args:\n img_folder_path: str\n train_file_path: str\n\n Returns: None\n\n \"\"\"\n files = []\n for ext in ('*.gif', '*.png', '*.jpg', '*.bmp'):\n img_path = glob(join(img_folder_path, ext))\n if img_path:\n files.extend(img_path)\n write_to_train_file(files, train_file_path)\n print('Training files are created in ' + img_folder_path)\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\ndef get_img_index(pred_result: List) ->List:\n \"\"\"\n A function to get the index of each image, so downstream function could split information accordingly.\n Args:\n pred_result: List\n\n Returns: A list.\n\n \"\"\"\n img_index = []\n for i, line in enumerate(pred_result):\n match = re.search('\\\\./test_pics/', line)\n if match:\n img_index.append(i)\n if i == len(pred_result) - 1:\n img_index.append(i)\n return img_index\n\n\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n\n\ndef run_shell_script(file_name: str) ->None:\n \"\"\"\n A function run *.sh script. It assumes the file is in the current directory.\n Args:\n file_name: str\n\n Returns:None\n\n \"\"\"\n cmd = ['./' + file_name]\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in iter(p.stdout.readline, b''):\n print('>>> ' + line.decode().rstrip())\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n<function token>\n\n\ndef get_image_names(file_path: str) ->List:\n \"\"\"\n A function to read file that contain all the images and return the names in a list.\n Args:\n file_path: str\n\n Returns: A List\n\n \"\"\"\n name_list = []\n f = open(file_path, 'r')\n lines = f.readlines()\n f.close()\n for line in lines:\n name = line.split('/')[-1].replace('\\n', '')\n name_list.append(name)\n return name_list\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n\n\ndef show_pred(img_name: str, pred_file_path: str, train_file_path: str,\n img_folder_path: str, confidence: Optional[float]=None, label: Optional\n [str]=None) ->None:\n \"\"\"\n A function to visualize predicted bbox in the original images.\n Args:\n img_name: str\n pred_file_path: str\n train_file_path: str\n img_folder_path: str\n confidence: float\n label: str\n\n Returns: None. Print images in notebook\n\n \"\"\"\n pred_result = find_bbox(pred_file_path, train_file_path)\n pred_list = pred_result[img_name]\n result = process_pred_list(pred_list)\n img_path = img_folder_path + img_name\n if confidence:\n result = [v for v in result if v[1] > confidence]\n if label:\n result = [v for v in result if v[0].lower() == label.lower()]\n draw_pic(img_path, result)\n else:\n draw_pic(img_path, result)\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n\n\ndef process_pred_list(pred_list: List) ->List:\n \"\"\"\n A function to convert the list of predictions to a list that contains specific data format for bbox visualization.\n Args:\n pred_list: list\n\n Returns: list [label, confidence, bbox]\n\n \"\"\"\n result = []\n for item in pred_list:\n item_replace_special_char = item.replace('\\n', '')\n meta_data = item_replace_special_char.split(':')\n label = meta_data[0]\n confidence = float(meta_data[1].split('\\t')[0].strip(' ').strip('%')\n ) / 100\n bbox_info = meta_data[2:]\n bbox = get_bbox(bbox_info)\n result.append([label, confidence, bbox])\n return result\n\n\n<function token>\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef write_to_train_file(files: List, train_file_path: str) ->None:\n \"\"\"\n A function to create files in the targe directory.\n Args:\n files:List\n train_file_path:str\n\n Returns: None\n\n \"\"\"\n f = open(train_file_path, 'w')\n text_to_save = ''\n for i, img_path in enumerate(files):\n img_path_stripped = img_path.replace('/darknet', '')\n if i == len(files) - 1:\n text_to_save += img_path_stripped\n else:\n text_to_save += img_path_stripped + '\\n'\n f.write(text_to_save)\n f.close()\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.