index
int64 0
100k
| blob_id
stringlengths 40
40
| code
stringlengths 7
7.27M
| steps
sequencelengths 1
1.25k
| error
bool 2
classes |
---|---|---|---|---|
99,900 | 6ecbe2d74c2996b804b3102329f59e9e32d278c9 | SPARSE = 'Sparse_word'
PADDING = 'Padding'
TRUE = 'true'
FALSE = 'false'
DISEASE = 'disease'
CHEMICAL = 'chemical'
GENE = 'gene'
E1_B = 'entity1begin'
E1_E = 'entity1end'
E2_B = 'entity2begin'
E2_E = 'entity2end' | [
"SPARSE = 'Sparse_word'\nPADDING = 'Padding'\n\nTRUE = 'true'\nFALSE = 'false'\n\nDISEASE = 'disease'\nCHEMICAL = 'chemical'\nGENE = 'gene'\n\nE1_B = 'entity1begin'\nE1_E = 'entity1end'\nE2_B = 'entity2begin'\nE2_E = 'entity2end'",
"SPARSE = 'Sparse_word'\nPADDING = 'Padding'\nTRUE = 'true'\nFALSE = 'false'\nDISEASE = 'disease'\nCHEMICAL = 'chemical'\nGENE = 'gene'\nE1_B = 'entity1begin'\nE1_E = 'entity1end'\nE2_B = 'entity2begin'\nE2_E = 'entity2end'\n",
"<assignment token>\n"
] | false |
99,901 | 8d3b4bd3b34dd168634cf24443244c33962291f8 | from . import db
from app.models.permiso_usuario_horario import Permiso_usuario_horario
from sqlalchemy import *
from app.models.grupo import Grupo
class Grupo_alumno_horario(db.Model):
__tablename__ = 'grupo_alumno_horario'
grupo = db.relationship(Grupo,backref = __tablename__,lazy=True)
usuario_horario = db.relationship(Permiso_usuario_horario,backref = __tablename__,lazy=True)
id_grupo = db.Column('ID_GRUPO',db.ForeignKey(Grupo.id_grupo),primary_key =True)
id_horario = db.Column('ID_HORARIO',db.Integer,primary_key= True)
id_usuario = db.Column('ID_USUARIO',db.Integer,primary_key =True)
__table_args__ = (
db.ForeignKeyConstraint(
['ID_HORARIO','ID_USUARIO'],
[Permiso_usuario_horario.id_horario,Permiso_usuario_horario.id_usuario]
),
)
def addOne(self,obj):
db.session.add(obj)
db.session.flush()
db.session.commit()
return
@classmethod
def getAll(self,idGrupo):
return Grupo_alumno_horario.query.filter_by(id_grupo = idGrupo)
@classmethod
def getAllGeneral(self,idHorario):
l = db.session.query(Grupo_alumno_horario,Grupo).join(Grupo).filter( and_(Grupo_alumno_horario.id_horario == idHorario,Grupo.flg_grupo_general == 1) )
return l | [
"from . import db\nfrom app.models.permiso_usuario_horario import Permiso_usuario_horario \nfrom sqlalchemy import *\nfrom app.models.grupo import Grupo\nclass Grupo_alumno_horario(db.Model):\n __tablename__ = 'grupo_alumno_horario'\n grupo = db.relationship(Grupo,backref = __tablename__,lazy=True)\n usuario_horario = db.relationship(Permiso_usuario_horario,backref = __tablename__,lazy=True)\n\n id_grupo = db.Column('ID_GRUPO',db.ForeignKey(Grupo.id_grupo),primary_key =True)\n id_horario = db.Column('ID_HORARIO',db.Integer,primary_key= True)\n id_usuario = db.Column('ID_USUARIO',db.Integer,primary_key =True)\n \n __table_args__ = (\n db.ForeignKeyConstraint(\n ['ID_HORARIO','ID_USUARIO'],\n [Permiso_usuario_horario.id_horario,Permiso_usuario_horario.id_usuario]\n ),\n )\n\n def addOne(self,obj):\n db.session.add(obj)\n db.session.flush()\n db.session.commit()\n return \n\n @classmethod\n def getAll(self,idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo = idGrupo)\n\n @classmethod\n def getAllGeneral(self,idHorario):\n l = db.session.query(Grupo_alumno_horario,Grupo).join(Grupo).filter( and_(Grupo_alumno_horario.id_horario == idHorario,Grupo.flg_grupo_general == 1) )\n \n return l",
"from . import db\nfrom app.models.permiso_usuario_horario import Permiso_usuario_horario\nfrom sqlalchemy import *\nfrom app.models.grupo import Grupo\n\n\nclass Grupo_alumno_horario(db.Model):\n __tablename__ = 'grupo_alumno_horario'\n grupo = db.relationship(Grupo, backref=__tablename__, lazy=True)\n usuario_horario = db.relationship(Permiso_usuario_horario, backref=\n __tablename__, lazy=True)\n id_grupo = db.Column('ID_GRUPO', db.ForeignKey(Grupo.id_grupo),\n primary_key=True)\n id_horario = db.Column('ID_HORARIO', db.Integer, primary_key=True)\n id_usuario = db.Column('ID_USUARIO', db.Integer, primary_key=True)\n __table_args__ = db.ForeignKeyConstraint(['ID_HORARIO', 'ID_USUARIO'],\n [Permiso_usuario_horario.id_horario, Permiso_usuario_horario.\n id_usuario]),\n\n def addOne(self, obj):\n db.session.add(obj)\n db.session.flush()\n db.session.commit()\n return\n\n @classmethod\n def getAll(self, idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo=idGrupo)\n\n @classmethod\n def getAllGeneral(self, idHorario):\n l = db.session.query(Grupo_alumno_horario, Grupo).join(Grupo).filter(\n and_(Grupo_alumno_horario.id_horario == idHorario, Grupo.\n flg_grupo_general == 1))\n return l\n",
"<import token>\n\n\nclass Grupo_alumno_horario(db.Model):\n __tablename__ = 'grupo_alumno_horario'\n grupo = db.relationship(Grupo, backref=__tablename__, lazy=True)\n usuario_horario = db.relationship(Permiso_usuario_horario, backref=\n __tablename__, lazy=True)\n id_grupo = db.Column('ID_GRUPO', db.ForeignKey(Grupo.id_grupo),\n primary_key=True)\n id_horario = db.Column('ID_HORARIO', db.Integer, primary_key=True)\n id_usuario = db.Column('ID_USUARIO', db.Integer, primary_key=True)\n __table_args__ = db.ForeignKeyConstraint(['ID_HORARIO', 'ID_USUARIO'],\n [Permiso_usuario_horario.id_horario, Permiso_usuario_horario.\n id_usuario]),\n\n def addOne(self, obj):\n db.session.add(obj)\n db.session.flush()\n db.session.commit()\n return\n\n @classmethod\n def getAll(self, idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo=idGrupo)\n\n @classmethod\n def getAllGeneral(self, idHorario):\n l = db.session.query(Grupo_alumno_horario, Grupo).join(Grupo).filter(\n and_(Grupo_alumno_horario.id_horario == idHorario, Grupo.\n flg_grupo_general == 1))\n return l\n",
"<import token>\n\n\nclass Grupo_alumno_horario(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 addOne(self, obj):\n db.session.add(obj)\n db.session.flush()\n db.session.commit()\n return\n\n @classmethod\n def getAll(self, idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo=idGrupo)\n\n @classmethod\n def getAllGeneral(self, idHorario):\n l = db.session.query(Grupo_alumno_horario, Grupo).join(Grupo).filter(\n and_(Grupo_alumno_horario.id_horario == idHorario, Grupo.\n flg_grupo_general == 1))\n return l\n",
"<import token>\n\n\nclass Grupo_alumno_horario(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 addOne(self, obj):\n db.session.add(obj)\n db.session.flush()\n db.session.commit()\n return\n\n @classmethod\n def getAll(self, idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo=idGrupo)\n <function token>\n",
"<import token>\n\n\nclass Grupo_alumno_horario(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 @classmethod\n def getAll(self, idGrupo):\n return Grupo_alumno_horario.query.filter_by(id_grupo=idGrupo)\n <function token>\n",
"<import token>\n\n\nclass Grupo_alumno_horario(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 <function token>\n",
"<import token>\n<class token>\n"
] | false |
99,902 | 979cfa17af2711f9389ee86eb4c1f8ac75086811 | import random
import datetime
while True:
question = input('Ask a question: ') # .split()
b = {"what" and "time": ["The time of the day is:", datetime.datetime.now().time()],
"name": ["My name is Precious!"],
"love": ["Yes, I love you", "No, I don't love you", "What is love?", "Love is wicked"],
"money": ["I will like to know what you think", "Me sef. Sapa be doing the most", "I know you have money",
"Is there something money cannot do?", "Come and gimme money"],
"shoe": ["I am like Jona, I have no shoes", "Will like to get one", "Do you want to buy for me?",
"Imagine walking with different shoes. Lol"],
"food": ["Do you want Ogi?", "Food is not problem", "Do you mind me buying something for you?",
"I need food too."],
"smart": ["What?! We are all smart.", "Yes, if you think so.", "Well. Lol"],
"doing": ["Nothing much", "Wise up", "No time oo", "Talking to you", "Sending videos to friends"],
"shawarma": ["You want?", "Yes!", "Ole ni e", "Can we create a time for that?", "Ori e o pe!"],
"how" or "are you": ["Fine", "Great", "Awwww.", "I need you", "I am fine"]
}
if "break." in question:
break
for word in question:
if word in b:
print(random.choice(b[word]))
elif word not in b:
print("I don't understand you! New question please.")
continue
# if "smart" in question:
# print(random.choice(b["smart"]))
# elif "name" in question:
# print(random.choice(b["name"]))
# elif "money" in question:
# print(random.choice(b["money"]))
# elif "food" in question:
# print(random.choice(b["food"]))
# elif "doing" in question:
# print(random.choice(b["doing"]))
# elif "shoe" in question:
# print(random.choice(b["shoe"]))
# elif "what" and "time" in question:
# print(random.choice(b["what" and "time"]))
# elif "sharwama":
# print(random.choice(b["sharwarma"]))
# elif ("how" and "you") or "how are you":
# print(random.choice(b["how" and "are you"]))
# else:
# print("Can we say something else?")
# # print(question)
# love = ["Yes, I love you", "No, I don't love you", "What is love?", "Love is wicked"]
# eat = ["I love food.", "Sapa, nice one"]
# age = [num for num in range(1, 100)]
# friend = ["I love friendships", "I will like to know you", "Friendship is key"]
# money = ["I will like to know what you think", "Me sef. Sapa be doing the most", "I know you have money",
# "Is there something money cannot do?", "Come and gimme money"]
# shoe = ["I am like Jona, I have no shoes", "Will like to get one", "Do you want to buy for me?",
# "Imagine walking with different shoes. Lol"]
# food = ["Do you want Ogi?", "Food is not problem", "Do you mind me buying something for you?", "I need food too."]
# smart = ["What?! We are all smart.", "Yes, if you think so.", "Well. Lol"]
# doing = ["Nothing much", "Wise up", "No time oo", "Talking to you", "Sending videos to friends"]
# # queyon = [love, eat, age, friend, money]
# print(b[random.choice("love")])
# if "what" and "time" in question:
# print("The time of the day is:", datetime.datetime.now().time())
# if "your name" in question:
# print("My name is Precious!")
# elif "your name" in question:
# print("My name is Precious!")
# elif "love" in question:
# print(random.choice(love))
# elif "eat" in question:
# print(random.choice(eat))
# elif "money" in question:
# print(random.choice(money))
# elif "friend" in question:
# print(random.choice(friend))
# elif "do" or "doing" in question:
# print(random.choice(doing))
# elif "shoes" and "do" in question:
# print(random.choice(shoe))
# elif "break" in question:
# break
# else:
# print("I don't understand you.\nDo you mean What is the time of the day?")
# response = input()
# if "yes" in response:
# print("The time of the day is:", datetime.datetime.now().time())
# if "no" in response:
# print("Wahala ooo")
# print(b.items())
# print(b.keys())
# print(b.values())
| [
"import random\nimport datetime\n\nwhile True:\n question = input('Ask a question: ') # .split()\n b = {\"what\" and \"time\": [\"The time of the day is:\", datetime.datetime.now().time()],\n \"name\": [\"My name is Precious!\"],\n \"love\": [\"Yes, I love you\", \"No, I don't love you\", \"What is love?\", \"Love is wicked\"],\n \"money\": [\"I will like to know what you think\", \"Me sef. Sapa be doing the most\", \"I know you have money\",\n \"Is there something money cannot do?\", \"Come and gimme money\"],\n \"shoe\": [\"I am like Jona, I have no shoes\", \"Will like to get one\", \"Do you want to buy for me?\",\n \"Imagine walking with different shoes. Lol\"],\n \"food\": [\"Do you want Ogi?\", \"Food is not problem\", \"Do you mind me buying something for you?\",\n \"I need food too.\"],\n \"smart\": [\"What?! We are all smart.\", \"Yes, if you think so.\", \"Well. Lol\"],\n \"doing\": [\"Nothing much\", \"Wise up\", \"No time oo\", \"Talking to you\", \"Sending videos to friends\"],\n \"shawarma\": [\"You want?\", \"Yes!\", \"Ole ni e\", \"Can we create a time for that?\", \"Ori e o pe!\"],\n \"how\" or \"are you\": [\"Fine\", \"Great\", \"Awwww.\", \"I need you\", \"I am fine\"]\n }\n if \"break.\" in question:\n break\n\n for word in question:\n if word in b:\n print(random.choice(b[word]))\n elif word not in b:\n print(\"I don't understand you! New question please.\")\n continue\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # if \"smart\" in question:\n # print(random.choice(b[\"smart\"]))\n # elif \"name\" in question:\n # print(random.choice(b[\"name\"]))\n # elif \"money\" in question:\n # print(random.choice(b[\"money\"]))\n # elif \"food\" in question:\n # print(random.choice(b[\"food\"]))\n # elif \"doing\" in question:\n # print(random.choice(b[\"doing\"]))\n # elif \"shoe\" in question:\n # print(random.choice(b[\"shoe\"]))\n # elif \"what\" and \"time\" in question:\n # print(random.choice(b[\"what\" and \"time\"]))\n # elif \"sharwama\":\n # print(random.choice(b[\"sharwarma\"]))\n # elif (\"how\" and \"you\") or \"how are you\":\n # print(random.choice(b[\"how\" and \"are you\"]))\n # else:\n # print(\"Can we say something else?\")\n # # print(question)\n # love = [\"Yes, I love you\", \"No, I don't love you\", \"What is love?\", \"Love is wicked\"]\n # eat = [\"I love food.\", \"Sapa, nice one\"]\n # age = [num for num in range(1, 100)]\n # friend = [\"I love friendships\", \"I will like to know you\", \"Friendship is key\"]\n # money = [\"I will like to know what you think\", \"Me sef. Sapa be doing the most\", \"I know you have money\",\n # \"Is there something money cannot do?\", \"Come and gimme money\"]\n # shoe = [\"I am like Jona, I have no shoes\", \"Will like to get one\", \"Do you want to buy for me?\",\n # \"Imagine walking with different shoes. Lol\"]\n # food = [\"Do you want Ogi?\", \"Food is not problem\", \"Do you mind me buying something for you?\", \"I need food too.\"]\n # smart = [\"What?! We are all smart.\", \"Yes, if you think so.\", \"Well. Lol\"]\n # doing = [\"Nothing much\", \"Wise up\", \"No time oo\", \"Talking to you\", \"Sending videos to friends\"]\n # # queyon = [love, eat, age, friend, money]\n\n # print(b[random.choice(\"love\")])\n # if \"what\" and \"time\" in question:\n # print(\"The time of the day is:\", datetime.datetime.now().time())\n # if \"your name\" in question:\n # print(\"My name is Precious!\")\n # elif \"your name\" in question:\n # print(\"My name is Precious!\")\n # elif \"love\" in question:\n # print(random.choice(love))\n # elif \"eat\" in question:\n # print(random.choice(eat))\n # elif \"money\" in question:\n # print(random.choice(money))\n # elif \"friend\" in question:\n # print(random.choice(friend))\n # elif \"do\" or \"doing\" in question:\n # print(random.choice(doing))\n # elif \"shoes\" and \"do\" in question:\n # print(random.choice(shoe))\n # elif \"break\" in question:\n # break\n # else:\n # print(\"I don't understand you.\\nDo you mean What is the time of the day?\")\n # response = input()\n # if \"yes\" in response:\n # print(\"The time of the day is:\", datetime.datetime.now().time())\n # if \"no\" in response:\n # print(\"Wahala ooo\")\n\n # print(b.items())\n # print(b.keys())\n # print(b.values())\n",
"import random\nimport datetime\nwhile True:\n question = input('Ask a question: ')\n b = {('what' and 'time'): ['The time of the day is:', datetime.datetime\n .now().time()], 'name': ['My name is Precious!'], 'love': [\n 'Yes, I love you', \"No, I don't love you\", 'What is love?',\n 'Love is wicked'], 'money': ['I will like to know what you think',\n 'Me sef. Sapa be doing the most', 'I know you have money',\n 'Is there something money cannot do?', 'Come and gimme money'],\n 'shoe': ['I am like Jona, I have no shoes', 'Will like to get one',\n 'Do you want to buy for me?',\n 'Imagine walking with different shoes. Lol'], 'food': [\n 'Do you want Ogi?', 'Food is not problem',\n 'Do you mind me buying something for you?', 'I need food too.'],\n 'smart': ['What?! We are all smart.', 'Yes, if you think so.',\n 'Well. Lol'], 'doing': ['Nothing much', 'Wise up', 'No time oo',\n 'Talking to you', 'Sending videos to friends'], 'shawarma': [\n 'You want?', 'Yes!', 'Ole ni e', 'Can we create a time for that?',\n 'Ori e o pe!'], ('how' or 'are you'): ['Fine', 'Great', 'Awwww.',\n 'I need you', 'I am fine']}\n if 'break.' in question:\n break\n for word in question:\n if word in b:\n print(random.choice(b[word]))\n elif word not in b:\n print(\"I don't understand you! New question please.\")\n continue\n",
"<import token>\nwhile True:\n question = input('Ask a question: ')\n b = {('what' and 'time'): ['The time of the day is:', datetime.datetime\n .now().time()], 'name': ['My name is Precious!'], 'love': [\n 'Yes, I love you', \"No, I don't love you\", 'What is love?',\n 'Love is wicked'], 'money': ['I will like to know what you think',\n 'Me sef. Sapa be doing the most', 'I know you have money',\n 'Is there something money cannot do?', 'Come and gimme money'],\n 'shoe': ['I am like Jona, I have no shoes', 'Will like to get one',\n 'Do you want to buy for me?',\n 'Imagine walking with different shoes. Lol'], 'food': [\n 'Do you want Ogi?', 'Food is not problem',\n 'Do you mind me buying something for you?', 'I need food too.'],\n 'smart': ['What?! We are all smart.', 'Yes, if you think so.',\n 'Well. Lol'], 'doing': ['Nothing much', 'Wise up', 'No time oo',\n 'Talking to you', 'Sending videos to friends'], 'shawarma': [\n 'You want?', 'Yes!', 'Ole ni e', 'Can we create a time for that?',\n 'Ori e o pe!'], ('how' or 'are you'): ['Fine', 'Great', 'Awwww.',\n 'I need you', 'I am fine']}\n if 'break.' in question:\n break\n for word in question:\n if word in b:\n print(random.choice(b[word]))\n elif word not in b:\n print(\"I don't understand you! New question please.\")\n continue\n",
"<import token>\n<code token>\n"
] | false |
99,903 | d5ac3b91b25ed4d6e1f1722e936513848eef3641 | import block
# block (bytes) as an integer
def getWords(block):
words = [0,0,0,0]
remainder = block
for i in range(4):
word = remainder % (16 ** 4)
# insert into array starting from low order bits
words[3-i] = word
remainder //= (16 ** 4)
return words
# xor each 4 words with the high 64 bits of the key
def whitening(block, key):
rVals = []
words = getWords(block)
whiteningKey = key // (16 ** 4)
keyWords = getWords(whiteningKey)
for word in range(len(words)):
rVals.append(words[word] ^ keyWords[word])
return rVals
# takes two keys as ints and concats their hex representation
def concatKeys(key1, key2):
return (key1 * 0x100) + key2
def concatHexWords(cipherBlocks):
cipher = 0
for word in range(4):
cipher = (cipher * 0x10000) + cipherBlocks[word]
# print(hex(cipher))
return cipher
def splitBlocks(plainText):
blocks = []
numBlocks = len(plainText) // 8
for i in range(numBlocks):
start = i * 8
stop = (i * 8) + 8
blocks.append(plainText[start:stop])
return blocks
def pad(plainText):
padding = len(plainText) % c.BLOCK_SIZE_BYTES
if padding != 0 :
pad = b'\x00' * (c.BLOCK_SIZE_BYTES - padding)
plainText += pad
elif padding == 0:
pad = b'\x00' * c.BLOCK_SIZE_BYTES
plainText += pad
return plainText
def bytesToASCII(hexStr):
plainBytes = bytes.fromhex(hexStr)
plainText = plainBytes.decode()
return plainText
def readFile(file):
plainText = b''
with open(file, 'rb') as f:
block = f.read(c.BLOCK_SIZE_BYTES)
while block != b'':
plainText += block
block = f.read(c.BLOCK_SIZE_BYTES)
return plainText | [
"import block \n\n# block (bytes) as an integer\ndef getWords(block):\n words = [0,0,0,0]\n remainder = block\n for i in range(4):\n word = remainder % (16 ** 4)\n # insert into array starting from low order bits\n words[3-i] = word\n remainder //= (16 ** 4)\n return words\n\n# xor each 4 words with the high 64 bits of the key\ndef whitening(block, key):\n rVals = []\n words = getWords(block)\n whiteningKey = key // (16 ** 4)\n keyWords = getWords(whiteningKey)\n for word in range(len(words)):\n rVals.append(words[word] ^ keyWords[word])\n\n return rVals\n\n# takes two keys as ints and concats their hex representation\ndef concatKeys(key1, key2):\n return (key1 * 0x100) + key2\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = (cipher * 0x10000) + cipherBlocks[word]\n # print(hex(cipher))\n return cipher\n\ndef splitBlocks(plainText):\n blocks = []\n numBlocks = len(plainText) // 8\n for i in range(numBlocks):\n start = i * 8\n stop = (i * 8) + 8\n blocks.append(plainText[start:stop])\n return blocks\n\ndef pad(plainText):\n padding = len(plainText) % c.BLOCK_SIZE_BYTES\n if padding != 0 :\n pad = b'\\x00' * (c.BLOCK_SIZE_BYTES - padding)\n plainText += pad\n elif padding == 0:\n pad = b'\\x00' * c.BLOCK_SIZE_BYTES\n plainText += pad\n return plainText\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText ",
"import block\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\ndef whitening(block, key):\n rVals = []\n words = getWords(block)\n whiteningKey = key // 16 ** 4\n keyWords = getWords(whiteningKey)\n for word in range(len(words)):\n rVals.append(words[word] ^ keyWords[word])\n return rVals\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\ndef splitBlocks(plainText):\n blocks = []\n numBlocks = len(plainText) // 8\n for i in range(numBlocks):\n start = i * 8\n stop = i * 8 + 8\n blocks.append(plainText[start:stop])\n return blocks\n\n\ndef pad(plainText):\n padding = len(plainText) % c.BLOCK_SIZE_BYTES\n if padding != 0:\n pad = b'\\x00' * (c.BLOCK_SIZE_BYTES - padding)\n plainText += pad\n elif padding == 0:\n pad = b'\\x00' * c.BLOCK_SIZE_BYTES\n plainText += pad\n return plainText\n\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\ndef whitening(block, key):\n rVals = []\n words = getWords(block)\n whiteningKey = key // 16 ** 4\n keyWords = getWords(whiteningKey)\n for word in range(len(words)):\n rVals.append(words[word] ^ keyWords[word])\n return rVals\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\ndef splitBlocks(plainText):\n blocks = []\n numBlocks = len(plainText) // 8\n for i in range(numBlocks):\n start = i * 8\n stop = i * 8 + 8\n blocks.append(plainText[start:stop])\n return blocks\n\n\ndef pad(plainText):\n padding = len(plainText) % c.BLOCK_SIZE_BYTES\n if padding != 0:\n pad = b'\\x00' * (c.BLOCK_SIZE_BYTES - padding)\n plainText += pad\n elif padding == 0:\n pad = b'\\x00' * c.BLOCK_SIZE_BYTES\n plainText += pad\n return plainText\n\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\ndef splitBlocks(plainText):\n blocks = []\n numBlocks = len(plainText) // 8\n for i in range(numBlocks):\n start = i * 8\n stop = i * 8 + 8\n blocks.append(plainText[start:stop])\n return blocks\n\n\ndef pad(plainText):\n padding = len(plainText) % c.BLOCK_SIZE_BYTES\n if padding != 0:\n pad = b'\\x00' * (c.BLOCK_SIZE_BYTES - padding)\n plainText += pad\n elif padding == 0:\n pad = b'\\x00' * c.BLOCK_SIZE_BYTES\n plainText += pad\n return plainText\n\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\n<function token>\n\n\ndef pad(plainText):\n padding = len(plainText) % c.BLOCK_SIZE_BYTES\n if padding != 0:\n pad = b'\\x00' * (c.BLOCK_SIZE_BYTES - padding)\n plainText += pad\n elif padding == 0:\n pad = b'\\x00' * c.BLOCK_SIZE_BYTES\n plainText += pad\n return plainText\n\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\n<function token>\n<function token>\n\n\ndef bytesToASCII(hexStr):\n plainBytes = bytes.fromhex(hexStr)\n plainText = plainBytes.decode()\n return plainText\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef readFile(file):\n plainText = b''\n with open(file, 'rb') as f:\n block = f.read(c.BLOCK_SIZE_BYTES)\n while block != b'':\n plainText += block\n block = f.read(c.BLOCK_SIZE_BYTES)\n return plainText\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n\n\ndef concatKeys(key1, key2):\n return key1 * 256 + key2\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n",
"<import token>\n\n\ndef getWords(block):\n words = [0, 0, 0, 0]\n remainder = block\n for i in range(4):\n word = remainder % 16 ** 4\n words[3 - i] = word\n remainder //= 16 ** 4\n return words\n\n\n<function token>\n<function token>\n\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\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\n\ndef concatHexWords(cipherBlocks):\n cipher = 0\n for word in range(4):\n cipher = cipher * 65536 + cipherBlocks[word]\n return cipher\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"
] | false |
99,904 | 03c4404901c23acadf0f12ac800fb5492ce7abbe | import os
""" Constant parameters
"""
UCR_DIR = '../../dataset/UCR_TS_Archive_2015'
""" classifiers
"""
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import LinearSVC
StandardClassifierDic = {
'LR': LogisticRegression(),
'LSVC': LinearSVC(),
'1NN': KNeighborsClassifier(n_neighbors=1)
}
from time import time
from sklearn import metrics
def classify(model, x_tr, y_tr, x_te, y_te):
## train
t_start = time()
model.fit(x_tr, y_tr)
time_tr = time() - t_start
acc_tr = metrics.accuracy_score(y_tr, model.predict(x_tr))
## test
t_start = time()
acc_te = metrics.accuracy_score(y_te, model.predict(x_te))
time_te = time() - t_start
return [acc_tr, acc_te], [time_tr, time_te]
"""
For path construction
"""
def path_split(path):
folders = []
while 1:
path, folder = os.path.split(path)
if folder != "":
folders.append(folder)
else:
if path != "":
folders.append(path)
break
folders.reverse()
return folders
def tag_path(path, nback=1):
"""
example:
tag_path(os.path.abspath(__file__), 1) # return file name
:param path:
:param nback:
:return:
"""
folders = path_split(path)
nf = len(folders)
assert nback >= 1, "nback={} should be larger than 0.".format(nback)
assert nback <= nf, "nback={} should be less than the number of folder {}!".format(nback, nf)
tag = folders[-1].split('.')[0]
if nback > 0:
for i in range(2, nback+1):
tag = folders[-i] + '_' + tag
return tag | [
"import os\n\n\"\"\" Constant parameters\n\"\"\"\nUCR_DIR = '../../dataset/UCR_TS_Archive_2015'\n\n\n\"\"\" classifiers\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC\nStandardClassifierDic = {\n 'LR': LogisticRegression(),\n 'LSVC': LinearSVC(),\n '1NN': KNeighborsClassifier(n_neighbors=1)\n}\n\nfrom time import time\nfrom sklearn import metrics\ndef classify(model, x_tr, y_tr, x_te, y_te):\n ## train\n t_start = time()\n model.fit(x_tr, y_tr)\n time_tr = time() - t_start\n acc_tr = metrics.accuracy_score(y_tr, model.predict(x_tr))\n ## test\n t_start = time()\n acc_te = metrics.accuracy_score(y_te, model.predict(x_te))\n time_te = time() - t_start\n\n return [acc_tr, acc_te], [time_tr, time_te]\n\n\"\"\"\n For path construction\n\"\"\"\n\ndef path_split(path):\n folders = []\n while 1:\n path, folder = os.path.split(path)\n\n if folder != \"\":\n folders.append(folder)\n else:\n if path != \"\":\n folders.append(path)\n break\n folders.reverse()\n return folders\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n\n assert nback >= 1, \"nback={} should be larger than 0.\".format(nback)\n assert nback <= nf, \"nback={} should be less than the number of folder {}!\".format(nback, nf)\n\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback+1):\n tag = folders[-i] + '_' + tag\n return tag",
"import os\n<docstring token>\nUCR_DIR = '../../dataset/UCR_TS_Archive_2015'\n<docstring token>\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC\nStandardClassifierDic = {'LR': LogisticRegression(), 'LSVC': LinearSVC(),\n '1NN': KNeighborsClassifier(n_neighbors=1)}\nfrom time import time\nfrom sklearn import metrics\n\n\ndef classify(model, x_tr, y_tr, x_te, y_te):\n t_start = time()\n model.fit(x_tr, y_tr)\n time_tr = time() - t_start\n acc_tr = metrics.accuracy_score(y_tr, model.predict(x_tr))\n t_start = time()\n acc_te = metrics.accuracy_score(y_te, model.predict(x_te))\n time_te = time() - t_start\n return [acc_tr, acc_te], [time_tr, time_te]\n\n\n<docstring token>\n\n\ndef path_split(path):\n folders = []\n while 1:\n path, folder = os.path.split(path)\n if folder != '':\n folders.append(folder)\n else:\n if path != '':\n folders.append(path)\n break\n folders.reverse()\n return folders\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n assert nback >= 1, 'nback={} should be larger than 0.'.format(nback)\n assert nback <= nf, 'nback={} should be less than the number of folder {}!'.format(\n nback, nf)\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback + 1):\n tag = folders[-i] + '_' + tag\n return tag\n",
"<import token>\n<docstring token>\nUCR_DIR = '../../dataset/UCR_TS_Archive_2015'\n<docstring token>\n<import token>\nStandardClassifierDic = {'LR': LogisticRegression(), 'LSVC': LinearSVC(),\n '1NN': KNeighborsClassifier(n_neighbors=1)}\n<import token>\n\n\ndef classify(model, x_tr, y_tr, x_te, y_te):\n t_start = time()\n model.fit(x_tr, y_tr)\n time_tr = time() - t_start\n acc_tr = metrics.accuracy_score(y_tr, model.predict(x_tr))\n t_start = time()\n acc_te = metrics.accuracy_score(y_te, model.predict(x_te))\n time_te = time() - t_start\n return [acc_tr, acc_te], [time_tr, time_te]\n\n\n<docstring token>\n\n\ndef path_split(path):\n folders = []\n while 1:\n path, folder = os.path.split(path)\n if folder != '':\n folders.append(folder)\n else:\n if path != '':\n folders.append(path)\n break\n folders.reverse()\n return folders\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n assert nback >= 1, 'nback={} should be larger than 0.'.format(nback)\n assert nback <= nf, 'nback={} should be less than the number of folder {}!'.format(\n nback, nf)\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback + 1):\n tag = folders[-i] + '_' + tag\n return tag\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<import token>\n<assignment token>\n<import token>\n\n\ndef classify(model, x_tr, y_tr, x_te, y_te):\n t_start = time()\n model.fit(x_tr, y_tr)\n time_tr = time() - t_start\n acc_tr = metrics.accuracy_score(y_tr, model.predict(x_tr))\n t_start = time()\n acc_te = metrics.accuracy_score(y_te, model.predict(x_te))\n time_te = time() - t_start\n return [acc_tr, acc_te], [time_tr, time_te]\n\n\n<docstring token>\n\n\ndef path_split(path):\n folders = []\n while 1:\n path, folder = os.path.split(path)\n if folder != '':\n folders.append(folder)\n else:\n if path != '':\n folders.append(path)\n break\n folders.reverse()\n return folders\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n assert nback >= 1, 'nback={} should be larger than 0.'.format(nback)\n assert nback <= nf, 'nback={} should be less than the number of folder {}!'.format(\n nback, nf)\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback + 1):\n tag = folders[-i] + '_' + tag\n return tag\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<import token>\n<assignment token>\n<import token>\n<function token>\n<docstring token>\n\n\ndef path_split(path):\n folders = []\n while 1:\n path, folder = os.path.split(path)\n if folder != '':\n folders.append(folder)\n else:\n if path != '':\n folders.append(path)\n break\n folders.reverse()\n return folders\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n assert nback >= 1, 'nback={} should be larger than 0.'.format(nback)\n assert nback <= nf, 'nback={} should be less than the number of folder {}!'.format(\n nback, nf)\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback + 1):\n tag = folders[-i] + '_' + tag\n return tag\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<import token>\n<assignment token>\n<import token>\n<function token>\n<docstring token>\n<function token>\n\n\ndef tag_path(path, nback=1):\n \"\"\"\n example:\n tag_path(os.path.abspath(__file__), 1) # return file name\n :param path: \n :param nback: \n :return: \n \"\"\"\n folders = path_split(path)\n nf = len(folders)\n assert nback >= 1, 'nback={} should be larger than 0.'.format(nback)\n assert nback <= nf, 'nback={} should be less than the number of folder {}!'.format(\n nback, nf)\n tag = folders[-1].split('.')[0]\n if nback > 0:\n for i in range(2, nback + 1):\n tag = folders[-i] + '_' + tag\n return tag\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<import token>\n<assignment token>\n<import token>\n<function token>\n<docstring token>\n<function token>\n<function token>\n"
] | false |
99,905 | 8cf6968582b9e0d0dfb124adfeaf78f9262618a2 | #! /usr/bin/python
# Single 6 faced dice
import random
print("Welcome to Dice Simulator. Press 'Enter' to start.")
Enter = input()
while Enter == "":
x = random.randint(1,6)
print(x)
if x == 6:
print ("Roll Again. Press 'Enter'")
Enter = input()
if Enter == "":
x = random.randint(1,6)
print(x)
if x == 6:
print("Two chances only.")
print("Next Player Turn. Press 'Enter'")
Enter = input()
else:
print("You did not press Enter")
| [
"#! /usr/bin/python\n# Single 6 faced dice\nimport random\nprint(\"Welcome to Dice Simulator. Press 'Enter' to start.\")\nEnter = input()\nwhile Enter == \"\":\n x = random.randint(1,6)\n print(x)\n if x == 6:\n print (\"Roll Again. Press 'Enter'\")\n Enter = input()\n if Enter == \"\":\n x = random.randint(1,6)\n print(x)\n if x == 6:\n print(\"Two chances only.\")\n print(\"Next Player Turn. Press 'Enter'\")\n Enter = input()\nelse:\n print(\"You did not press Enter\")\n",
"import random\nprint(\"Welcome to Dice Simulator. Press 'Enter' to start.\")\nEnter = input()\nwhile Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print(\"Roll Again. Press 'Enter'\")\n Enter = input()\n if Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print('Two chances only.')\n print(\"Next Player Turn. Press 'Enter'\")\n Enter = input()\nelse:\n print('You did not press Enter')\n",
"<import token>\nprint(\"Welcome to Dice Simulator. Press 'Enter' to start.\")\nEnter = input()\nwhile Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print(\"Roll Again. Press 'Enter'\")\n Enter = input()\n if Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print('Two chances only.')\n print(\"Next Player Turn. Press 'Enter'\")\n Enter = input()\nelse:\n print('You did not press Enter')\n",
"<import token>\nprint(\"Welcome to Dice Simulator. Press 'Enter' to start.\")\n<assignment token>\nwhile Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print(\"Roll Again. Press 'Enter'\")\n Enter = input()\n if Enter == '':\n x = random.randint(1, 6)\n print(x)\n if x == 6:\n print('Two chances only.')\n print(\"Next Player Turn. Press 'Enter'\")\n Enter = input()\nelse:\n print('You did not press Enter')\n",
"<import token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,906 | c5ac9cb72b76168a706dc43f27806985d59bbb31 | import errno
import os
import re
import sass
import shutil
from cssmin import cssmin
from jsmin import jsmin
from src.lib.util.injection import *
from src.lib.util.logger import *
from src.lib.util.settings import *
class Renderer:
def __init__(self):
settings = Settings.get_instance()
cwd = os.getcwd()
sep = os.sep
self.__page_name = 'default';
self.__components_path = cwd + settings.render_path(settings.prop('app_settings.components_dir')) + sep
self.__content_path = cwd + settings.render_path(settings.prop('app_settings.content_dir')) + sep
self.__css_path = cwd + settings.render_path(settings.prop('app_settings.css_dir')) + sep
self.__dist_dir = cwd + settings.render_path(settings.prop('app_settings.dist_dir')) + sep
self.__dist_css_path = cwd + settings.render_path(settings.prop('app_settings.compiled_css_dir')) + sep
self.__dist_js_path = cwd + settings.render_path(settings.prop('app_settings.compiled_js_dir')) + sep
self.__js_path = cwd + settings.render_path(settings.prop('app_settings.js_dir')) + sep
self.__pages_path = cwd + settings.render_path(settings.prop('app_settings.pages_dir')) + sep
self.__scss_path = cwd + settings.render_path(settings.prop('app_settings.scss_dir')) + sep
def render(self):
''' begins the rendering process '''
directories = []
pages = []
for file in os.listdir(self.__pages_path):
if os.path.isfile(f'{self.__pages_path}{file}') and '.html' in file:
pages.append(file)
elif os.path.isdir(f'{self.__pages_path}{file}'):
# todo: move into the directory
pass
self.__render_pages(pages)
self.__render_js()
settings = Settings.get_instance()
if settings.use_scss():
self.__render_scss()
else:
self.__render_css()
# create general symlinks
if settings.prop('app_settings.use_symlinks'):
self.__generate_symlinks()
def __render_scss(self):
''' compiles main.scss to main.css in dist '''
sass.compile(dirname=(self.__scss_path, self.__dist_css_path), output_style='compressed')
# TODO: combine js and css renderers (DRY)
def __render_css(self):
''' writes css files to dist '''
should_minify = Settings.get_instance().minify_css()
self.__js_css_render(should_minify, self.__css_path, self.__dist_css_path, '.css')
def __render_js(self):
''' writes js files to dist '''
should_minify = Settings.get_instance().minify_js()
self.__js_css_render(should_minify, self.__js_path, self.__dist_js_path, '.js')
def __js_css_render(self, should_minify, path, dist_path, extension):
''' . '''
for file in os.listdir(path):
#
if os.path.isfile(path+file) and file.endswith(extension):
#
if should_minify and '.min.' not in file:
with open(path+file, 'r') as f:
min_name = file.replace(extension, '.min'+extension)
with self.__write_file_path(dist_path+min_name) as min_f:
if extension == '.js':
min_f.write(jsmin(f.read()))
elif extension == '.css':
min_f.write(cssmin(f.read()))
else:
#
shutil.copy(path+file, dist_path+file)
elif os.path.isdir(path+file):
if Settings.get_instance().prop('app_settings.use_symlinks'):
try:
# create symlink of the directory
os.symlink(path+file, dist_path+file)
except Exception as e:
pass # the symlink already exists
def __generate_symlinks(self):
''' . '''
cwd = os.getcwd()
settings = Settings.get_instance()
links = {}
# images
images_path = cwd + settings.render_path(settings.prop('app_settings.images_dir'))
images_dist = cwd + settings.render_path(settings.prop('app_settings.compiled_images_dir'))
links[images_path] = images_dist
# loop through the links and attempt to create them if they don't already exist
for src,dest in links.items():
try:
os.symlink(src, dest)
except Exception as e:
pass # the symlink already exists
def __parse_value(self, injection_str, containers):
''' pare the value from the injection string '''
parsed = injection_str.replace(containers[0],'').replace(containers[1],'').strip()
if '[[' in containers and ']]' in containers:
# handle page_meta defaulting
split_parsed = parsed.split('.')
if split_parsed[0] == 'page_meta' and not Settings.get_instance().has_prop(parsed):
Logger.warning(f'\t\tUsing default attributes for property: {parsed}')
split_parsed[1] = 'default'
parsed = ''
for i in range(len(split_parsed)):
parsed += f'{"." if i > 0 else ""}{split_parsed[i]}'
return Settings.get_instance().prop(parsed)
elif '{{' in containers and '}}' in containers:
return Injection.get_instance().exec_inj(parsed)
def __render_content(self, content_name, component_html):
''' gets the rendered html of a specific component with the specified content '''
try:
with open(f'{self.__content_path}{content_name}.json', 'r') as f:
content_json = json.loads(f.read())
# go through the component's html and inject the appropriate content
return_html = ''
for line in component_html.splitlines():
while '((' in line and '))' in line:
start = line.find('((')
end = line.find('))')+2
attr_inj = line[start:end]
try:
content_attr = content_json[re.sub(r'\(\(|\)\)', '', attr_inj).strip()]
line = line.replace(attr_inj, content_attr)
except Exception as e:
Logger.error(f'\t\tmissing content attribute from {content_name}.json: {e}')
line = line.replace(attr_inj, re.sub(r'\(\(|\)\)', '**ERROR**', attr_inj))
return_html += line
return return_html
except Exception as e:
Logger.error(e)
return component_html
def __render_loop(self, attrs):
''' gets the rendered html of the specified children component '''
try:
children_name = attrs['pfFor']
# add loop class
if 'class' in attrs:
attrs['class'] += f' {children_name} parent'
else:
attrs['class'] = f'{children_name}'
# build the container for the looped elements
return_html = '<div '
for attr in attrs:
if not attr == 'pfFor':
return_html += f'{attr}="{attrs[attr]}"'
return_html += '>'
# grab the children json
with open(f'{self.__content_path}{children_name}.json', 'r') as f:
try:
content_json = json.loads(f.read())
except Exception as e:
raise Exception(f'Malformed JSON in {children_name}.json: {e}')
# start writing out the children
with open(f'{self.__components_path}{children_name}.html', 'r') as f:
for child in content_json['children']:
# reset the read head
f.seek(0)
# build the child's container
return_html += f'<div class="{children_name} child">'
# loop through each line in the child html
for line in f.readlines():
# check for injection
if not '((' in line and not '))' in line:
return_html += line
else:
while '((' in line and '))' in line:
start = line.find('((')
end = line.find('))')+2
attr_inj = line[start:end]
try:
content_attr = child[re.sub(r'\(\(|\)\)', '', attr_inj).strip()]
line = line.replace(attr_inj, content_attr)
except Exception as e:
Logger.error(f'\t\tmissing content attribute from {children_name}.json: {e}')
line = line.replace(attr_inj, re.sub(r'\(\(|\)\)', '**ERROR**', attr_inj))
# print(f'line: {line}')
return_html += line
return_html += '</div>'
# close the outer container div
return return_html + '</div>'
except Exception as e:
Logger.error(f'\t\tError rendering children for {attrs["pfFor"]} component. {e}')
return f'<div>{e}</div>'
def __render_component(self, component_str):
''' gets the rendered html of a specific component '''
split_attr = component_str.replace('<pfcomponent','').replace('/>','').strip().split(' ')
attrs = {}
# break apart the component's attributes
for attr in split_attr:
split = attr.split('=')
attrs[split[0].strip()] = split[1].replace('"','').strip()
# look for general components
return_str = ''
if 'name' in attrs:
with open(f'{self.__components_path}{attrs["name"]}.html', 'r') as f:
for line in f:
return_str += self.__manage_component(line)
# look for content segments
if 'content' in attrs:
return self.__render_content(attrs['content'], return_str)
# look for repeated content segments
if 'pfFor' in attrs:
return self.__render_loop(attrs)
return return_str
def __render_pages(self, pages):
''' gets the rendered html of each page and saves each file in dist '''
for page in pages:
new_html = ''
Logger.info(f'\n\tRendering "{page}"')
# manage page name details for page_meta
page_name = page.split('.')[0]
if Settings.get_instance().has_prop(f'page_meta.{page_name}'):
self.__page_name = page_name
else:
self.__page_name = 'default'
# loop through the page and look for components to render
with open(self.__pages_path + page, 'r') as f:
for line in f:
new_html += self.__manage_component(line)
with self.__write_file_path(f'{self.__dist_dir}{page}') as f:
f.write(new_html)
Logger.info('\t\t-- Done --')
Logger.info('')
def __manage_component(self, line):
''' checks if the line contains a pfcomponent and replaces it with the component's html '''
line = self.__manage_injection(line)
component_name = '<pfcomponent'
if component_name in line:
if '/>' in line:
start = line.find(component_name)
end = line.find('/>', start+len(component_name))+2
component_str = line[start:end]
line = line.replace(component_str, self.__render_component(component_str))
else:
Logger.error(f'\t\tMissing tag terminator ("/>"): {line.strip()}')
line = ''
return line
def __manage_injection(self, line, content=''):
''' checks if the line contains injected code and renders it '''
while '[[' in line and ']]' in line:
start = line.find('[[')
end = line.find(']]')+2
line_replacement = line[start:end]
# add the current page to the page_meta if it exists
injection_str = line_replacement.replace('page_meta', f'page_meta.{self.__page_name}')
# update the line with the new parsed value
line = line.replace(line_replacement, str(self.__parse_value(injection_str, ('[[',']]'))))
while '{{' in line and '}}' in line:
start = line.find('{{')
end = line.find('}}')+2
injection_str = line[start:end]
line = line.replace(injection_str, str(self.__parse_value(injection_str, ('{{','}}'))))
return line
def mkdir_p(self, path):
''' . '''
try:
os.makedirs(path)
except OSError as o:
if os.path.isdir(path) and o.errno == errno.EEXIST:
pass
else:
raise
def __write_file_path(self, path):
''' . '''
self.mkdir_p(os.path.dirname(path))
return open(path, 'w')
| [
"import errno\nimport os\nimport re\nimport sass\nimport shutil\nfrom cssmin import cssmin\nfrom jsmin import jsmin\nfrom src.lib.util.injection import *\nfrom src.lib.util.logger import *\nfrom src.lib.util.settings import *\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n\n self.__page_name = 'default';\n self.__components_path = cwd + settings.render_path(settings.prop('app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop('app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop('app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop('app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop('app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop('app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop('app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop('app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop('app_settings.scss_dir')) + sep\n\n\n def render(self):\n ''' begins the rendering process '''\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}') and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n # todo: move into the directory\n pass\n\n self.__render_pages(pages)\n self.__render_js()\n\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n\n # create general symlinks\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n\n def __render_scss(self):\n ''' compiles main.scss to main.css in dist '''\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path), output_style='compressed')\n\n\n # TODO: combine js and css renderers (DRY)\n def __render_css(self):\n ''' writes css files to dist '''\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.__dist_css_path, '.css')\n\n\n def __render_js(self):\n ''' writes js files to dist '''\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.__dist_js_path, '.js')\n\n\n def __js_css_render(self, should_minify, path, dist_path, extension):\n ''' . '''\n for file in os.listdir(path):\n # \n if os.path.isfile(path+file) and file.endswith(extension):\n # \n if should_minify and '.min.' not in file:\n with open(path+file, 'r') as f:\n min_name = file.replace(extension, '.min'+extension)\n\n with self.__write_file_path(dist_path+min_name) as min_f:\n if extension == '.js':\n min_f.write(jsmin(f.read()))\n elif extension == '.css':\n min_f.write(cssmin(f.read()))\n else:\n # \n shutil.copy(path+file, dist_path+file)\n elif os.path.isdir(path+file):\n if Settings.get_instance().prop('app_settings.use_symlinks'):\n try:\n # create symlink of the directory\n os.symlink(path+file, dist_path+file)\n except Exception as e:\n pass # the symlink already exists\n\n\n def __generate_symlinks(self):\n ''' . '''\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n\n # images\n images_path = cwd + settings.render_path(settings.prop('app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop('app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n\n # loop through the links and attempt to create them if they don't already exist\n for src,dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass # the symlink already exists\n\n\n def __parse_value(self, injection_str, containers):\n ''' pare the value from the injection string '''\n parsed = injection_str.replace(containers[0],'').replace(containers[1],'').strip()\n\n if '[[' in containers and ']]' in containers:\n # handle page_meta defaulting\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance().has_prop(parsed):\n Logger.warning(f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n \n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f'{\".\" if i > 0 else \"\"}{split_parsed[i]}'\n\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n\n def __render_content(self, content_name, component_html):\n ''' gets the rendered html of a specific component with the specified content '''\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n\n # go through the component's html and inject the appropriate content\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))')+2\n attr_inj = line[start:end]\n\n try:\n content_attr = content_json[re.sub(r'\\(\\(|\\)\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(f'\\t\\tmissing content attribute from {content_name}.json: {e}')\n line = line.replace(attr_inj, re.sub(r'\\(\\(|\\)\\)', '**ERROR**', attr_inj))\n return_html += line\n\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n\n def __render_loop(self, attrs):\n ''' gets the rendered html of the specified children component '''\n try:\n children_name = attrs['pfFor']\n\n # add loop class\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n\n # build the container for the looped elements\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n\n # grab the children json\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(f'Malformed JSON in {children_name}.json: {e}')\n\n # start writing out the children\n with open(f'{self.__components_path}{children_name}.html', 'r') as f:\n for child in content_json['children']:\n # reset the read head\n f.seek(0)\n\n # build the child's container\n return_html += f'<div class=\"{children_name} child\">'\n\n # loop through each line in the child html\n for line in f.readlines():\n # check for injection\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))')+2\n attr_inj = line[start:end]\n\n try:\n content_attr = child[re.sub(r'\\(\\(|\\)\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(f'\\t\\tmissing content attribute from {children_name}.json: {e}')\n line = line.replace(attr_inj, re.sub(r'\\(\\(|\\)\\)', '**ERROR**', attr_inj))\n\n # print(f'line: {line}')\n return_html += line\n\n return_html += '</div>'\n # close the outer container div\n return return_html + '</div>'\n except Exception as e:\n Logger.error(f'\\t\\tError rendering children for {attrs[\"pfFor\"]} component. {e}')\n return f'<div>{e}</div>'\n\n\n def __render_component(self, component_str):\n ''' gets the rendered html of a specific component '''\n split_attr = component_str.replace('<pfcomponent','').replace('/>','').strip().split(' ')\n attrs = {}\n\n # break apart the component's attributes\n for attr in split_attr:\n split = attr.split('=')\n attrs[split[0].strip()] = split[1].replace('\"','').strip()\n\n # look for general components\n return_str = ''\n if 'name' in attrs:\n with open(f'{self.__components_path}{attrs[\"name\"]}.html', 'r') as f:\n for line in f:\n return_str += self.__manage_component(line)\n\n # look for content segments\n if 'content' in attrs:\n return self.__render_content(attrs['content'], return_str)\n\n # look for repeated content segments\n if 'pfFor' in attrs:\n return self.__render_loop(attrs)\n\n return return_str\n\n\n def __render_pages(self, pages):\n ''' gets the rendered html of each page and saves each file in dist '''\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n\n # manage page name details for page_meta\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n\n # loop through the page and look for components to render\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n\n\n def __manage_component(self, line):\n ''' checks if the line contains a pfcomponent and replaces it with the component's html '''\n line = self.__manage_injection(line)\n component_name = '<pfcomponent'\n\n if component_name in line:\n if '/>' in line:\n start = line.find(component_name)\n end = line.find('/>', start+len(component_name))+2\n\n component_str = line[start:end]\n line = line.replace(component_str, self.__render_component(component_str))\n else:\n Logger.error(f'\\t\\tMissing tag terminator (\"/>\"): {line.strip()}')\n line = ''\n return line\n\n\n def __manage_injection(self, line, content=''):\n ''' checks if the line contains injected code and renders it '''\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]')+2\n line_replacement = line[start:end]\n\n # add the current page to the page_meta if it exists\n injection_str = line_replacement.replace('page_meta', f'page_meta.{self.__page_name}')\n\n # update the line with the new parsed value\n line = line.replace(line_replacement, str(self.__parse_value(injection_str, ('[[',']]'))))\n\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}')+2\n\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(injection_str, ('{{','}}'))))\n\n return line\n\n\n def mkdir_p(self, path):\n ''' . '''\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n\n def __write_file_path(self, path):\n ''' . '''\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"import errno\nimport os\nimport re\nimport sass\nimport shutil\nfrom cssmin import cssmin\nfrom jsmin import jsmin\nfrom src.lib.util.injection import *\nfrom src.lib.util.logger import *\nfrom src.lib.util.settings import *\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n\n def render(self):\n \"\"\" begins the rendering process \"\"\"\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}'\n ) and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n pass\n self.__render_pages(pages)\n self.__render_js()\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n\n def __js_css_render(self, should_minify, path, dist_path, extension):\n \"\"\" . \"\"\"\n for file in os.listdir(path):\n if os.path.isfile(path + file) and file.endswith(extension):\n if should_minify and '.min.' not in file:\n with open(path + file, 'r') as f:\n min_name = file.replace(extension, '.min' + extension)\n with self.__write_file_path(dist_path + min_name\n ) as min_f:\n if extension == '.js':\n min_f.write(jsmin(f.read()))\n elif extension == '.css':\n min_f.write(cssmin(f.read()))\n else:\n shutil.copy(path + file, dist_path + file)\n elif os.path.isdir(path + file):\n if Settings.get_instance().prop('app_settings.use_symlinks'):\n try:\n os.symlink(path + file, dist_path + file)\n except Exception as e:\n pass\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n\n def __render_component(self, component_str):\n \"\"\" gets the rendered html of a specific component \"\"\"\n split_attr = component_str.replace('<pfcomponent', '').replace('/>', ''\n ).strip().split(' ')\n attrs = {}\n for attr in split_attr:\n split = attr.split('=')\n attrs[split[0].strip()] = split[1].replace('\"', '').strip()\n return_str = ''\n if 'name' in attrs:\n with open(f\"{self.__components_path}{attrs['name']}.html\", 'r'\n ) as f:\n for line in f:\n return_str += self.__manage_component(line)\n if 'content' in attrs:\n return self.__render_content(attrs['content'], return_str)\n if 'pfFor' in attrs:\n return self.__render_loop(attrs)\n return return_str\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n\n def __manage_component(self, line):\n \"\"\" checks if the line contains a pfcomponent and replaces it with the component's html \"\"\"\n line = self.__manage_injection(line)\n component_name = '<pfcomponent'\n if component_name in line:\n if '/>' in line:\n start = line.find(component_name)\n end = line.find('/>', start + len(component_name)) + 2\n component_str = line[start:end]\n line = line.replace(component_str, self.__render_component(\n component_str))\n else:\n Logger.error(\n f'\\t\\tMissing tag terminator (\"/>\"): {line.strip()}')\n line = ''\n return line\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n\n def render(self):\n \"\"\" begins the rendering process \"\"\"\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}'\n ) and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n pass\n self.__render_pages(pages)\n self.__render_js()\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n\n def __js_css_render(self, should_minify, path, dist_path, extension):\n \"\"\" . \"\"\"\n for file in os.listdir(path):\n if os.path.isfile(path + file) and file.endswith(extension):\n if should_minify and '.min.' not in file:\n with open(path + file, 'r') as f:\n min_name = file.replace(extension, '.min' + extension)\n with self.__write_file_path(dist_path + min_name\n ) as min_f:\n if extension == '.js':\n min_f.write(jsmin(f.read()))\n elif extension == '.css':\n min_f.write(cssmin(f.read()))\n else:\n shutil.copy(path + file, dist_path + file)\n elif os.path.isdir(path + file):\n if Settings.get_instance().prop('app_settings.use_symlinks'):\n try:\n os.symlink(path + file, dist_path + file)\n except Exception as e:\n pass\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n\n def __render_component(self, component_str):\n \"\"\" gets the rendered html of a specific component \"\"\"\n split_attr = component_str.replace('<pfcomponent', '').replace('/>', ''\n ).strip().split(' ')\n attrs = {}\n for attr in split_attr:\n split = attr.split('=')\n attrs[split[0].strip()] = split[1].replace('\"', '').strip()\n return_str = ''\n if 'name' in attrs:\n with open(f\"{self.__components_path}{attrs['name']}.html\", 'r'\n ) as f:\n for line in f:\n return_str += self.__manage_component(line)\n if 'content' in attrs:\n return self.__render_content(attrs['content'], return_str)\n if 'pfFor' in attrs:\n return self.__render_loop(attrs)\n return return_str\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n\n def __manage_component(self, line):\n \"\"\" checks if the line contains a pfcomponent and replaces it with the component's html \"\"\"\n line = self.__manage_injection(line)\n component_name = '<pfcomponent'\n if component_name in line:\n if '/>' in line:\n start = line.find(component_name)\n end = line.find('/>', start + len(component_name)) + 2\n component_str = line[start:end]\n line = line.replace(component_str, self.__render_component(\n component_str))\n else:\n Logger.error(\n f'\\t\\tMissing tag terminator (\"/>\"): {line.strip()}')\n line = ''\n return line\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n\n def render(self):\n \"\"\" begins the rendering process \"\"\"\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}'\n ) and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n pass\n self.__render_pages(pages)\n self.__render_js()\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n\n def __render_component(self, component_str):\n \"\"\" gets the rendered html of a specific component \"\"\"\n split_attr = component_str.replace('<pfcomponent', '').replace('/>', ''\n ).strip().split(' ')\n attrs = {}\n for attr in split_attr:\n split = attr.split('=')\n attrs[split[0].strip()] = split[1].replace('\"', '').strip()\n return_str = ''\n if 'name' in attrs:\n with open(f\"{self.__components_path}{attrs['name']}.html\", 'r'\n ) as f:\n for line in f:\n return_str += self.__manage_component(line)\n if 'content' in attrs:\n return self.__render_content(attrs['content'], return_str)\n if 'pfFor' in attrs:\n return self.__render_loop(attrs)\n return return_str\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n\n def __manage_component(self, line):\n \"\"\" checks if the line contains a pfcomponent and replaces it with the component's html \"\"\"\n line = self.__manage_injection(line)\n component_name = '<pfcomponent'\n if component_name in line:\n if '/>' in line:\n start = line.find(component_name)\n end = line.find('/>', start + len(component_name)) + 2\n component_str = line[start:end]\n line = line.replace(component_str, self.__render_component(\n component_str))\n else:\n Logger.error(\n f'\\t\\tMissing tag terminator (\"/>\"): {line.strip()}')\n line = ''\n return line\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n\n def render(self):\n \"\"\" begins the rendering process \"\"\"\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}'\n ) and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n pass\n self.__render_pages(pages)\n self.__render_js()\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n\n def __render_component(self, component_str):\n \"\"\" gets the rendered html of a specific component \"\"\"\n split_attr = component_str.replace('<pfcomponent', '').replace('/>', ''\n ).strip().split(' ')\n attrs = {}\n for attr in split_attr:\n split = attr.split('=')\n attrs[split[0].strip()] = split[1].replace('\"', '').strip()\n return_str = ''\n if 'name' in attrs:\n with open(f\"{self.__components_path}{attrs['name']}.html\", 'r'\n ) as f:\n for line in f:\n return_str += self.__manage_component(line)\n if 'content' in attrs:\n return self.__render_content(attrs['content'], return_str)\n if 'pfFor' in attrs:\n return self.__render_loop(attrs)\n return return_str\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n\n def render(self):\n \"\"\" begins the rendering process \"\"\"\n directories = []\n pages = []\n for file in os.listdir(self.__pages_path):\n if os.path.isfile(f'{self.__pages_path}{file}'\n ) and '.html' in file:\n pages.append(file)\n elif os.path.isdir(f'{self.__pages_path}{file}'):\n pass\n self.__render_pages(pages)\n self.__render_js()\n settings = Settings.get_instance()\n if settings.use_scss():\n self.__render_scss()\n else:\n self.__render_css()\n if settings.prop('app_settings.use_symlinks'):\n self.__generate_symlinks()\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n\n def __manage_injection(self, line, content=''):\n \"\"\" checks if the line contains injected code and renders it \"\"\"\n while '[[' in line and ']]' in line:\n start = line.find('[[')\n end = line.find(']]') + 2\n line_replacement = line[start:end]\n injection_str = line_replacement.replace('page_meta',\n f'page_meta.{self.__page_name}')\n line = line.replace(line_replacement, str(self.__parse_value(\n injection_str, ('[[', ']]'))))\n while '{{' in line and '}}' in line:\n start = line.find('{{')\n end = line.find('}}') + 2\n injection_str = line[start:end]\n line = line.replace(injection_str, str(self.__parse_value(\n injection_str, ('{{', '}}'))))\n return line\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance()\n cwd = os.getcwd()\n sep = os.sep\n self.__page_name = 'default'\n self.__components_path = cwd + settings.render_path(settings.prop(\n 'app_settings.components_dir')) + sep\n self.__content_path = cwd + settings.render_path(settings.prop(\n 'app_settings.content_dir')) + sep\n self.__css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.css_dir')) + sep\n self.__dist_dir = cwd + settings.render_path(settings.prop(\n 'app_settings.dist_dir')) + sep\n self.__dist_css_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_css_dir')) + sep\n self.__dist_js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_js_dir')) + sep\n self.__js_path = cwd + settings.render_path(settings.prop(\n 'app_settings.js_dir')) + sep\n self.__pages_path = cwd + settings.render_path(settings.prop(\n 'app_settings.pages_dir')) + sep\n self.__scss_path = cwd + settings.render_path(settings.prop(\n 'app_settings.scss_dir')) + sep\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n\n def __render_js(self):\n \"\"\" writes js files to dist \"\"\"\n should_minify = Settings.get_instance().minify_js()\n self.__js_css_render(should_minify, self.__js_path, self.\n __dist_js_path, '.js')\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n\n def __render_loop(self, attrs):\n \"\"\" gets the rendered html of the specified children component \"\"\"\n try:\n children_name = attrs['pfFor']\n if 'class' in attrs:\n attrs['class'] += f' {children_name} parent'\n else:\n attrs['class'] = f'{children_name}'\n return_html = '<div '\n for attr in attrs:\n if not attr == 'pfFor':\n return_html += f'{attr}=\"{attrs[attr]}\"'\n return_html += '>'\n with open(f'{self.__content_path}{children_name}.json', 'r') as f:\n try:\n content_json = json.loads(f.read())\n except Exception as e:\n raise Exception(\n f'Malformed JSON in {children_name}.json: {e}')\n with open(f'{self.__components_path}{children_name}.html', 'r'\n ) as f:\n for child in content_json['children']:\n f.seek(0)\n return_html += f'<div class=\"{children_name} child\">'\n for line in f.readlines():\n if not '((' in line and not '))' in line:\n return_html += line\n else:\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = child[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {children_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj)\n )\n return_html += line\n return_html += '</div>'\n return return_html + '</div>'\n except Exception as e:\n Logger.error(\n f\"\\t\\tError rendering children for {attrs['pfFor']} component. {e}\"\n )\n return f'<div>{e}</div>'\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n\n def __render_content(self, content_name, component_html):\n \"\"\" gets the rendered html of a specific component with the specified content \"\"\"\n try:\n with open(f'{self.__content_path}{content_name}.json', 'r') as f:\n content_json = json.loads(f.read())\n return_html = ''\n for line in component_html.splitlines():\n while '((' in line and '))' in line:\n start = line.find('((')\n end = line.find('))') + 2\n attr_inj = line[start:end]\n try:\n content_attr = content_json[re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '', attr_inj).strip()]\n line = line.replace(attr_inj, content_attr)\n except Exception as e:\n Logger.error(\n f'\\t\\tmissing content attribute from {content_name}.json: {e}'\n )\n line = line.replace(attr_inj, re.sub(\n '\\\\(\\\\(|\\\\)\\\\)', '**ERROR**', attr_inj))\n return_html += line\n return return_html\n except Exception as e:\n Logger.error(e)\n return component_html\n <function token>\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n <function token>\n <function token>\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n\n def mkdir_p(self, path):\n \"\"\" . \"\"\"\n try:\n os.makedirs(path)\n except OSError as o:\n if os.path.isdir(path) and o.errno == errno.EEXIST:\n pass\n else:\n raise\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n <function token>\n <function token>\n <function token>\n\n def __render_pages(self, pages):\n \"\"\" gets the rendered html of each page and saves each file in dist \"\"\"\n for page in pages:\n new_html = ''\n Logger.info(f'\\n\\tRendering \"{page}\"')\n page_name = page.split('.')[0]\n if Settings.get_instance().has_prop(f'page_meta.{page_name}'):\n self.__page_name = page_name\n else:\n self.__page_name = 'default'\n with open(self.__pages_path + page, 'r') as f:\n for line in f:\n new_html += self.__manage_component(line)\n with self.__write_file_path(f'{self.__dist_dir}{page}') as f:\n f.write(new_html)\n Logger.info('\\t\\t-- Done --')\n Logger.info('')\n <function token>\n <function token>\n <function token>\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n\n def __generate_symlinks(self):\n \"\"\" . \"\"\"\n cwd = os.getcwd()\n settings = Settings.get_instance()\n links = {}\n images_path = cwd + settings.render_path(settings.prop(\n 'app_settings.images_dir'))\n images_dist = cwd + settings.render_path(settings.prop(\n 'app_settings.compiled_images_dir'))\n links[images_path] = images_dist\n for src, dest in links.items():\n try:\n os.symlink(src, dest)\n except Exception as e:\n pass\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n\n def __render_scss(self):\n \"\"\" compiles main.scss to main.css in dist \"\"\"\n sass.compile(dirname=(self.__scss_path, self.__dist_css_path),\n output_style='compressed')\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n <function token>\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n <function token>\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\n <function token>\n <function token>\n <function token>\n\n def __parse_value(self, injection_str, containers):\n \"\"\" pare the value from the injection string \"\"\"\n parsed = injection_str.replace(containers[0], '').replace(containers\n [1], '').strip()\n if '[[' in containers and ']]' in containers:\n split_parsed = parsed.split('.')\n if split_parsed[0] == 'page_meta' and not Settings.get_instance(\n ).has_prop(parsed):\n Logger.warning(\n f'\\t\\tUsing default attributes for property: {parsed}')\n split_parsed[1] = 'default'\n parsed = ''\n for i in range(len(split_parsed)):\n parsed += f\"{'.' if i > 0 else ''}{split_parsed[i]}\"\n return Settings.get_instance().prop(parsed)\n elif '{{' in containers and '}}' in containers:\n return Injection.get_instance().exec_inj(parsed)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n <function token>\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\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 __write_file_path(self, path):\n \"\"\" . \"\"\"\n self.mkdir_p(os.path.dirname(path))\n return open(path, 'w')\n",
"<import token>\n\n\nclass Renderer:\n <function token>\n <function token>\n <function token>\n\n def __render_css(self):\n \"\"\" writes css files to dist \"\"\"\n should_minify = Settings.get_instance().minify_css()\n self.__js_css_render(should_minify, self.__css_path, self.\n __dist_css_path, '.css')\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",
"<import token>\n\n\nclass Renderer:\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",
"<import token>\n<class token>\n"
] | false |
99,907 | 4712e515d3ec32bbf8ba2b506cada78cbd553fd8 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
http://selenium-python.readthedocs.io
https://realpython.com/blog/python/modern-web-automation-with-python-and-selenium/
dokumentace s příklady:
https://media.readthedocs.org/pdf/selenium-python/latest/selenium-python.pdf
"""
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
opts = Options()
opts.set_headless(False)
browser = Firefox(options=opts)
browser.get('https://www.ihned.cz')
x = browser.find_elements_by_class_name('article-title')
y = x[0].find_element_by_tag_name("a")
y.click()
browser.get_screenshot_as_file('./scrsht/img_1.png')
browser.set_window_size(800,2048)
browser.get_screenshot_as_file('./scrsht/img_2.png')
browser.minimize_window()
browser.maximize_window()
browser.back()
browser.refresh()
# scroll
browser.execute_script("window.scrollTo(0, 300)")
y = 900
browser.execute_script("window.scrollTo(0, arguments[0])", y)
#where y is the height, předání pomocí y -> arguments[0]
browser.set_window_size(300,600)
x, y = 150, 1200
browser.execute_script("window.scrollTo(arguments[0], arguments[1])", x, y)
browser.set_window_size(600,600)
# scroll-down na konec okna
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
#zavři cookie warning
cookies = browser.get_cookies()
cookies_old = cookies.copy()
#umožňuje zadat jen 1 class
cookie_warning_1 = browser.find_element_by_class_name('cc_btn_accept_all')
#umožňuje zadat více classes (.cc_btn and .cc_btn_accept_all)
cookie_warning_2 = browser.find_element_by_css_selector(
'.cc_btn.cc_btn_accept_all')
cookie_warning_2.click() #clik for close warning banner
#najdi nově přidanou cookie
cookies = browser.get_cookies()
[c['name'] for c in cookies if c not in cookies_old]
browser.delete_cookie('cookieconsent_dismissed')
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nhttp://selenium-python.readthedocs.io\nhttps://realpython.com/blog/python/modern-web-automation-with-python-and-selenium/\n\ndokumentace s příklady:\nhttps://media.readthedocs.org/pdf/selenium-python/latest/selenium-python.pdf\n \n\"\"\"\n\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.firefox.options import Options\nopts = Options()\nopts.set_headless(False)\nbrowser = Firefox(options=opts)\nbrowser.get('https://www.ihned.cz')\n\nx = browser.find_elements_by_class_name('article-title')\ny = x[0].find_element_by_tag_name(\"a\")\ny.click()\n\nbrowser.get_screenshot_as_file('./scrsht/img_1.png')\n\nbrowser.set_window_size(800,2048)\n\nbrowser.get_screenshot_as_file('./scrsht/img_2.png')\n\nbrowser.minimize_window()\nbrowser.maximize_window()\n\nbrowser.back()\nbrowser.refresh()\n\n\n\n# scroll\nbrowser.execute_script(\"window.scrollTo(0, 300)\") \ny = 900\nbrowser.execute_script(\"window.scrollTo(0, arguments[0])\", y) \n#where y is the height, předání pomocí y -> arguments[0]\n\nbrowser.set_window_size(300,600)\nx, y = 150, 1200\nbrowser.execute_script(\"window.scrollTo(arguments[0], arguments[1])\", x, y) \n\nbrowser.set_window_size(600,600)\n# scroll-down na konec okna\nbrowser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n\n\n\n#zavři cookie warning\ncookies = browser.get_cookies()\ncookies_old = cookies.copy()\n\n#umožňuje zadat jen 1 class\ncookie_warning_1 = browser.find_element_by_class_name('cc_btn_accept_all')\n\n#umožňuje zadat více classes (.cc_btn and .cc_btn_accept_all)\ncookie_warning_2 = browser.find_element_by_css_selector(\n '.cc_btn.cc_btn_accept_all')\n\ncookie_warning_2.click() #clik for close warning banner\n\n#najdi nově přidanou cookie\ncookies = browser.get_cookies()\n[c['name'] for c in cookies if c not in cookies_old]\n\nbrowser.delete_cookie('cookieconsent_dismissed') \n\n",
"<docstring token>\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.firefox.options import Options\nopts = Options()\nopts.set_headless(False)\nbrowser = Firefox(options=opts)\nbrowser.get('https://www.ihned.cz')\nx = browser.find_elements_by_class_name('article-title')\ny = x[0].find_element_by_tag_name('a')\ny.click()\nbrowser.get_screenshot_as_file('./scrsht/img_1.png')\nbrowser.set_window_size(800, 2048)\nbrowser.get_screenshot_as_file('./scrsht/img_2.png')\nbrowser.minimize_window()\nbrowser.maximize_window()\nbrowser.back()\nbrowser.refresh()\nbrowser.execute_script('window.scrollTo(0, 300)')\ny = 900\nbrowser.execute_script('window.scrollTo(0, arguments[0])', y)\nbrowser.set_window_size(300, 600)\nx, y = 150, 1200\nbrowser.execute_script('window.scrollTo(arguments[0], arguments[1])', x, y)\nbrowser.set_window_size(600, 600)\nbrowser.execute_script('window.scrollTo(0, document.body.scrollHeight);')\ncookies = browser.get_cookies()\ncookies_old = cookies.copy()\ncookie_warning_1 = browser.find_element_by_class_name('cc_btn_accept_all')\ncookie_warning_2 = browser.find_element_by_css_selector(\n '.cc_btn.cc_btn_accept_all')\ncookie_warning_2.click()\ncookies = browser.get_cookies()\n[c['name'] for c in cookies if c not in cookies_old]\nbrowser.delete_cookie('cookieconsent_dismissed')\n",
"<docstring token>\n<import token>\nopts = Options()\nopts.set_headless(False)\nbrowser = Firefox(options=opts)\nbrowser.get('https://www.ihned.cz')\nx = browser.find_elements_by_class_name('article-title')\ny = x[0].find_element_by_tag_name('a')\ny.click()\nbrowser.get_screenshot_as_file('./scrsht/img_1.png')\nbrowser.set_window_size(800, 2048)\nbrowser.get_screenshot_as_file('./scrsht/img_2.png')\nbrowser.minimize_window()\nbrowser.maximize_window()\nbrowser.back()\nbrowser.refresh()\nbrowser.execute_script('window.scrollTo(0, 300)')\ny = 900\nbrowser.execute_script('window.scrollTo(0, arguments[0])', y)\nbrowser.set_window_size(300, 600)\nx, y = 150, 1200\nbrowser.execute_script('window.scrollTo(arguments[0], arguments[1])', x, y)\nbrowser.set_window_size(600, 600)\nbrowser.execute_script('window.scrollTo(0, document.body.scrollHeight);')\ncookies = browser.get_cookies()\ncookies_old = cookies.copy()\ncookie_warning_1 = browser.find_element_by_class_name('cc_btn_accept_all')\ncookie_warning_2 = browser.find_element_by_css_selector(\n '.cc_btn.cc_btn_accept_all')\ncookie_warning_2.click()\ncookies = browser.get_cookies()\n[c['name'] for c in cookies if c not in cookies_old]\nbrowser.delete_cookie('cookieconsent_dismissed')\n",
"<docstring token>\n<import token>\n<assignment token>\nopts.set_headless(False)\n<assignment token>\nbrowser.get('https://www.ihned.cz')\n<assignment token>\ny.click()\nbrowser.get_screenshot_as_file('./scrsht/img_1.png')\nbrowser.set_window_size(800, 2048)\nbrowser.get_screenshot_as_file('./scrsht/img_2.png')\nbrowser.minimize_window()\nbrowser.maximize_window()\nbrowser.back()\nbrowser.refresh()\nbrowser.execute_script('window.scrollTo(0, 300)')\n<assignment token>\nbrowser.execute_script('window.scrollTo(0, arguments[0])', y)\nbrowser.set_window_size(300, 600)\n<assignment token>\nbrowser.execute_script('window.scrollTo(arguments[0], arguments[1])', x, y)\nbrowser.set_window_size(600, 600)\nbrowser.execute_script('window.scrollTo(0, document.body.scrollHeight);')\n<assignment token>\ncookie_warning_2.click()\n<assignment token>\n[c['name'] for c in cookies if c not in cookies_old]\nbrowser.delete_cookie('cookieconsent_dismissed')\n",
"<docstring token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment 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,908 | 920e987d7aefd02603b5d96c8e593a3c80547733 | #!/usr/bin/env python3
"""
Non-interactive tests for installer.
pytest files should start from `test_`
"""
import cluster_dev as installer # pylint: disable=unused-import # noqa: WPS110, F401
# Example usage:
def func(test_param):
"""Test something."""
return test_param + 1
def test_func():
"""Function for test func().
Test function should start from `test_`
"""
assert func(3) == 5 # noqa: S101
| [
"#!/usr/bin/env python3\n\"\"\"\nNon-interactive tests for installer.\n\npytest files should start from `test_`\n\"\"\"\nimport cluster_dev as installer # pylint: disable=unused-import # noqa: WPS110, F401\n\n# Example usage:\n\n\ndef func(test_param):\n \"\"\"Test something.\"\"\"\n return test_param + 1\n\n\ndef test_func():\n \"\"\"Function for test func().\n\n Test function should start from `test_`\n \"\"\"\n assert func(3) == 5 # noqa: S101\n",
"<docstring token>\nimport cluster_dev as installer\n\n\ndef func(test_param):\n \"\"\"Test something.\"\"\"\n return test_param + 1\n\n\ndef test_func():\n \"\"\"Function for test func().\n\n Test function should start from `test_`\n \"\"\"\n assert func(3) == 5\n",
"<docstring token>\n<import token>\n\n\ndef func(test_param):\n \"\"\"Test something.\"\"\"\n return test_param + 1\n\n\ndef test_func():\n \"\"\"Function for test func().\n\n Test function should start from `test_`\n \"\"\"\n assert func(3) == 5\n",
"<docstring token>\n<import token>\n<function token>\n\n\ndef test_func():\n \"\"\"Function for test func().\n\n Test function should start from `test_`\n \"\"\"\n assert func(3) == 5\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n"
] | false |
99,909 | 9638d2d2cc9f4777aeccfd237cae8bb14253c6b4 | #censor >> "this **** is wack ****"
text = "this hack is wack hack"
word = "hack"
def censor(text, word):
Z = []
for g in text.split():
if g != word:
Z.append(g)
elif g == word:
P = ""
for x in g:
x = "*"
P += x
Z.append(P)
return(" ".join(Z))
print(censor(text, word))
| [
"#censor >> \"this **** is wack ****\"\n\ntext = \"this hack is wack hack\"\nword = \"hack\"\n\ndef censor(text, word):\n Z = []\n for g in text.split():\n if g != word:\n Z.append(g)\n elif g == word:\n P = \"\"\n for x in g:\n x = \"*\"\n P += x\n Z.append(P)\n return(\" \".join(Z))\n\nprint(censor(text, word))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"text = 'this hack is wack hack'\nword = 'hack'\n\n\ndef censor(text, word):\n Z = []\n for g in text.split():\n if g != word:\n Z.append(g)\n elif g == word:\n P = ''\n for x in g:\n x = '*'\n P += x\n Z.append(P)\n return ' '.join(Z)\n\n\nprint(censor(text, word))\n",
"<assignment token>\n\n\ndef censor(text, word):\n Z = []\n for g in text.split():\n if g != word:\n Z.append(g)\n elif g == word:\n P = ''\n for x in g:\n x = '*'\n P += x\n Z.append(P)\n return ' '.join(Z)\n\n\nprint(censor(text, word))\n",
"<assignment token>\n\n\ndef censor(text, word):\n Z = []\n for g in text.split():\n if g != word:\n Z.append(g)\n elif g == word:\n P = ''\n for x in g:\n x = '*'\n P += x\n Z.append(P)\n return ' '.join(Z)\n\n\n<code token>\n",
"<assignment token>\n<function token>\n<code token>\n"
] | false |
99,910 | 5a8e34748e48e532036899ebea1d6c2506f8d4b7 | import copy
import random
D = list(map(int, input().split()))
q = int(input())
for x in range(q):
y, z = map(int, input().split())
while True:
r = random.randint(0,3)
if r == 0:
Dt = copy.copy(D)
temp = Dt[0]
Dt[0] = Dt[4]
Dt[4] = Dt[5]
Dt[5] = Dt[1]
Dt[1] = temp
elif r== 1:
Dt = copy.copy(D)
temp = Dt[0]
Dt[0] = Dt[2]
Dt[2] = Dt[5]
Dt[5] = Dt[3]
Dt[3] = temp
elif r== 2:
Dt = copy.copy(D)
temp = Dt[0]
Dt[0] = Dt[3]
Dt[3] = Dt[5]
Dt[5] = Dt[2]
Dt[2] = temp
elif r == 3:
Dt = copy.copy(D)
temp = Dt[0]
Dt[0] = Dt[1]
Dt[1] = Dt[5]
Dt[5] = Dt[4]
Dt[4] = temp
D = copy.copy(Dt)
if Dt[0] == y and Dt[1] == z:
print(Dt[2])
break
| [
"import copy\nimport random\n\nD = list(map(int, input().split()))\nq = int(input())\n\nfor x in range(q):\n y, z = map(int, input().split())\n while True:\n r = random.randint(0,3)\n if r == 0:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[4]\n Dt[4] = Dt[5]\n Dt[5] = Dt[1]\n Dt[1] = temp\n elif r== 1:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[2]\n Dt[2] = Dt[5]\n Dt[5] = Dt[3]\n Dt[3] = temp\n elif r== 2:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[3]\n Dt[3] = Dt[5]\n Dt[5] = Dt[2]\n Dt[2] = temp\n elif r == 3:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[1]\n Dt[1] = Dt[5]\n Dt[5] = Dt[4]\n Dt[4] = temp\n\n D = copy.copy(Dt)\n if Dt[0] == y and Dt[1] == z:\n print(Dt[2])\n break\n\n",
"import copy\nimport random\nD = list(map(int, input().split()))\nq = int(input())\nfor x in range(q):\n y, z = map(int, input().split())\n while True:\n r = random.randint(0, 3)\n if r == 0:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[4]\n Dt[4] = Dt[5]\n Dt[5] = Dt[1]\n Dt[1] = temp\n elif r == 1:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[2]\n Dt[2] = Dt[5]\n Dt[5] = Dt[3]\n Dt[3] = temp\n elif r == 2:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[3]\n Dt[3] = Dt[5]\n Dt[5] = Dt[2]\n Dt[2] = temp\n elif r == 3:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[1]\n Dt[1] = Dt[5]\n Dt[5] = Dt[4]\n Dt[4] = temp\n D = copy.copy(Dt)\n if Dt[0] == y and Dt[1] == z:\n print(Dt[2])\n break\n",
"<import token>\nD = list(map(int, input().split()))\nq = int(input())\nfor x in range(q):\n y, z = map(int, input().split())\n while True:\n r = random.randint(0, 3)\n if r == 0:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[4]\n Dt[4] = Dt[5]\n Dt[5] = Dt[1]\n Dt[1] = temp\n elif r == 1:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[2]\n Dt[2] = Dt[5]\n Dt[5] = Dt[3]\n Dt[3] = temp\n elif r == 2:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[3]\n Dt[3] = Dt[5]\n Dt[5] = Dt[2]\n Dt[2] = temp\n elif r == 3:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[1]\n Dt[1] = Dt[5]\n Dt[5] = Dt[4]\n Dt[4] = temp\n D = copy.copy(Dt)\n if Dt[0] == y and Dt[1] == z:\n print(Dt[2])\n break\n",
"<import token>\n<assignment token>\nfor x in range(q):\n y, z = map(int, input().split())\n while True:\n r = random.randint(0, 3)\n if r == 0:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[4]\n Dt[4] = Dt[5]\n Dt[5] = Dt[1]\n Dt[1] = temp\n elif r == 1:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[2]\n Dt[2] = Dt[5]\n Dt[5] = Dt[3]\n Dt[3] = temp\n elif r == 2:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[3]\n Dt[3] = Dt[5]\n Dt[5] = Dt[2]\n Dt[2] = temp\n elif r == 3:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[1]\n Dt[1] = Dt[5]\n Dt[5] = Dt[4]\n Dt[4] = temp\n D = copy.copy(Dt)\n if Dt[0] == y and Dt[1] == z:\n print(Dt[2])\n break\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,911 | 32a73965fd70a27f68a4884a2e3738e15a5dfd05 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyriskadjust` package."""
import unittest
import json
from pyriskadjust.models import model_2018_v22
class TestPyriskadjust(unittest.TestCase):
"""Tests for `pyriskadjust` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures, if any."""
def test_model_community_aged_nondual(self):
self.assertEqual(
json.dumps(
model_2018_v22.compute_risk_score_components(
["E1169", "I5030", "I509", "I211", "I209", "R05"], age=70, sex=1
),
sort_keys=True,
indent=2,
),
json.dumps(
{
"cna_m70_74": 0.379,
"cna_hcc88": 0.14,
"cna_hcc18": 0.318,
"cna_hcc85": 0.323,
"cna_hcc85_gdiabetesmellit": 0.154,
},
sort_keys=True,
indent=2,
),
)
def test_explain_total(self):
explanation = model_2018_v22.explain_score(
{
"cna_m70_74": 0.379,
"cna_hcc88": 0.14,
"cna_hcc18": 0.318,
"cna_hcc85": 0.323,
"cna_hcc85_gdiabetesmellit": 0.154,
}
)
self.assertEqual(explanation["total"], 1.314)
self.assertEqual(
json.dumps(explanation["demographic_components"][0], sort_keys=True),
json.dumps(
{
"variable_name": "cna_m70_74",
"score": 0.379,
"description": "Male with age in range 70 to 74",
},
sort_keys=True,
),
)
self.assertEqual(
json.dumps(explanation["interaction_components"][0], sort_keys=True),
json.dumps(
{
"variable_name": "cna_hcc85_gdiabetesmellit",
"score": 0.154,
"description": "Congestive Heart Failure & Diabetes",
},
sort_keys=True,
),
)
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n\nimport unittest\nimport json\nfrom pyriskadjust.models import model_2018_v22\n\n\nclass TestPyriskadjust(unittest.TestCase):\n \"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(\n json.dumps(\n model_2018_v22.compute_risk_score_components(\n [\"E1169\", \"I5030\", \"I509\", \"I211\", \"I209\", \"R05\"], age=70, sex=1\n ),\n sort_keys=True,\n indent=2,\n ),\n json.dumps(\n {\n \"cna_m70_74\": 0.379,\n \"cna_hcc88\": 0.14,\n \"cna_hcc18\": 0.318,\n \"cna_hcc85\": 0.323,\n \"cna_hcc85_gdiabetesmellit\": 0.154,\n },\n sort_keys=True,\n indent=2,\n ),\n )\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score(\n {\n \"cna_m70_74\": 0.379,\n \"cna_hcc88\": 0.14,\n \"cna_hcc18\": 0.318,\n \"cna_hcc85\": 0.323,\n \"cna_hcc85_gdiabetesmellit\": 0.154,\n }\n )\n self.assertEqual(explanation[\"total\"], 1.314)\n self.assertEqual(\n json.dumps(explanation[\"demographic_components\"][0], sort_keys=True),\n json.dumps(\n {\n \"variable_name\": \"cna_m70_74\",\n \"score\": 0.379,\n \"description\": \"Male with age in range 70 to 74\",\n },\n sort_keys=True,\n ),\n )\n self.assertEqual(\n json.dumps(explanation[\"interaction_components\"][0], sort_keys=True),\n json.dumps(\n {\n \"variable_name\": \"cna_hcc85_gdiabetesmellit\",\n \"score\": 0.154,\n \"description\": \"Congestive Heart Failure & Diabetes\",\n },\n sort_keys=True,\n ),\n )\n",
"<docstring token>\nimport unittest\nimport json\nfrom pyriskadjust.models import model_2018_v22\n\n\nclass TestPyriskadjust(unittest.TestCase):\n \"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(json.dumps(model_2018_v22.\n compute_risk_score_components(['E1169', 'I5030', 'I509', 'I211',\n 'I209', 'R05'], age=70, sex=1), sort_keys=True, indent=2), json\n .dumps({'cna_m70_74': 0.379, 'cna_hcc88': 0.14, 'cna_hcc18': \n 0.318, 'cna_hcc85': 0.323, 'cna_hcc85_gdiabetesmellit': 0.154},\n sort_keys=True, indent=2))\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n \"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(json.dumps(model_2018_v22.\n compute_risk_score_components(['E1169', 'I5030', 'I509', 'I211',\n 'I209', 'R05'], age=70, sex=1), sort_keys=True, indent=2), json\n .dumps({'cna_m70_74': 0.379, 'cna_hcc88': 0.14, 'cna_hcc18': \n 0.318, 'cna_hcc85': 0.323, 'cna_hcc85_gdiabetesmellit': 0.154},\n sort_keys=True, indent=2))\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n <docstring token>\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(json.dumps(model_2018_v22.\n compute_risk_score_components(['E1169', 'I5030', 'I509', 'I211',\n 'I209', 'R05'], age=70, sex=1), sort_keys=True, indent=2), json\n .dumps({'cna_m70_74': 0.379, 'cna_hcc88': 0.14, 'cna_hcc18': \n 0.318, 'cna_hcc85': 0.323, 'cna_hcc85_gdiabetesmellit': 0.154},\n sort_keys=True, indent=2))\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n <docstring token>\n\n def setUp(self):\n \"\"\"Set up test fixtures, if any.\"\"\"\n <function token>\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(json.dumps(model_2018_v22.\n compute_risk_score_components(['E1169', 'I5030', 'I509', 'I211',\n 'I209', 'R05'], age=70, sex=1), sort_keys=True, indent=2), json\n .dumps({'cna_m70_74': 0.379, 'cna_hcc88': 0.14, 'cna_hcc18': \n 0.318, 'cna_hcc85': 0.323, 'cna_hcc85_gdiabetesmellit': 0.154},\n sort_keys=True, indent=2))\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n\n def test_model_community_aged_nondual(self):\n self.assertEqual(json.dumps(model_2018_v22.\n compute_risk_score_components(['E1169', 'I5030', 'I509', 'I211',\n 'I209', 'R05'], age=70, sex=1), sort_keys=True, indent=2), json\n .dumps({'cna_m70_74': 0.379, 'cna_hcc88': 0.14, 'cna_hcc18': \n 0.318, 'cna_hcc85': 0.323, 'cna_hcc85_gdiabetesmellit': 0.154},\n sort_keys=True, indent=2))\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def test_explain_total(self):\n explanation = model_2018_v22.explain_score({'cna_m70_74': 0.379,\n 'cna_hcc88': 0.14, 'cna_hcc18': 0.318, 'cna_hcc85': 0.323,\n 'cna_hcc85_gdiabetesmellit': 0.154})\n self.assertEqual(explanation['total'], 1.314)\n self.assertEqual(json.dumps(explanation['demographic_components'][0\n ], sort_keys=True), json.dumps({'variable_name': 'cna_m70_74',\n 'score': 0.379, 'description':\n 'Male with age in range 70 to 74'}, sort_keys=True))\n self.assertEqual(json.dumps(explanation['interaction_components'][0\n ], sort_keys=True), json.dumps({'variable_name':\n 'cna_hcc85_gdiabetesmellit', 'score': 0.154, 'description':\n 'Congestive Heart Failure & Diabetes'}, sort_keys=True))\n",
"<docstring token>\n<import token>\n\n\nclass TestPyriskadjust(unittest.TestCase):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<class token>\n"
] | false |
99,912 | 4c3fb19a90ebabbed4fc3193b38fec720eb27dc9 | #
# [222] Count Complete Tree Nodes
#
# https://leetcode.com/problems/count-complete-tree-nodes
#
# Medium (27.30%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[]'
#
# Given a complete binary tree, count the number of nodes.
#
# Definition of a complete binary tree from Wikipedia:
# In a complete binary tree every level, except possibly the last, is
# completely filled, and all nodes in the last level are as far left as
# possible. It can have between 1 and 2h nodes inclusive at the last level h.
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
| [
"#\r\n# [222] Count Complete Tree Nodes\r\n#\r\n# https://leetcode.com/problems/count-complete-tree-nodes\r\n#\r\n# Medium (27.30%)\r\n# Total Accepted: \r\n# Total Submissions: \r\n# Testcase Example: '[]'\r\n#\r\n# Given a complete binary tree, count the number of nodes.\r\n# \r\n# Definition of a complete binary tree from Wikipedia:\r\n# In a complete binary tree every level, except possibly the last, is\r\n# completely filled, and all nodes in the last level are as far left as\r\n# possible. It can have between 1 and 2h nodes inclusive at the last level h.\r\n#\r\n# Definition for a binary tree node.\r\n# class TreeNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nclass Solution(object):\r\n def countNodes(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: int\r\n \"\"\"\r\n \r\n",
"class Solution(object):\n\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n",
"class Solution(object):\n <function token>\n",
"<class token>\n"
] | false |
99,913 | a4aad2760de34fde725a59a148e85b86f5e6e673 | import numpy as np
from numpy import *
from numpy.linalg import inv
import MahalanobisDistance
from os import listdir
"""rawdata has n rows
## Create arr_groupvariance to store variance of each group of 5 rows (has n/5 rows)"""
arr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv',
dtype=float, delimiter=',')
arr_groupvariance = arange((len(arr_rawdata)) / 5, dtype=float32).reshape(
(len(arr_rawdata)) / 5, 1)
"""Compute MDistance between Origin and the Variance of group of 5 rows.
We use 4 most important features only
Results in arr_groupvariance containing variances for all groups for all users [x, k]"""
row = -5
i_groups = 0
while row < len(arr_rawdata):
arr_groups = array(arr_rawdata[row + 5:row + 10, [4, 8, 14, 19]])
arr_reference = zeros_like(var(arr_groups, axis=0))
while True:
try:
MDistance = MahalanobisDistance.ComputeMdistVector(arr_groups,
arr_reference)
arr_groupvariance[i_groups, 0] = MDistance
break
except:
print(0)
break
i_groups += 1
row += 5
arr_allvariance = arr_groupvariance.reshape(31, ((len(arr_rawdata)) / 5) / 31)
np.savetxt("../../Output Files/Experiment20/MdistVariance1.csv",
np.transpose(arr_allvariance), delimiter=",")
| [
"import numpy as np\nfrom numpy import *\nfrom numpy.linalg import inv\nimport MahalanobisDistance\nfrom os import listdir\n\n\"\"\"rawdata has n rows\n## Create arr_groupvariance to store variance of each group of 5 rows (has n/5 rows)\"\"\"\n\narr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv',\n dtype=float, delimiter=',')\narr_groupvariance = arange((len(arr_rawdata)) / 5, dtype=float32).reshape(\n (len(arr_rawdata)) / 5, 1)\n\n\"\"\"Compute MDistance between Origin and the Variance of group of 5 rows.\n We use 4 most important features only\n Results in arr_groupvariance containing variances for all groups for all users [x, k]\"\"\"\n\nrow = -5\ni_groups = 0\nwhile row < len(arr_rawdata):\n arr_groups = array(arr_rawdata[row + 5:row + 10, [4, 8, 14, 19]])\n arr_reference = zeros_like(var(arr_groups, axis=0))\n while True:\n try:\n MDistance = MahalanobisDistance.ComputeMdistVector(arr_groups,\n arr_reference)\n arr_groupvariance[i_groups, 0] = MDistance\n break\n except:\n print(0)\n break\n i_groups += 1\n row += 5\n\narr_allvariance = arr_groupvariance.reshape(31, ((len(arr_rawdata)) / 5) / 31)\n\nnp.savetxt(\"../../Output Files/Experiment20/MdistVariance1.csv\",\n np.transpose(arr_allvariance), delimiter=\",\")\n",
"import numpy as np\nfrom numpy import *\nfrom numpy.linalg import inv\nimport MahalanobisDistance\nfrom os import listdir\n<docstring token>\narr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv', dtype=\n float, delimiter=',')\narr_groupvariance = arange(len(arr_rawdata) / 5, dtype=float32).reshape(len\n (arr_rawdata) / 5, 1)\n<docstring token>\nrow = -5\ni_groups = 0\nwhile row < len(arr_rawdata):\n arr_groups = array(arr_rawdata[row + 5:row + 10, [4, 8, 14, 19]])\n arr_reference = zeros_like(var(arr_groups, axis=0))\n while True:\n try:\n MDistance = MahalanobisDistance.ComputeMdistVector(arr_groups,\n arr_reference)\n arr_groupvariance[i_groups, 0] = MDistance\n break\n except:\n print(0)\n break\n i_groups += 1\n row += 5\narr_allvariance = arr_groupvariance.reshape(31, len(arr_rawdata) / 5 / 31)\nnp.savetxt('../../Output Files/Experiment20/MdistVariance1.csv', np.\n transpose(arr_allvariance), delimiter=',')\n",
"<import token>\n<docstring token>\narr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv', dtype=\n float, delimiter=',')\narr_groupvariance = arange(len(arr_rawdata) / 5, dtype=float32).reshape(len\n (arr_rawdata) / 5, 1)\n<docstring token>\nrow = -5\ni_groups = 0\nwhile row < len(arr_rawdata):\n arr_groups = array(arr_rawdata[row + 5:row + 10, [4, 8, 14, 19]])\n arr_reference = zeros_like(var(arr_groups, axis=0))\n while True:\n try:\n MDistance = MahalanobisDistance.ComputeMdistVector(arr_groups,\n arr_reference)\n arr_groupvariance[i_groups, 0] = MDistance\n break\n except:\n print(0)\n break\n i_groups += 1\n row += 5\narr_allvariance = arr_groupvariance.reshape(31, len(arr_rawdata) / 5 / 31)\nnp.savetxt('../../Output Files/Experiment20/MdistVariance1.csv', np.\n transpose(arr_allvariance), delimiter=',')\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<assignment token>\nwhile row < len(arr_rawdata):\n arr_groups = array(arr_rawdata[row + 5:row + 10, [4, 8, 14, 19]])\n arr_reference = zeros_like(var(arr_groups, axis=0))\n while True:\n try:\n MDistance = MahalanobisDistance.ComputeMdistVector(arr_groups,\n arr_reference)\n arr_groupvariance[i_groups, 0] = MDistance\n break\n except:\n print(0)\n break\n i_groups += 1\n row += 5\n<assignment token>\nnp.savetxt('../../Output Files/Experiment20/MdistVariance1.csv', np.\n transpose(arr_allvariance), delimiter=',')\n",
"<import token>\n<docstring token>\n<assignment token>\n<docstring token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,914 | 9cd6b07d724922d9d6568483fd5cbc5a0d0c886a | import ftplib
import os
| [
"import ftplib\nimport os\n\n",
"import ftplib\nimport os\n",
"<import token>\n"
] | false |
99,915 | 5dac538485abb64388974ba3201084a779d5e9cf | # Adaptar o programa desenvolvido acima para que ela calcule o percentual dos valores positivos e
# negativos em relação ao total de valores fornecidos.
positivos, negativos = 0, 0
total = 1
num = int(input("Informe um número: "))
while (num != 0):
if num > 0:
positivos += 1
if num < 0:
negativos += 1
num = int(input("Informe um número: "))
total += 1
print("Positivos: %.1f%%" %((positivos/total)*100))
print("Negativos: %.1f%%" %((negativos/total)*100)) | [
"# Adaptar o programa desenvolvido acima para que ela calcule o percentual dos valores positivos e\n# negativos em relação ao total de valores fornecidos.\n\npositivos, negativos = 0, 0\ntotal = 1\nnum = int(input(\"Informe um número: \"))\nwhile (num != 0):\n if num > 0:\n positivos += 1\n if num < 0:\n negativos += 1\n num = int(input(\"Informe um número: \"))\n total += 1\n\nprint(\"Positivos: %.1f%%\" %((positivos/total)*100))\nprint(\"Negativos: %.1f%%\" %((negativos/total)*100))",
"positivos, negativos = 0, 0\ntotal = 1\nnum = int(input('Informe um número: '))\nwhile num != 0:\n if num > 0:\n positivos += 1\n if num < 0:\n negativos += 1\n num = int(input('Informe um número: '))\n total += 1\nprint('Positivos: %.1f%%' % (positivos / total * 100))\nprint('Negativos: %.1f%%' % (negativos / total * 100))\n",
"<assignment token>\nwhile num != 0:\n if num > 0:\n positivos += 1\n if num < 0:\n negativos += 1\n num = int(input('Informe um número: '))\n total += 1\nprint('Positivos: %.1f%%' % (positivos / total * 100))\nprint('Negativos: %.1f%%' % (negativos / total * 100))\n",
"<assignment token>\n<code token>\n"
] | false |
99,916 | 2f6e85ef5154e92e270adda5b92ff5e51cf0e22f | # -*- coding: utf-8 -*-
# 震惊小伙伴的单行代码(Python篇)
# 1、让列表中的每个元素都乘以2
print map(lambda x: x * 2, range(1, 11))
# 2、求列表中的所有元素之和
print sum(range(1, 1001))
# 3、判断一个字符串中是否存在某些词
wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"]
tweet = "This is an example tweet talking about scala and sbt."
print map(lambda x: x in tweet.split(), wordlist)
# 4、读取文件
print open("test_oneline.py").readlines()
# 5、祝你生日快乐!
print map(lambda x: "Happy Birthday to " + ("you" if x != 2 else "dear Name"), range(4))
# 6. 过滤列表中的数值
print reduce(lambda(a, b), c: (a+[c], b) if c > 60 else (a, b + [c]), [49, 58, 76, 82, 88, 90], ([], []))
# 7. 获取XML web service数据并分析
from xml.dom.minidom import parse, parseString
import urllib2
# 注意,我将它转换成XML格式化并打印出来
print parse(urllib2.urlopen("http://search.twitter.com/search.atom?&q=python")).toprettyxml(encoding="utf-8")
# 8. 找到列表中最小或最大的一个数字
print min([14, 35, -7, 46, 98])
print max([14, 35, -7, 46, 98])
# 9. 并行处理
import multiprocessing
import math
print list(multiprocessing.Pool(processes=4).map(math.exp, range(1, 11)))
# 10. “Sieve of Eratosthenes”算法
# Python里没有Sieve of Eratosthenes操作符,但这对于Python来说并不是难事。
n = 50 # We want to find prime numbers between 2 and 50
print sorted(set(range(2, n+1)).difference(set((p * f) for p in range(2, int(n**0.5) + 2) for f in range(2, (n/p)+1))))
| [
"# -*- coding: utf-8 -*-\n\n# 震惊小伙伴的单行代码(Python篇)\n\n# 1、让列表中的每个元素都乘以2\n\nprint map(lambda x: x * 2, range(1, 11))\n\n# 2、求列表中的所有元素之和\n\nprint sum(range(1, 1001))\n\n# 3、判断一个字符串中是否存在某些词\n\nwordlist = [\"scala\", \"akka\", \"play framework\", \"sbt\", \"typesafe\"]\ntweet = \"This is an example tweet talking about scala and sbt.\"\n\nprint map(lambda x: x in tweet.split(), wordlist)\n\n# 4、读取文件\nprint open(\"test_oneline.py\").readlines()\n\n# 5、祝你生日快乐!\nprint map(lambda x: \"Happy Birthday to \" + (\"you\" if x != 2 else \"dear Name\"), range(4))\n\n# 6. 过滤列表中的数值\nprint reduce(lambda(a, b), c: (a+[c], b) if c > 60 else (a, b + [c]), [49, 58, 76, 82, 88, 90], ([], []))\n\n# 7. 获取XML web service数据并分析\n\nfrom xml.dom.minidom import parse, parseString\nimport urllib2\n\n# 注意,我将它转换成XML格式化并打印出来\nprint parse(urllib2.urlopen(\"http://search.twitter.com/search.atom?&q=python\")).toprettyxml(encoding=\"utf-8\")\n\n# 8. 找到列表中最小或最大的一个数字\n\nprint min([14, 35, -7, 46, 98])\nprint max([14, 35, -7, 46, 98])\n\n# 9. 并行处理\n\nimport multiprocessing\nimport math\n\nprint list(multiprocessing.Pool(processes=4).map(math.exp, range(1, 11)))\n\n# 10. “Sieve of Eratosthenes”算法\n\n# Python里没有Sieve of Eratosthenes操作符,但这对于Python来说并不是难事。\n\nn = 50 # We want to find prime numbers between 2 and 50\n\nprint sorted(set(range(2, n+1)).difference(set((p * f) for p in range(2, int(n**0.5) + 2) for f in range(2, (n/p)+1))))\n\n"
] | true |
99,917 | 9af1005a865196e45664e7a353e33c32f4814e6c | #! /usr/bin/env python2
#
# This file is part of khmer, http://github.com/ged-lab/khmer`, and is
# Copyright (C) Michigan State University, 2009-2014. It is licensed under
# the three-clause BSD license; see doc/LICENSE.txt.
# Contact: khmer-project@idyll.org
# Author Sherine Awad
import sys, getopt
import glob
from collections import defaultdict
import numpy
import argparse
def main(argv):
parser=argparse.ArgumentParser()
parser.add_argument("outfile", help="Enter output file name")
args=parser.parse_args()
outfp=args.outfile
nones=0
snps=0
index=1
vcfs=list()
filelist = glob.glob('*.vcf')
dic={}
outfp=open(sys.argv[1], 'w')
j=0
for every in filelist:
name=every.split('.')
vcf=name[0]
vcfs.append(vcf)
mat=numpy.zeros((2000000,len(vcfs)+2),int)
indeces= []
indeces.append('zero')
for r1 in filelist:
print 'processing', r1, index
i=0
j=j+1
for line in open(r1):
i=i+1
rec=line.split('\t')
if line.startswith('#'):
continue
else:
ivalue=str(rec[0])+'-'+str(rec[1])
if(ivalue in indeces):
oldindex=indeces.index(ivalue)
mat[oldindex][j]=1
else:
mat[index][j]=1
indeces.append(ivalue)
index+=1
print len(indeces)
deli=" "
zero="0"
one="1"
outfp.write(str(' ').rstrip('\n'))
outfp.write(str(deli).rstrip('\n'))
for every in vcfs:
outfp.write(str(every).rstrip('\n'))
outfp.write(str(deli).rstrip('\n'))
print >> outfp ,'\n'
itr1=1
while itr1 < len(indeces) :
itr2=1
outfp.write(str(indeces[itr1]).rstrip('\n'))
outfp.write(str(deli).rstrip('\n'))
while itr2 <= j:
outfp.write(str(mat[itr1][itr2]).rstrip('\n'))
outfp.write(str(deli).rstrip('\n'))
itr2+=1
print >> outfp ,'\n'
itr1+=1
outfp.close()
if __name__ == '__main__':
main(sys.argv[1:])
| [
"#! /usr/bin/env python2\n#\n# This file is part of khmer, http://github.com/ged-lab/khmer`, and is\n# Copyright (C) Michigan State University, 2009-2014. It is licensed under\n# the three-clause BSD license; see doc/LICENSE.txt.\n# Contact: khmer-project@idyll.org\n# Author Sherine Awad\nimport sys, getopt\nimport glob\nfrom collections import defaultdict\nimport numpy\nimport argparse\n\ndef main(argv):\n \n parser=argparse.ArgumentParser()\n parser.add_argument(\"outfile\", help=\"Enter output file name\") \n args=parser.parse_args()\n outfp=args.outfile\n nones=0\n snps=0\n index=1\n vcfs=list()\n filelist = glob.glob('*.vcf')\n dic={}\n outfp=open(sys.argv[1], 'w') \n j=0\n for every in filelist:\n name=every.split('.')\n vcf=name[0]\n vcfs.append(vcf)\n mat=numpy.zeros((2000000,len(vcfs)+2),int)\n indeces= []\n indeces.append('zero')\n for r1 in filelist:\n print 'processing', r1, index\n i=0\n j=j+1\n for line in open(r1):\n i=i+1 \n rec=line.split('\\t')\n if line.startswith('#'): \n continue \n \n else:\n ivalue=str(rec[0])+'-'+str(rec[1])\n if(ivalue in indeces):\n oldindex=indeces.index(ivalue)\n mat[oldindex][j]=1\n else: \n mat[index][j]=1\n indeces.append(ivalue)\n index+=1\n print len(indeces)\n deli=\" \"\n zero=\"0\"\n one=\"1\"\n outfp.write(str(' ').rstrip('\\n'))\n outfp.write(str(deli).rstrip('\\n'))\n for every in vcfs:\n outfp.write(str(every).rstrip('\\n'))\n outfp.write(str(deli).rstrip('\\n'))\n print >> outfp ,'\\n'\n itr1=1\n while itr1 < len(indeces) :\n itr2=1 \n outfp.write(str(indeces[itr1]).rstrip('\\n')) \n outfp.write(str(deli).rstrip('\\n'))\n while itr2 <= j: \n outfp.write(str(mat[itr1][itr2]).rstrip('\\n'))\n outfp.write(str(deli).rstrip('\\n'))\n itr2+=1 \n print >> outfp ,'\\n' \n itr1+=1 \n outfp.close()\nif __name__ == '__main__':\n main(sys.argv[1:])\n"
] | true |
99,918 | 09d50bcb40089bd2213279b156c77943653d631b | """
Collection of models.
""" | [
"\"\"\"\nCollection of models.\n\"\"\"",
"<docstring token>\n"
] | false |
99,919 | 1a1a1c2de774ae8c79004824678fabd5b2029a01 | # Write a Python function that takes a list of words and returns the length of the longest one
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
l=['cnxvjxnlkxnlxc','kjgnfxkjvkfjnvklxnv','xkjvbfkjbvjkxznvkjxcnvkjzcxnvjzxcnv','jfvjcgcb','ggg']
max_s=l[0]
for i in l:
if len(max_s) < len(i):
max_s=i
print("The maximum length string is: '{}'".format(max_s))
### we can still do like
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
print(word_len)
word_len.sort()
print(word_len)
return word_len[-1][1]
print(find_longest_word(["PHP", "Exercises", "Backend"])) | [
"# Write a Python function that takes a list of words and returns the length of the longest one\n#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6\nl=['cnxvjxnlkxnlxc','kjgnfxkjvkfjnvklxnv','xkjvbfkjbvjkxznvkjxcnvkjzcxnvjzxcnv','jfvjcgcb','ggg']\nmax_s=l[0]\nfor i in l:\n if len(max_s) < len(i):\n max_s=i\nprint(\"The maximum length string is: '{}'\".format(max_s))\n\n\n### we can still do like\ndef find_longest_word(words_list):\n word_len = []\n for n in words_list:\n word_len.append((len(n), n))\n print(word_len)\n word_len.sort()\n print(word_len)\n return word_len[-1][1]\n\nprint(find_longest_word([\"PHP\", \"Exercises\", \"Backend\"]))",
"l = ['cnxvjxnlkxnlxc', 'kjgnfxkjvkfjnvklxnv',\n 'xkjvbfkjbvjkxznvkjxcnvkjzcxnvjzxcnv', 'jfvjcgcb', 'ggg']\nmax_s = l[0]\nfor i in l:\n if len(max_s) < len(i):\n max_s = i\nprint(\"The maximum length string is: '{}'\".format(max_s))\n\n\ndef find_longest_word(words_list):\n word_len = []\n for n in words_list:\n word_len.append((len(n), n))\n print(word_len)\n word_len.sort()\n print(word_len)\n return word_len[-1][1]\n\n\nprint(find_longest_word(['PHP', 'Exercises', 'Backend']))\n",
"<assignment token>\nfor i in l:\n if len(max_s) < len(i):\n max_s = i\nprint(\"The maximum length string is: '{}'\".format(max_s))\n\n\ndef find_longest_word(words_list):\n word_len = []\n for n in words_list:\n word_len.append((len(n), n))\n print(word_len)\n word_len.sort()\n print(word_len)\n return word_len[-1][1]\n\n\nprint(find_longest_word(['PHP', 'Exercises', 'Backend']))\n",
"<assignment token>\n<code token>\n\n\ndef find_longest_word(words_list):\n word_len = []\n for n in words_list:\n word_len.append((len(n), n))\n print(word_len)\n word_len.sort()\n print(word_len)\n return word_len[-1][1]\n\n\n<code token>\n",
"<assignment token>\n<code token>\n<function token>\n<code token>\n"
] | false |
99,920 | 28d4cf5fd4193fbf8a2ccc5484fd5ac7bd7bfc1f | from abc import ABCMeta, abstractmethod
from conformal_predictors.validation import NotCalibratedError
from conformal_predictors.nc_measures import NCMeasure
import numpy as np
from decimal import *
class ConformalPredictor:
"""
Abstract class that represents the Conformal Predictors and defines their
basic functionality
"""
_metaclass_ = ABCMeta
def __init__(self, nc_measure: NCMeasure, clf) -> None:
"""
Initialises the conformal predictor
:param nc_measure: nonconformity measure to be used
:param clf: classifier
"""
self._nc_measure = nc_measure # Non-conformity measure
self._clf = clf # Classifier
self._cal_l = None # Calibration labels
self._cal_a = None # Calibration alphas
def is_calibrated(self):
"""
Establish if a conformal predictor is calibrated (the calibration set
is not null)
:return: 'True' if the calibration set is populated, ´false´ otherwise
"""
return not ((self._cal_a is None) or
(self._cal_l is None))
def check_calibrated(self):
"""
This method raises a NotCalibratedError if the conformal predictor is
not calibrated
:return:
"""
if not self.is_calibrated():
raise NotCalibratedError()
@abstractmethod
def predict_cf(self, x, **kwargs):
"""
It classifies the samples on X and adds conformal measures
:param x:
:return:
"""
pass
@abstractmethod
def calibrate(self, x, y) -> None:
"""
Method that calibrates the conformal predictor using the calibration
set in x
:param x: array-like, shape (n_samples, n_features)
:return: nothing
"""
pass
@abstractmethod
def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array = np.empty(0)) -> None:
"""
Fits the SVM model according to the given training data
:param x: {array-like, sparse matrix}, shape (n_samples, n_features).
Training vectors, where n_samples is the number of samples and
n_features is the number of features. For kernel="precomputed", the
expected shape of X is (n_samples, n_samples).
:param y: array-like, shape (n_samples,). Target values (class labels
in classification, real number in regression)
:param sample_weight: array-like, shape (n_samples,). Per-sample
weights. Rescale C per sample. Higher weights force the classifier to
put more emphasis on these points.
:return: nothing
"""
pass
def compute_pvalue(self, alphas) -> float:
resolution = 10000
pvalues = np.array([0.0] * len(alphas))
for i in range(0, len(alphas)):
index = np.ix_(self._cal_l == self._clf.classes_[i])
calibration = np.round(
(np.array(self._cal_a)[index] * resolution).astype(int))
alpha = int(np.round(alphas[i] * resolution))
pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)
return pvalues
| [
"from abc import ABCMeta, abstractmethod\nfrom conformal_predictors.validation import NotCalibratedError\nfrom conformal_predictors.nc_measures import NCMeasure\nimport numpy as np\nfrom decimal import *\n\n\nclass ConformalPredictor:\n \"\"\"\n Abstract class that represents the Conformal Predictors and defines their\n basic functionality\n \"\"\"\n\n _metaclass_ = ABCMeta\n\n def __init__(self, nc_measure: NCMeasure, clf) -> None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure # Non-conformity measure\n self._clf = clf # Classifier\n self._cal_l = None # Calibration labels\n self._cal_a = None # Calibration alphas\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not ((self._cal_a is None) or\n (self._cal_l is None))\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) -> None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n\n @abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array = np.empty(0)) -> None:\n \"\"\"\n Fits the SVM model according to the given training data\n\n :param x: {array-like, sparse matrix}, shape (n_samples, n_features).\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features. For kernel=\"precomputed\", the\n expected shape of X is (n_samples, n_samples).\n :param y: array-like, shape (n_samples,). Target values (class labels\n in classification, real number in regression)\n :param sample_weight: array-like, shape (n_samples,). Per-sample\n weights. Rescale C per sample. Higher weights force the classifier to\n put more emphasis on these points.\n :return: nothing\n \"\"\"\n pass\n\n def compute_pvalue(self, alphas) -> float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round(\n (np.array(self._cal_a)[index] * resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n\n return pvalues\n",
"from abc import ABCMeta, abstractmethod\nfrom conformal_predictors.validation import NotCalibratedError\nfrom conformal_predictors.nc_measures import NCMeasure\nimport numpy as np\nfrom decimal import *\n\n\nclass ConformalPredictor:\n \"\"\"\n Abstract class that represents the Conformal Predictors and defines their\n basic functionality\n \"\"\"\n _metaclass_ = ABCMeta\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n\n @abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array=np.\n empty(0)) ->None:\n \"\"\"\n Fits the SVM model according to the given training data\n\n :param x: {array-like, sparse matrix}, shape (n_samples, n_features).\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features. For kernel=\"precomputed\", the\n expected shape of X is (n_samples, n_samples).\n :param y: array-like, shape (n_samples,). Target values (class labels\n in classification, real number in regression)\n :param sample_weight: array-like, shape (n_samples,). Per-sample\n weights. Rescale C per sample. Higher weights force the classifier to\n put more emphasis on these points.\n :return: nothing\n \"\"\"\n pass\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n \"\"\"\n Abstract class that represents the Conformal Predictors and defines their\n basic functionality\n \"\"\"\n _metaclass_ = ABCMeta\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n\n @abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array=np.\n empty(0)) ->None:\n \"\"\"\n Fits the SVM model according to the given training data\n\n :param x: {array-like, sparse matrix}, shape (n_samples, n_features).\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features. For kernel=\"precomputed\", the\n expected shape of X is (n_samples, n_samples).\n :param y: array-like, shape (n_samples,). Target values (class labels\n in classification, real number in regression)\n :param sample_weight: array-like, shape (n_samples,). Per-sample\n weights. Rescale C per sample. Higher weights force the classifier to\n put more emphasis on these points.\n :return: nothing\n \"\"\"\n pass\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n _metaclass_ = ABCMeta\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n\n @abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array=np.\n empty(0)) ->None:\n \"\"\"\n Fits the SVM model according to the given training data\n\n :param x: {array-like, sparse matrix}, shape (n_samples, n_features).\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features. For kernel=\"precomputed\", the\n expected shape of X is (n_samples, n_samples).\n :param y: array-like, shape (n_samples,). Target values (class labels\n in classification, real number in regression)\n :param sample_weight: array-like, shape (n_samples,). Per-sample\n weights. Rescale C per sample. Higher weights force the classifier to\n put more emphasis on these points.\n :return: nothing\n \"\"\"\n pass\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n\n @abstractmethod\n def fit(self, x: np.ndarray, y: np.ndarray, sample_weight: np.array=np.\n empty(0)) ->None:\n \"\"\"\n Fits the SVM model according to the given training data\n\n :param x: {array-like, sparse matrix}, shape (n_samples, n_features).\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features. For kernel=\"precomputed\", the\n expected shape of X is (n_samples, n_samples).\n :param y: array-like, shape (n_samples,). Target values (class labels\n in classification, real number in regression)\n :param sample_weight: array-like, shape (n_samples,). Per-sample\n weights. Rescale C per sample. Higher weights force the classifier to\n put more emphasis on these points.\n :return: nothing\n \"\"\"\n pass\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n\n @abstractmethod\n def predict_cf(self, x, **kwargs):\n \"\"\"\n It classifies the samples on X and adds conformal measures\n\n :param x:\n :return:\n \"\"\"\n pass\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n\n def is_calibrated(self):\n \"\"\"\n Establish if a conformal predictor is calibrated (the calibration set\n is not null)\n\n :return: 'True' if the calibration set is populated, ´false´ otherwise\n \"\"\"\n return not (self._cal_a is None or self._cal_l is None)\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n <function token>\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n <function token>\n\n def check_calibrated(self):\n \"\"\"\n This method raises a NotCalibratedError if the conformal predictor is\n not calibrated\n :return:\n \"\"\"\n if not self.is_calibrated():\n raise NotCalibratedError()\n <function token>\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n\n def __init__(self, nc_measure: NCMeasure, clf) ->None:\n \"\"\"\n Initialises the conformal predictor\n\n :param nc_measure: nonconformity measure to be used\n :param clf: classifier\n \"\"\"\n self._nc_measure = nc_measure\n self._clf = clf\n self._cal_l = None\n self._cal_a = None\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n\n def compute_pvalue(self, alphas) ->float:\n resolution = 10000\n pvalues = np.array([0.0] * len(alphas))\n for i in range(0, len(alphas)):\n index = np.ix_(self._cal_l == self._clf.classes_[i])\n calibration = np.round((np.array(self._cal_a)[index] *\n resolution).astype(int))\n alpha = int(np.round(alphas[i] * resolution))\n pvalues[i] = sum(calibration >= alpha) / (len(calibration) * 1.0)\n return pvalues\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def calibrate(self, x, y) ->None:\n \"\"\"\n Method that calibrates the conformal predictor using the calibration\n set in x\n\n :param x: array-like, shape (n_samples, n_features)\n :return: nothing\n \"\"\"\n pass\n <function token>\n <function token>\n",
"<import token>\n\n\nclass ConformalPredictor:\n <docstring 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",
"<import token>\n<class token>\n"
] | false |
99,921 | 855c58fd502af172bbc95e2a111edbba4f715368 | import numpy as np
import re
import nltk
from sklearn.datasets import load_files
nltk.download('stopwords' )
import pickle
from nltk.corpus import stopwords
movie_data = load_files("data/review_polarity/txt_sentoken")
X, y = movie_data.data, movie_data.target
print(type(X))
documents = []
from nltk.stem import WordNetLemmatizer
stemmer = WordNetLemmatizer()
for sen in range(0, len(X)):
document = re.sub(r'\W', ' ', str(X[sen]))
document = re.sub(r'\s+[a-zA-Z]\s+', ' ', document)
document = re.sub(r'\^[a-zA-Z]\s+', ' ', document)
document = re.sub(r'\s+', ' ', document, flags=re.I)
document = re.sub(r'^b\s+', '', document)
document = document.lower()
document =document.split()
document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)
documents.append(document)
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(documents).toarray()
from sklearn.feature_extraction.text import TfidfTransformer
tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
with open('text_classifier', 'wb') as picklefile:
pickle.dump(classifier, picklefile)
with open('text_classifier', 'rb') as training_model:
model = pickle.load(training_model)
y_pred2 = model.predict(X_test)
print(confusion_matrix(y_test, y_pred2))
print(classification_report(y_test, y_pred2))
print(accuracy_score(y_test, y_pred2)) | [
"import numpy as np \nimport re \nimport nltk\nfrom sklearn.datasets import load_files \nnltk.download('stopwords' )\nimport pickle \nfrom nltk.corpus import stopwords \n\n\nmovie_data = load_files(\"data/review_polarity/txt_sentoken\")\nX, y = movie_data.data, movie_data.target\n\nprint(type(X))\n\ndocuments = []\n\nfrom nltk.stem import WordNetLemmatizer \n\nstemmer = WordNetLemmatizer() \n\nfor sen in range(0, len(X)):\n document = re.sub(r'\\W', ' ', str(X[sen]))\n document = re.sub(r'\\s+[a-zA-Z]\\s+', ' ', document)\n document = re.sub(r'\\^[a-zA-Z]\\s+', ' ', document)\n document = re.sub(r'\\s+', ' ', document, flags=re.I)\n document = re.sub(r'^b\\s+', '', document)\n document = document.lower()\n document =document.split()\n document = [stemmer.lemmatize(word) for word in document]\n document = ' '.join(document)\n documents.append(document)\n\nfrom sklearn.feature_extraction.text import CountVectorizer \nvectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))\nX = vectorizer.fit_transform(documents).toarray()\n\nfrom sklearn.feature_extraction.text import TfidfTransformer\ntfidfconverter = TfidfTransformer()\nX = tfidfconverter.fit_transform(X).toarray()\n\nfrom sklearn.model_selection import train_test_split \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nclassifier = RandomForestClassifier(n_estimators=1000, random_state=0)\nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict(X_test)\n\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score \nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\nprint(accuracy_score(y_test, y_pred))\n\nwith open('text_classifier', 'wb') as picklefile:\n pickle.dump(classifier, picklefile)\n\nwith open('text_classifier', 'rb') as training_model:\n model = pickle.load(training_model)\n\ny_pred2 = model.predict(X_test)\nprint(confusion_matrix(y_test, y_pred2))\nprint(classification_report(y_test, y_pred2))\nprint(accuracy_score(y_test, y_pred2))",
"import numpy as np\nimport re\nimport nltk\nfrom sklearn.datasets import load_files\nnltk.download('stopwords')\nimport pickle\nfrom nltk.corpus import stopwords\nmovie_data = load_files('data/review_polarity/txt_sentoken')\nX, y = movie_data.data, movie_data.target\nprint(type(X))\ndocuments = []\nfrom nltk.stem import WordNetLemmatizer\nstemmer = WordNetLemmatizer()\nfor sen in range(0, len(X)):\n document = re.sub('\\\\W', ' ', str(X[sen]))\n document = re.sub('\\\\s+[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\^[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\s+', ' ', document, flags=re.I)\n document = re.sub('^b\\\\s+', '', document)\n document = document.lower()\n document = document.split()\n document = [stemmer.lemmatize(word) for word in document]\n document = ' '.join(document)\n documents.append(document)\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7,\n stop_words=stopwords.words('english'))\nX = vectorizer.fit_transform(documents).toarray()\nfrom sklearn.feature_extraction.text import TfidfTransformer\ntfidfconverter = TfidfTransformer()\nX = tfidfconverter.fit_transform(X).toarray()\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators=1000, random_state=0)\nclassifier.fit(X_train, y_train)\ny_pred = classifier.predict(X_test)\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\nprint(accuracy_score(y_test, y_pred))\nwith open('text_classifier', 'wb') as picklefile:\n pickle.dump(classifier, picklefile)\nwith open('text_classifier', 'rb') as training_model:\n model = pickle.load(training_model)\ny_pred2 = model.predict(X_test)\nprint(confusion_matrix(y_test, y_pred2))\nprint(classification_report(y_test, y_pred2))\nprint(accuracy_score(y_test, y_pred2))\n",
"<import token>\nnltk.download('stopwords')\n<import token>\nmovie_data = load_files('data/review_polarity/txt_sentoken')\nX, y = movie_data.data, movie_data.target\nprint(type(X))\ndocuments = []\n<import token>\nstemmer = WordNetLemmatizer()\nfor sen in range(0, len(X)):\n document = re.sub('\\\\W', ' ', str(X[sen]))\n document = re.sub('\\\\s+[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\^[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\s+', ' ', document, flags=re.I)\n document = re.sub('^b\\\\s+', '', document)\n document = document.lower()\n document = document.split()\n document = [stemmer.lemmatize(word) for word in document]\n document = ' '.join(document)\n documents.append(document)\n<import token>\nvectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7,\n stop_words=stopwords.words('english'))\nX = vectorizer.fit_transform(documents).toarray()\n<import token>\ntfidfconverter = TfidfTransformer()\nX = tfidfconverter.fit_transform(X).toarray()\n<import token>\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n random_state=0)\n<import token>\nclassifier = RandomForestClassifier(n_estimators=1000, random_state=0)\nclassifier.fit(X_train, y_train)\ny_pred = classifier.predict(X_test)\n<import token>\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\nprint(accuracy_score(y_test, y_pred))\nwith open('text_classifier', 'wb') as picklefile:\n pickle.dump(classifier, picklefile)\nwith open('text_classifier', 'rb') as training_model:\n model = pickle.load(training_model)\ny_pred2 = model.predict(X_test)\nprint(confusion_matrix(y_test, y_pred2))\nprint(classification_report(y_test, y_pred2))\nprint(accuracy_score(y_test, y_pred2))\n",
"<import token>\nnltk.download('stopwords')\n<import token>\n<assignment token>\nprint(type(X))\n<assignment token>\n<import token>\n<assignment token>\nfor sen in range(0, len(X)):\n document = re.sub('\\\\W', ' ', str(X[sen]))\n document = re.sub('\\\\s+[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\^[a-zA-Z]\\\\s+', ' ', document)\n document = re.sub('\\\\s+', ' ', document, flags=re.I)\n document = re.sub('^b\\\\s+', '', document)\n document = document.lower()\n document = document.split()\n document = [stemmer.lemmatize(word) for word in document]\n document = ' '.join(document)\n documents.append(document)\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\nclassifier.fit(X_train, y_train)\n<assignment token>\n<import token>\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\nprint(accuracy_score(y_test, y_pred))\nwith open('text_classifier', 'wb') as picklefile:\n pickle.dump(classifier, picklefile)\nwith open('text_classifier', 'rb') as training_model:\n model = pickle.load(training_model)\n<assignment token>\nprint(confusion_matrix(y_test, y_pred2))\nprint(classification_report(y_test, y_pred2))\nprint(accuracy_score(y_test, y_pred2))\n",
"<import token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<import token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,922 | 48b91572a5d492e416042d0ea9800775a6257682 | """This is the class for the light powerup."""
import random
import pygame
import os
from .entity import Entity
DIRECTORY = os.path.abspath(os.getcwd())
POWERUP_DIR = DIRECTORY+"/players_images/powerups/flash.png"
POWERUPSIZE = 20
class Flash(Entity):
"""get the size"""
def __init__(self, name):
Entity.__init__(self,name)
self.image = pygame.image.load(POWERUP_DIR).convert_alpha()
self.rect = self.image.get_rect()
self.size = 0
self.speed = 0
self.points = 0
def add_new_figure(self, resized_w, resized_h):
"""adding new figure"""
size = POWERUPSIZE
new_figure = {'rect' : pygame.Rect(random.randint(0, resized_w - size),
random.randint(0, resized_h - size), size, size),
'surface' : pygame.transform.scale(self.get_image(),(size, size)),
}
return new_figure
def check_for_collision_with_flash(self, hero_rect, powerups):
"""checking for collisions"""
for p in powerups[:]:
if hero_rect.colliderect(p['rect']):
powerups.remove(p)
return True
return False
def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):
"""add new flashes to the list after X iterations"""
if iteration % 500 == 0:
new_speed = self.add_new_figure(resized_w, resized_h)
powerups.append(new_speed)
return powerups
def get_size(self):
"""get the size"""
return self.size
def get_speed(self):
"""get the speed"""
return self.speed
def get_points(self):
"""get the points"""
return self.points
def get_image(self):
"""get the image"""
return self.image
def get_rectangle(self):
"""get the rectangle"""
return self.rect
def __str__(self):
return f'{self.name}'
def __repr__(self):
return self.__str__
| [
"\"\"\"This is the class for the light powerup.\"\"\"\nimport random\nimport pygame\nimport os\nfrom .entity import Entity\n\n\nDIRECTORY = os.path.abspath(os.getcwd())\nPOWERUP_DIR = DIRECTORY+\"/players_images/powerups/flash.png\"\n\nPOWERUPSIZE = 20\n\nclass Flash(Entity):\n \"\"\"get the size\"\"\"\n def __init__(self, name):\n Entity.__init__(self,name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n\n new_figure = {'rect' : pygame.Rect(random.randint(0, resized_w - size),\n random.randint(0, resized_h - size), size, size),\n 'surface' : pygame.transform.scale(self.get_image(),(size, size)),\n }\n\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\nimport random\nimport pygame\nimport os\nfrom .entity import Entity\nDIRECTORY = os.path.abspath(os.getcwd())\nPOWERUP_DIR = DIRECTORY + '/players_images/powerups/flash.png'\nPOWERUPSIZE = 20\n\n\nclass Flash(Entity):\n \"\"\"get the size\"\"\"\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\nDIRECTORY = os.path.abspath(os.getcwd())\nPOWERUP_DIR = DIRECTORY + '/players_images/powerups/flash.png'\nPOWERUPSIZE = 20\n\n\nclass Flash(Entity):\n \"\"\"get the size\"\"\"\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n \"\"\"get the size\"\"\"\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n\n def check_for_collision_with_flash(self, hero_rect, powerups):\n \"\"\"checking for collisions\"\"\"\n for p in powerups[:]:\n if hero_rect.colliderect(p['rect']):\n powerups.remove(p)\n return True\n return False\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n <function token>\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n\n def get_rectangle(self):\n \"\"\"get the rectangle\"\"\"\n return self.rect\n <function token>\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n\n def __init__(self, name):\n Entity.__init__(self, name)\n self.image = pygame.image.load(POWERUP_DIR).convert_alpha()\n self.rect = self.image.get_rect()\n self.size = 0\n self.speed = 0\n self.points = 0\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n\n def add_new_flash_to_list(self, iteration, powerups, resized_w, resized_h):\n \"\"\"add new flashes to the list after X iterations\"\"\"\n if iteration % 500 == 0:\n new_speed = self.add_new_figure(resized_w, resized_h)\n powerups.append(new_speed)\n return powerups\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n\n def __repr__(self):\n return self.__str__\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n\n def get_speed(self):\n \"\"\"get the speed\"\"\"\n return self.speed\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n <function token>\n\n def get_points(self):\n \"\"\"get the points\"\"\"\n return self.points\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n\n def add_new_figure(self, resized_w, resized_h):\n \"\"\"adding new figure\"\"\"\n size = POWERUPSIZE\n new_figure = {'rect': pygame.Rect(random.randint(0, resized_w -\n size), random.randint(0, resized_h - size), size, size),\n 'surface': pygame.transform.scale(self.get_image(), (size, size))}\n return new_figure\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n <function token>\n <function token>\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\n <function token>\n <function token>\n\n def get_image(self):\n \"\"\"get the image\"\"\"\n return self.image\n <function token>\n <function token>\n <function token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\nclass Flash(Entity):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_size(self):\n \"\"\"get the size\"\"\"\n return self.size\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 Flash(Entity):\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",
"<docstring token>\n<import token>\n<assignment token>\n<class token>\n"
] | false |
99,923 | 3e9df2ef61ea6d62d1e7508de18431b8f05023e6 | #tokenizing and covertint to lower-case
import nltk.tokenize
raw = open("E:\\dataset.txt").read()
raw = raw.lower()
docs = nltk.tokenize.sent_tokenize(raw)
docs = docs[0].split('\n')
#pre-processing punctuations
from string import punctuation as punc
for d in docs:
for ch in d:
if ch in punc:
d.replace(ch, '')
#removing stopwords, stemming words
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS
from nltk.stem import PorterStemmer
ps = PorterStemmer()
for d in docs:
for token in nltk.tokenize.word_tokenize(d):
if token in ENGLISH_STOP_WORDS:
d.replace(token, '')
d.replace(token, ps.stem(token))
# asking for the test document from the user through direct input
for i in range(len(docs)):
print('D' + str(i) + ": " + docs[i])
test = input("Enter your text: ")
docs.append(test + ":")
#separating input documents from labels, stripping off the unwanted spaces
X, y = [], []
for d in docs:
X.append(d[:d.index(":")].lstrip().rstrip())
y.append(d[d.index(":")+1:].lstrip().rstrip())
#Vectorizing with Tfidf vectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
vec = vectorizer.fit_transform(X)
print(vec.toarray)
#training KNN Classifier
import sklearn
clf = sklearn.neighbors.KNeighborsClassifier(1)
clf.fit(vec[:6], y[:6])
print('Label: ', clf.predict(vec[6]))
#sentiment analysis
from nltk.corpus import wordnet
test_tokens = test.split(' ')
good = wordnet.synsets('good')
bad = wordnet.synsets('evil')
score_pos = score_neg = 0
for token in test_tokens:
t = wordnet.synsets(token)
if len(t) > 0:
sim_good = wordnet.wup_similarity(good[0], t[0])
sim_bad = wordnet.wup_similarity(bad[0], t[0])
if(sim_good is not None) :
score_pos = score_pos + sim_good
if(sim_bad is not None):
score_neg = score_neg + sim_bad
if(score_neg - score_pos > 0.1):
print('Subjective statement, Negative opinion of strength: %.2f' %score_neg)
elif(score_pos - score_neg > 0.1):
print('Subjective statement, Positive opinion of strength: %.2f' %score_pos)
else:
print('Objective statement, No opinion showed')
#nearest documents
nbrs = sklearn.neighbors.NearestNeighbors(n_neighbors=2)
nbrs.fit(vec[:6])
closest_docs = nbrs.kneighbors(vec[6])
print('Recommended readings are documents with IDs ', closest_docs[1])
print('having distances ', closest_docs[0])
| [
"#tokenizing and covertint to lower-case\nimport nltk.tokenize\nraw = open(\"E:\\\\dataset.txt\").read()\nraw = raw.lower()\ndocs = nltk.tokenize.sent_tokenize(raw)\ndocs = docs[0].split('\\n')\n\n#pre-processing punctuations\nfrom string import punctuation as punc\nfor d in docs:\n for ch in d:\n if ch in punc:\n d.replace(ch, '')\n\n#removing stopwords, stemming words \nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\nfrom nltk.stem import PorterStemmer\nps = PorterStemmer() \nfor d in docs:\n for token in nltk.tokenize.word_tokenize(d):\n if token in ENGLISH_STOP_WORDS:\n d.replace(token, '')\n d.replace(token, ps.stem(token))\n \n# asking for the test document from the user through direct input\nfor i in range(len(docs)):\n print('D' + str(i) + \": \" + docs[i])\ntest = input(\"Enter your text: \")\ndocs.append(test + \":\")\n\n#separating input documents from labels, stripping off the unwanted spaces\nX, y = [], []\nfor d in docs:\n X.append(d[:d.index(\":\")].lstrip().rstrip())\n y.append(d[d.index(\":\")+1:].lstrip().rstrip())\n\n#Vectorizing with Tfidf vectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer = TfidfVectorizer()\nvec = vectorizer.fit_transform(X)\nprint(vec.toarray)\n\n#training KNN Classifier\nimport sklearn\nclf = sklearn.neighbors.KNeighborsClassifier(1)\nclf.fit(vec[:6], y[:6])\nprint('Label: ', clf.predict(vec[6]))\n\n#sentiment analysis\nfrom nltk.corpus import wordnet\ntest_tokens = test.split(' ') \ngood = wordnet.synsets('good')\nbad = wordnet.synsets('evil')\nscore_pos = score_neg = 0\n\nfor token in test_tokens:\n t = wordnet.synsets(token)\n if len(t) > 0:\n sim_good = wordnet.wup_similarity(good[0], t[0])\n sim_bad = wordnet.wup_similarity(bad[0], t[0])\n if(sim_good is not None) :\n score_pos = score_pos + sim_good\n if(sim_bad is not None):\n score_neg = score_neg + sim_bad\n\nif(score_neg - score_pos > 0.1):\n print('Subjective statement, Negative opinion of strength: %.2f' %score_neg)\nelif(score_pos - score_neg > 0.1):\n print('Subjective statement, Positive opinion of strength: %.2f' %score_pos)\nelse:\n print('Objective statement, No opinion showed')\n \n#nearest documents \nnbrs = sklearn.neighbors.NearestNeighbors(n_neighbors=2)\nnbrs.fit(vec[:6])\nclosest_docs = nbrs.kneighbors(vec[6])\nprint('Recommended readings are documents with IDs ', closest_docs[1])\nprint('having distances ', closest_docs[0])\n",
"import nltk.tokenize\nraw = open('E:\\\\dataset.txt').read()\nraw = raw.lower()\ndocs = nltk.tokenize.sent_tokenize(raw)\ndocs = docs[0].split('\\n')\nfrom string import punctuation as punc\nfor d in docs:\n for ch in d:\n if ch in punc:\n d.replace(ch, '')\nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\nfrom nltk.stem import PorterStemmer\nps = PorterStemmer()\nfor d in docs:\n for token in nltk.tokenize.word_tokenize(d):\n if token in ENGLISH_STOP_WORDS:\n d.replace(token, '')\n d.replace(token, ps.stem(token))\nfor i in range(len(docs)):\n print('D' + str(i) + ': ' + docs[i])\ntest = input('Enter your text: ')\ndocs.append(test + ':')\nX, y = [], []\nfor d in docs:\n X.append(d[:d.index(':')].lstrip().rstrip())\n y.append(d[d.index(':') + 1:].lstrip().rstrip())\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer = TfidfVectorizer()\nvec = vectorizer.fit_transform(X)\nprint(vec.toarray)\nimport sklearn\nclf = sklearn.neighbors.KNeighborsClassifier(1)\nclf.fit(vec[:6], y[:6])\nprint('Label: ', clf.predict(vec[6]))\nfrom nltk.corpus import wordnet\ntest_tokens = test.split(' ')\ngood = wordnet.synsets('good')\nbad = wordnet.synsets('evil')\nscore_pos = score_neg = 0\nfor token in test_tokens:\n t = wordnet.synsets(token)\n if len(t) > 0:\n sim_good = wordnet.wup_similarity(good[0], t[0])\n sim_bad = wordnet.wup_similarity(bad[0], t[0])\n if sim_good is not None:\n score_pos = score_pos + sim_good\n if sim_bad is not None:\n score_neg = score_neg + sim_bad\nif score_neg - score_pos > 0.1:\n print('Subjective statement, Negative opinion of strength: %.2f' %\n score_neg)\nelif score_pos - score_neg > 0.1:\n print('Subjective statement, Positive opinion of strength: %.2f' %\n score_pos)\nelse:\n print('Objective statement, No opinion showed')\nnbrs = sklearn.neighbors.NearestNeighbors(n_neighbors=2)\nnbrs.fit(vec[:6])\nclosest_docs = nbrs.kneighbors(vec[6])\nprint('Recommended readings are documents with IDs ', closest_docs[1])\nprint('having distances ', closest_docs[0])\n",
"<import token>\nraw = open('E:\\\\dataset.txt').read()\nraw = raw.lower()\ndocs = nltk.tokenize.sent_tokenize(raw)\ndocs = docs[0].split('\\n')\n<import token>\nfor d in docs:\n for ch in d:\n if ch in punc:\n d.replace(ch, '')\n<import token>\nps = PorterStemmer()\nfor d in docs:\n for token in nltk.tokenize.word_tokenize(d):\n if token in ENGLISH_STOP_WORDS:\n d.replace(token, '')\n d.replace(token, ps.stem(token))\nfor i in range(len(docs)):\n print('D' + str(i) + ': ' + docs[i])\ntest = input('Enter your text: ')\ndocs.append(test + ':')\nX, y = [], []\nfor d in docs:\n X.append(d[:d.index(':')].lstrip().rstrip())\n y.append(d[d.index(':') + 1:].lstrip().rstrip())\n<import token>\nvectorizer = TfidfVectorizer()\nvec = vectorizer.fit_transform(X)\nprint(vec.toarray)\n<import token>\nclf = sklearn.neighbors.KNeighborsClassifier(1)\nclf.fit(vec[:6], y[:6])\nprint('Label: ', clf.predict(vec[6]))\n<import token>\ntest_tokens = test.split(' ')\ngood = wordnet.synsets('good')\nbad = wordnet.synsets('evil')\nscore_pos = score_neg = 0\nfor token in test_tokens:\n t = wordnet.synsets(token)\n if len(t) > 0:\n sim_good = wordnet.wup_similarity(good[0], t[0])\n sim_bad = wordnet.wup_similarity(bad[0], t[0])\n if sim_good is not None:\n score_pos = score_pos + sim_good\n if sim_bad is not None:\n score_neg = score_neg + sim_bad\nif score_neg - score_pos > 0.1:\n print('Subjective statement, Negative opinion of strength: %.2f' %\n score_neg)\nelif score_pos - score_neg > 0.1:\n print('Subjective statement, Positive opinion of strength: %.2f' %\n score_pos)\nelse:\n print('Objective statement, No opinion showed')\nnbrs = sklearn.neighbors.NearestNeighbors(n_neighbors=2)\nnbrs.fit(vec[:6])\nclosest_docs = nbrs.kneighbors(vec[6])\nprint('Recommended readings are documents with IDs ', closest_docs[1])\nprint('having distances ', closest_docs[0])\n",
"<import token>\n<assignment token>\n<import token>\nfor d in docs:\n for ch in d:\n if ch in punc:\n d.replace(ch, '')\n<import token>\n<assignment token>\nfor d in docs:\n for token in nltk.tokenize.word_tokenize(d):\n if token in ENGLISH_STOP_WORDS:\n d.replace(token, '')\n d.replace(token, ps.stem(token))\nfor i in range(len(docs)):\n print('D' + str(i) + ': ' + docs[i])\n<assignment token>\ndocs.append(test + ':')\n<assignment token>\nfor d in docs:\n X.append(d[:d.index(':')].lstrip().rstrip())\n y.append(d[d.index(':') + 1:].lstrip().rstrip())\n<import token>\n<assignment token>\nprint(vec.toarray)\n<import token>\n<assignment token>\nclf.fit(vec[:6], y[:6])\nprint('Label: ', clf.predict(vec[6]))\n<import token>\n<assignment token>\nfor token in test_tokens:\n t = wordnet.synsets(token)\n if len(t) > 0:\n sim_good = wordnet.wup_similarity(good[0], t[0])\n sim_bad = wordnet.wup_similarity(bad[0], t[0])\n if sim_good is not None:\n score_pos = score_pos + sim_good\n if sim_bad is not None:\n score_neg = score_neg + sim_bad\nif score_neg - score_pos > 0.1:\n print('Subjective statement, Negative opinion of strength: %.2f' %\n score_neg)\nelif score_pos - score_neg > 0.1:\n print('Subjective statement, Positive opinion of strength: %.2f' %\n score_pos)\nelse:\n print('Objective statement, No opinion showed')\n<assignment token>\nnbrs.fit(vec[:6])\n<assignment token>\nprint('Recommended readings are documents with IDs ', closest_docs[1])\nprint('having distances ', closest_docs[0])\n",
"<import token>\n<assignment token>\n<import token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\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<assignment token>\n<code token>\n"
] | false |
99,924 | ddf5d72696f6e1c5e40685902336c88167dfc065 | def solution(tickets):
tck = dict()
for t1, t2 in tickets:
if t1 in tck.keys():
tck[t1].append(t2)
else:
tck[t1] = [t2]
for k in tck.keys():
tck[k].sort()
st = ['ICN']
res = []
while st:
top = st[-1]
if top not in tck.keys() or not tck[top]:
res.append(st.pop())
else:
st.append(tck[top].pop(0))
return res[::-1]
# 1. { 시작점 : [도착점], ... } 형태의 인접 리스트 그래프 생성
# 2. ‘도착점’의 리스트 정렬
# 3. DFS 알고리즘을 사용해 모든 점 순회
# 3-1. 스택에서 가장 위 데이터(top) 가져옴
# 3-2-1. 가져온 데이터(top)가 그래프에 없거나, 티켓을 모두 사용한 경우, path에 저장
# 3-2-2. 아니라면, 가져온 데이터(top)을 시작점으로 하는 도착점 데이터 중 가장 앞 데이터(알파벳순으로 선택해야하므로)를 가져와 stack에 저장
# 4. path를 역순으로 출력
| [
"def solution(tickets): \n tck = dict()\n \n for t1, t2 in tickets:\n if t1 in tck.keys():\n tck[t1].append(t2)\n else:\n tck[t1] = [t2]\n \n for k in tck.keys():\n tck[k].sort()\n \n st = ['ICN']\n res = []\n \n while st:\n top = st[-1]\n \n if top not in tck.keys() or not tck[top]:\n res.append(st.pop())\n else:\n st.append(tck[top].pop(0))\n \n return res[::-1]\n\n\n # 1. { 시작점 : [도착점], ... } 형태의 인접 리스트 그래프 생성\n # 2. ‘도착점’의 리스트 정렬\n\n # 3. DFS 알고리즘을 사용해 모든 점 순회\n # 3-1. 스택에서 가장 위 데이터(top) 가져옴\n # 3-2-1. 가져온 데이터(top)가 그래프에 없거나, 티켓을 모두 사용한 경우, path에 저장\n # 3-2-2. 아니라면, 가져온 데이터(top)을 시작점으로 하는 도착점 데이터 중 가장 앞 데이터(알파벳순으로 선택해야하므로)를 가져와 stack에 저장\n # 4. path를 역순으로 출력\n",
"def solution(tickets):\n tck = dict()\n for t1, t2 in tickets:\n if t1 in tck.keys():\n tck[t1].append(t2)\n else:\n tck[t1] = [t2]\n for k in tck.keys():\n tck[k].sort()\n st = ['ICN']\n res = []\n while st:\n top = st[-1]\n if top not in tck.keys() or not tck[top]:\n res.append(st.pop())\n else:\n st.append(tck[top].pop(0))\n return res[::-1]\n",
"<function token>\n"
] | false |
99,925 | 3e2838efdd4efa8a6b5ac227504030fa64388877 | import keras
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout
import cv2
import numpy as np
model2 = Sequential()
model2.add(Conv2D(filters = 16,kernel_size=2,padding='same',activation='relu',input_shape=(100,100,3)))
model2.add(MaxPooling2D(pool_size=2))
model2.add(Conv2D(filters=32,kernel_size=2,padding='same',activation='relu'))
model2.add(MaxPooling2D(pool_size=2))
model2.add(Conv2D(filters=64,kernel_size=2,padding='same',activation='relu'))
model2.add(MaxPooling2D(pool_size=2))
model2.add(Conv2D(filters=128,kernel_size=2,padding='same',activation='relu'))
model2.add(MaxPooling2D(pool_size=2))
model2.add(Dropout(0.2))
model2.add(Flatten())
model2.add(Dense(1000,activation='relu'))
model2.add(Dropout(0.2))
model2.add(Dense(1200,activation='relu'))
model2.add(Dropout(0.2))
model2.add(Dense(1000,activation='relu'))
model2.add(Dropout(0.2))
model2.add(Dense(2,activation='softmax'))
# model2.summary()
#compile the model
# model2.compile(loss='mean_squared_error', optimizer='rmsprop',metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
model2.load_weights('modelDetectFruit.weights.best.hdf5')
Labels = ['Approved', 'defected']
def detection(img):
global Labels
img = np.array(cv2.resize(img,(100,100)))
img = np.reshape(img,(1,img.shape[0],img.shape[1],img.shape[2]))
label = model2.predict(img)
id = np.argmax(label)
return Labels[id]
# img = cv2.imread("Pictures/Orange/0_100.jpg")
# print(detection(img))
| [
"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout\nimport cv2\nimport numpy as np\n\nmodel2 = Sequential()\nmodel2.add(Conv2D(filters = 16,kernel_size=2,padding='same',activation='relu',input_shape=(100,100,3)))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=32,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=64,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=128,kernel_size=2,padding='same',activation='relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\n\nmodel2.add(Dropout(0.2))\nmodel2.add(Flatten())\nmodel2.add(Dense(1000,activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1200,activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1000,activation='relu'))\nmodel2.add(Dropout(0.2))\n\n\nmodel2.add(Dense(2,activation='softmax'))\n# model2.summary()\n\n#compile the model\n# model2.compile(loss='mean_squared_error', optimizer='rmsprop',metrics=['accuracy'])\nfrom keras.callbacks import ModelCheckpoint\nmodel2.load_weights('modelDetectFruit.weights.best.hdf5')\n\nLabels = ['Approved', 'defected']\ndef detection(img):\n global Labels\n img = np.array(cv2.resize(img,(100,100)))\n img = np.reshape(img,(1,img.shape[0],img.shape[1],img.shape[2]))\n label = model2.predict(img)\n id = np.argmax(label)\n return Labels[id]\n\n# img = cv2.imread(\"Pictures/Orange/0_100.jpg\")\n# print(detection(img))\n",
"import keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nimport cv2\nimport numpy as np\nmodel2 = Sequential()\nmodel2.add(Conv2D(filters=16, kernel_size=2, padding='same', activation=\n 'relu', input_shape=(100, 100, 3)))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=128, kernel_size=2, padding='same', activation=\n 'relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Dropout(0.2))\nmodel2.add(Flatten())\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1200, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(2, activation='softmax'))\nfrom keras.callbacks import ModelCheckpoint\nmodel2.load_weights('modelDetectFruit.weights.best.hdf5')\nLabels = ['Approved', 'defected']\n\n\ndef detection(img):\n global Labels\n img = np.array(cv2.resize(img, (100, 100)))\n img = np.reshape(img, (1, img.shape[0], img.shape[1], img.shape[2]))\n label = model2.predict(img)\n id = np.argmax(label)\n return Labels[id]\n",
"<import token>\nmodel2 = Sequential()\nmodel2.add(Conv2D(filters=16, kernel_size=2, padding='same', activation=\n 'relu', input_shape=(100, 100, 3)))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=128, kernel_size=2, padding='same', activation=\n 'relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Dropout(0.2))\nmodel2.add(Flatten())\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1200, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(2, activation='softmax'))\n<import token>\nmodel2.load_weights('modelDetectFruit.weights.best.hdf5')\nLabels = ['Approved', 'defected']\n\n\ndef detection(img):\n global Labels\n img = np.array(cv2.resize(img, (100, 100)))\n img = np.reshape(img, (1, img.shape[0], img.shape[1], img.shape[2]))\n label = model2.predict(img)\n id = np.argmax(label)\n return Labels[id]\n",
"<import token>\n<assignment token>\nmodel2.add(Conv2D(filters=16, kernel_size=2, padding='same', activation=\n 'relu', input_shape=(100, 100, 3)))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu')\n )\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Conv2D(filters=128, kernel_size=2, padding='same', activation=\n 'relu'))\nmodel2.add(MaxPooling2D(pool_size=2))\nmodel2.add(Dropout(0.2))\nmodel2.add(Flatten())\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1200, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(1000, activation='relu'))\nmodel2.add(Dropout(0.2))\nmodel2.add(Dense(2, activation='softmax'))\n<import token>\nmodel2.load_weights('modelDetectFruit.weights.best.hdf5')\n<assignment token>\n\n\ndef detection(img):\n global Labels\n img = np.array(cv2.resize(img, (100, 100)))\n img = np.reshape(img, (1, img.shape[0], img.shape[1], img.shape[2]))\n label = model2.predict(img)\n id = np.argmax(label)\n return Labels[id]\n",
"<import token>\n<assignment token>\n<code token>\n<import token>\n<code token>\n<assignment token>\n\n\ndef detection(img):\n global Labels\n img = np.array(cv2.resize(img, (100, 100)))\n img = np.reshape(img, (1, img.shape[0], img.shape[1], img.shape[2]))\n label = model2.predict(img)\n id = np.argmax(label)\n return Labels[id]\n",
"<import token>\n<assignment token>\n<code token>\n<import token>\n<code token>\n<assignment token>\n<function token>\n"
] | false |
99,926 | f7407cf768d072a19b7086a40f29a633c5a6fe6c | import sqlite3
#function for creating table to store user
def make_user():
conn = sqlite3.connect("app.db")
cur = conn.cursor()
sql = 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'
cur.execute(sql)
conn.commit()
#function to insert values into user table
def insert(tablename : str, values: tuple):
conn = sqlite3.connect("app.db")
cur = conn.cursor()
sql = f'INSERT INTO {tablename} VALUES{values}'
cur.execute(sql)
conn.commit()
#function checks if email and password match
def checkpassword(password : str, email : str):
conn = sqlite3.connect("app.db")
cur = conn.cursor()
sql = f"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'"
cur.execute(sql)
results = cur.fetchall()
if len(results) >0 :
return True
return False
#function to get user's email
def getemail():
conn = sqlite3.connect("app.db")
cur = conn.cursor()
sql = 'SELECT Email FROM user'
cur.execute(sql)
emails = cur.fetchall()
return emails
#function to get name from user table
def getname(email: tuple):
email = email[0]
conn = sqlite3.connect("app.db")
cur = conn.cursor()
sql = f"SELECT Name FROM user WHERE Email='{email}'"
cur.execute(sql)
result = cur.fetchall()
return result[0][0]
if __name__ == '__main__':
pass
# insert("user", values=("at8029@srmist.edu.in", "Aradhya", "SOMEONE"))
# print(checkpassword("SOMEONE", "at8029@srmist.edu.in"))
| [
"import sqlite3\n\n#function for creating table to store user\ndef make_user():\n conn = sqlite3.connect(\"app.db\")\n cur = conn.cursor()\n\n sql = 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'\n cur.execute(sql)\n conn.commit()\n\n#function to insert values into user table \ndef insert(tablename : str, values: tuple):\n conn = sqlite3.connect(\"app.db\")\n cur = conn.cursor()\n\n sql = f'INSERT INTO {tablename} VALUES{values}' \n cur.execute(sql)\n conn.commit()\n\n#function checks if email and password match\ndef checkpassword(password : str, email : str):\n \n conn = sqlite3.connect(\"app.db\")\n cur = conn.cursor()\n\n\n sql = f\"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'\"\n cur.execute(sql)\n results = cur.fetchall()\n if len(results) >0 :\n return True\n\n return False\n#function to get user's email \ndef getemail():\n \n conn = sqlite3.connect(\"app.db\")\n cur = conn.cursor()\n\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n \n return emails\n#function to get name from user table\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect(\"app.db\")\n\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n\nif __name__ == '__main__':\n pass\n # insert(\"user\", values=(\"at8029@srmist.edu.in\", \"Aradhya\", \"SOMEONE\"))\n # print(checkpassword(\"SOMEONE\", \"at8029@srmist.edu.in\"))\n",
"import sqlite3\n\n\ndef make_user():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = (\n 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'\n )\n cur.execute(sql)\n conn.commit()\n\n\ndef insert(tablename: str, values: tuple):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f'INSERT INTO {tablename} VALUES{values}'\n cur.execute(sql)\n conn.commit()\n\n\ndef checkpassword(password: str, email: str):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'\"\n cur.execute(sql)\n results = cur.fetchall()\n if len(results) > 0:\n return True\n return False\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\nif __name__ == '__main__':\n pass\n",
"<import token>\n\n\ndef make_user():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = (\n 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'\n )\n cur.execute(sql)\n conn.commit()\n\n\ndef insert(tablename: str, values: tuple):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f'INSERT INTO {tablename} VALUES{values}'\n cur.execute(sql)\n conn.commit()\n\n\ndef checkpassword(password: str, email: str):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'\"\n cur.execute(sql)\n results = cur.fetchall()\n if len(results) > 0:\n return True\n return False\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\nif __name__ == '__main__':\n pass\n",
"<import token>\n\n\ndef make_user():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = (\n 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'\n )\n cur.execute(sql)\n conn.commit()\n\n\ndef insert(tablename: str, values: tuple):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f'INSERT INTO {tablename} VALUES{values}'\n cur.execute(sql)\n conn.commit()\n\n\ndef checkpassword(password: str, email: str):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'\"\n cur.execute(sql)\n results = cur.fetchall()\n if len(results) > 0:\n return True\n return False\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\ndef insert(tablename: str, values: tuple):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f'INSERT INTO {tablename} VALUES{values}'\n cur.execute(sql)\n conn.commit()\n\n\ndef checkpassword(password: str, email: str):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT * FROM user WHERE Password='{password}' AND Email='{email}'\"\n cur.execute(sql)\n results = cur.fetchall()\n if len(results) > 0:\n return True\n return False\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\ndef insert(tablename: str, values: tuple):\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f'INSERT INTO {tablename} VALUES{values}'\n cur.execute(sql)\n conn.commit()\n\n\n<function token>\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef getemail():\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = 'SELECT Email FROM user'\n cur.execute(sql)\n emails = cur.fetchall()\n return emails\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef getname(email: tuple):\n email = email[0]\n conn = sqlite3.connect('app.db')\n cur = conn.cursor()\n sql = f\"SELECT Name FROM user WHERE Email='{email}'\"\n cur.execute(sql)\n result = cur.fetchall()\n return result[0][0]\n\n\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,927 | 28f11c9882baa46236557fa8d18e38805c3a9546 |
def part_1():
bag_rules = {}
direct_bags = set([])
for line in open("input.txt"):
# Using :-1 instead of rstrip as it is faster
line = line[:-1]
splitln = line.split(' bags contain ')
bag_type = splitln[0]
rules = {}
for bag_rule in splitln[1].split(', '):
quantity = bag_rule[0]
split_bag_rule = bag_rule.split(' ')
if split_bag_rule[0] != "no":
rule_name = split_bag_rule[1] + " " + split_bag_rule[2]
if rule_name == "shiny gold":
direct_bags.add(bag_type)
rules[rule_name] = quantity
bag_rules[bag_type] = rules
# Now perform a search
while True:
current_direct_set = len(direct_bags)
for search_bag in bag_rules:
for bag_rule in bag_rules[search_bag]:
if bag_rule in direct_bags:
direct_bags.add(search_bag)
if current_direct_set == len(direct_bags):
return len(direct_bags)
print(direct_bags)
def part_2():
bag_rules = {}
finalizers = []
for line in open("input.txt"):
# Using :-1 instead of rstrip as it is faster
line = line[:-1]
splitln = line.split(' bags contain ')
bag_type = splitln[0]
rules = {}
# Seprate the bag conditions out into a list
for bag_rule in splitln[1].split(', '):
quantity = bag_rule[0]
split_bag_rule = bag_rule.split(' ')
if bag_rule == "no other bags.":
finalizers.append(bag_type)
else:
rule_name = split_bag_rule[1] + " " + split_bag_rule[2]
rules[rule_name] = int(quantity)
if rules != {}:
bag_rules[bag_type] = rules
# No, I don't know why I need to subtract 1.
return (recurse(finalizers, bag_rules, "shiny gold") - 1)
def recurse(finalizers, bag_rules, search_bag, prepared_totals={}):
# If the bag cannot recurse any further, just return
if search_bag in finalizers:
# Return None if a finalizer is met
return None
# If not, commit an atrocity
else:
# Create a running total to add to
total = 1
# Iterate over the bag rules for each bag
for next_bag in bag_rules[search_bag]:
# Set the multiplier
next_bag_total = bag_rules[search_bag][next_bag]
# Recurse into the bag rules
if next_bag in prepared_totals:
recurse_answer = prepared_totals[next_bag]
else:
recurse_answer = recurse(finalizers, bag_rules, next_bag, prepared_totals)
prepared_totals[next_bag] = recurse_answer
# So that we don't multiply by None
if recurse_answer is None:
total += next_bag_total
else:
total += next_bag_total * recurse_answer
return total
# timecheck code lovingly submitted by Vess
"""
'####:'########::'######:::::'###::::'########:::'#######:::'######:::'######::'##::::'##:'##::::'##:
. ##::... ##..::'##... ##:::'## ##::: ##.... ##:'##.... ##:'##... ##:'##... ##: ##:::: ##: ###::'###:
: ##::::: ##:::: ##:::..:::'##:. ##:: ##:::: ##: ##:::: ##: ##:::..:: ##:::..:: ##:::: ##: ####'####:
: ##::::: ##::::. ######::'##:::. ##: ########:: ##:::: ##:. ######::. ######:: ##:::: ##: ## ### ##:
: ##::::: ##:::::..... ##: #########: ##.....::: ##:::: ##::..... ##::..... ##: ##:::: ##: ##. #: ##:
: ##::::: ##::::'##::: ##: ##.... ##: ##:::::::: ##:::: ##:'##::: ##:'##::: ##: ##:::: ##: ##:.:: ##:
'####:::: ##::::. ######:: ##:::: ##: ##::::::::. #######::. ######::. ######::. #######:: ##:::: ##:
....:::::..::::::......:::..:::::..::..::::::::::.......::::......::::......::::.......:::..:::::..::
"""
def timecheck():
import time
time_total = 0
test_count = 100
for temp_step in range(test_count):
time_before = time.time()
part_2()
time_total += time.time() - time_before
print(test_count, "trials took", time_total / test_count)
#
if __name__ == '__main__':
#part_1()
part_2()
| [
"\n\ndef part_1():\n bag_rules = {}\n direct_bags = set([])\n for line in open(\"input.txt\"):\n # Using :-1 instead of rstrip as it is faster\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if split_bag_rule[0] != \"no\":\n rule_name = split_bag_rule[1] + \" \" + split_bag_rule[2]\n if rule_name == \"shiny gold\":\n direct_bags.add(bag_type)\n rules[rule_name] = quantity\n bag_rules[bag_type] = rules\n # Now perform a search\n while True:\n current_direct_set = len(direct_bags)\n for search_bag in bag_rules:\n for bag_rule in bag_rules[search_bag]:\n if bag_rule in direct_bags:\n direct_bags.add(search_bag)\n if current_direct_set == len(direct_bags):\n return len(direct_bags)\n print(direct_bags)\n\n\ndef part_2():\n bag_rules = {}\n finalizers = []\n for line in open(\"input.txt\"):\n # Using :-1 instead of rstrip as it is faster\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n # Seprate the bag conditions out into a list\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if bag_rule == \"no other bags.\":\n finalizers.append(bag_type)\n else:\n rule_name = split_bag_rule[1] + \" \" + split_bag_rule[2]\n rules[rule_name] = int(quantity)\n if rules != {}:\n bag_rules[bag_type] = rules\n\n # No, I don't know why I need to subtract 1.\n return (recurse(finalizers, bag_rules, \"shiny gold\") - 1)\n\n\ndef recurse(finalizers, bag_rules, search_bag, prepared_totals={}):\n # If the bag cannot recurse any further, just return\n if search_bag in finalizers:\n # Return None if a finalizer is met\n return None\n # If not, commit an atrocity\n else:\n # Create a running total to add to\n total = 1\n # Iterate over the bag rules for each bag\n for next_bag in bag_rules[search_bag]:\n # Set the multiplier\n next_bag_total = bag_rules[search_bag][next_bag]\n # Recurse into the bag rules\n if next_bag in prepared_totals:\n recurse_answer = prepared_totals[next_bag]\n else:\n recurse_answer = recurse(finalizers, bag_rules, next_bag, prepared_totals)\n prepared_totals[next_bag] = recurse_answer\n # So that we don't multiply by None\n if recurse_answer is None:\n total += next_bag_total\n else:\n total += next_bag_total * recurse_answer\n\n return total\n\n# timecheck code lovingly submitted by Vess\n\"\"\"\n'####:'########::'######:::::'###::::'########:::'#######:::'######:::'######::'##::::'##:'##::::'##:\n. ##::... ##..::'##... ##:::'## ##::: ##.... ##:'##.... ##:'##... ##:'##... ##: ##:::: ##: ###::'###:\n: ##::::: ##:::: ##:::..:::'##:. ##:: ##:::: ##: ##:::: ##: ##:::..:: ##:::..:: ##:::: ##: ####'####:\n: ##::::: ##::::. ######::'##:::. ##: ########:: ##:::: ##:. ######::. ######:: ##:::: ##: ## ### ##:\n: ##::::: ##:::::..... ##: #########: ##.....::: ##:::: ##::..... ##::..... ##: ##:::: ##: ##. #: ##:\n: ##::::: ##::::'##::: ##: ##.... ##: ##:::::::: ##:::: ##:'##::: ##:'##::: ##: ##:::: ##: ##:.:: ##:\n'####:::: ##::::. ######:: ##:::: ##: ##::::::::. #######::. ######::. ######::. #######:: ##:::: ##:\n....:::::..::::::......:::..:::::..::..::::::::::.......::::......::::......::::.......:::..:::::..::\n\"\"\"\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, \"trials took\", time_total / test_count)\n#\n\n\nif __name__ == '__main__':\n #part_1()\n part_2()\n",
"def part_1():\n bag_rules = {}\n direct_bags = set([])\n for line in open('input.txt'):\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if split_bag_rule[0] != 'no':\n rule_name = split_bag_rule[1] + ' ' + split_bag_rule[2]\n if rule_name == 'shiny gold':\n direct_bags.add(bag_type)\n rules[rule_name] = quantity\n bag_rules[bag_type] = rules\n while True:\n current_direct_set = len(direct_bags)\n for search_bag in bag_rules:\n for bag_rule in bag_rules[search_bag]:\n if bag_rule in direct_bags:\n direct_bags.add(search_bag)\n if current_direct_set == len(direct_bags):\n return len(direct_bags)\n print(direct_bags)\n\n\ndef part_2():\n bag_rules = {}\n finalizers = []\n for line in open('input.txt'):\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if bag_rule == 'no other bags.':\n finalizers.append(bag_type)\n else:\n rule_name = split_bag_rule[1] + ' ' + split_bag_rule[2]\n rules[rule_name] = int(quantity)\n if rules != {}:\n bag_rules[bag_type] = rules\n return recurse(finalizers, bag_rules, 'shiny gold') - 1\n\n\ndef recurse(finalizers, bag_rules, search_bag, prepared_totals={}):\n if search_bag in finalizers:\n return None\n else:\n total = 1\n for next_bag in bag_rules[search_bag]:\n next_bag_total = bag_rules[search_bag][next_bag]\n if next_bag in prepared_totals:\n recurse_answer = prepared_totals[next_bag]\n else:\n recurse_answer = recurse(finalizers, bag_rules, next_bag,\n prepared_totals)\n prepared_totals[next_bag] = recurse_answer\n if recurse_answer is None:\n total += next_bag_total\n else:\n total += next_bag_total * recurse_answer\n return total\n\n\n<docstring token>\n\n\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, 'trials took', time_total / test_count)\n\n\nif __name__ == '__main__':\n part_2()\n",
"def part_1():\n bag_rules = {}\n direct_bags = set([])\n for line in open('input.txt'):\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if split_bag_rule[0] != 'no':\n rule_name = split_bag_rule[1] + ' ' + split_bag_rule[2]\n if rule_name == 'shiny gold':\n direct_bags.add(bag_type)\n rules[rule_name] = quantity\n bag_rules[bag_type] = rules\n while True:\n current_direct_set = len(direct_bags)\n for search_bag in bag_rules:\n for bag_rule in bag_rules[search_bag]:\n if bag_rule in direct_bags:\n direct_bags.add(search_bag)\n if current_direct_set == len(direct_bags):\n return len(direct_bags)\n print(direct_bags)\n\n\ndef part_2():\n bag_rules = {}\n finalizers = []\n for line in open('input.txt'):\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if bag_rule == 'no other bags.':\n finalizers.append(bag_type)\n else:\n rule_name = split_bag_rule[1] + ' ' + split_bag_rule[2]\n rules[rule_name] = int(quantity)\n if rules != {}:\n bag_rules[bag_type] = rules\n return recurse(finalizers, bag_rules, 'shiny gold') - 1\n\n\ndef recurse(finalizers, bag_rules, search_bag, prepared_totals={}):\n if search_bag in finalizers:\n return None\n else:\n total = 1\n for next_bag in bag_rules[search_bag]:\n next_bag_total = bag_rules[search_bag][next_bag]\n if next_bag in prepared_totals:\n recurse_answer = prepared_totals[next_bag]\n else:\n recurse_answer = recurse(finalizers, bag_rules, next_bag,\n prepared_totals)\n prepared_totals[next_bag] = recurse_answer\n if recurse_answer is None:\n total += next_bag_total\n else:\n total += next_bag_total * recurse_answer\n return total\n\n\n<docstring token>\n\n\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, 'trials took', time_total / test_count)\n\n\n<code token>\n",
"def part_1():\n bag_rules = {}\n direct_bags = set([])\n for line in open('input.txt'):\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln[1].split(', '):\n quantity = bag_rule[0]\n split_bag_rule = bag_rule.split(' ')\n if split_bag_rule[0] != 'no':\n rule_name = split_bag_rule[1] + ' ' + split_bag_rule[2]\n if rule_name == 'shiny gold':\n direct_bags.add(bag_type)\n rules[rule_name] = quantity\n bag_rules[bag_type] = rules\n while True:\n current_direct_set = len(direct_bags)\n for search_bag in bag_rules:\n for bag_rule in bag_rules[search_bag]:\n if bag_rule in direct_bags:\n direct_bags.add(search_bag)\n if current_direct_set == len(direct_bags):\n return len(direct_bags)\n print(direct_bags)\n\n\n<function token>\n\n\ndef recurse(finalizers, bag_rules, search_bag, prepared_totals={}):\n if search_bag in finalizers:\n return None\n else:\n total = 1\n for next_bag in bag_rules[search_bag]:\n next_bag_total = bag_rules[search_bag][next_bag]\n if next_bag in prepared_totals:\n recurse_answer = prepared_totals[next_bag]\n else:\n recurse_answer = recurse(finalizers, bag_rules, next_bag,\n prepared_totals)\n prepared_totals[next_bag] = recurse_answer\n if recurse_answer is None:\n total += next_bag_total\n else:\n total += next_bag_total * recurse_answer\n return total\n\n\n<docstring token>\n\n\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, 'trials took', time_total / test_count)\n\n\n<code token>\n",
"<function token>\n<function token>\n\n\ndef recurse(finalizers, bag_rules, search_bag, prepared_totals={}):\n if search_bag in finalizers:\n return None\n else:\n total = 1\n for next_bag in bag_rules[search_bag]:\n next_bag_total = bag_rules[search_bag][next_bag]\n if next_bag in prepared_totals:\n recurse_answer = prepared_totals[next_bag]\n else:\n recurse_answer = recurse(finalizers, bag_rules, next_bag,\n prepared_totals)\n prepared_totals[next_bag] = recurse_answer\n if recurse_answer is None:\n total += next_bag_total\n else:\n total += next_bag_total * recurse_answer\n return total\n\n\n<docstring token>\n\n\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, 'trials took', time_total / test_count)\n\n\n<code token>\n",
"<function token>\n<function token>\n<function token>\n<docstring token>\n\n\ndef timecheck():\n import time\n time_total = 0\n test_count = 100\n for temp_step in range(test_count):\n time_before = time.time()\n part_2()\n time_total += time.time() - time_before\n print(test_count, 'trials took', time_total / test_count)\n\n\n<code token>\n",
"<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<code token>\n"
] | false |
99,928 | 40f53e254466550f08cf627a46b5c247fabe1901 | # using `value_counts`
result = df['Position'].value_counts()
display(Markdown("Using `value_counts`:"))
display(result)
# using `groupby`
result = df.groupby(['Position'])['Position'].count()
display(Markdown("Using `groupby`:"))
display(result)
# using `pivot_table`
# NOTE: This is not the correct way to get the result
# We practice this to see the difference between value_counts/groupby/pivot_table ONLY
result = df.pivot_table(index='Position', aggfunc='count').iloc[:, 0]
display(Markdown("Using `pivot_table`:"))
display(result) | [
"# using `value_counts`\nresult = df['Position'].value_counts()\ndisplay(Markdown(\"Using `value_counts`:\"))\ndisplay(result)\n\n# using `groupby`\nresult = df.groupby(['Position'])['Position'].count()\ndisplay(Markdown(\"Using `groupby`:\"))\ndisplay(result)\n\n# using `pivot_table`\n# NOTE: This is not the correct way to get the result\n# We practice this to see the difference between value_counts/groupby/pivot_table ONLY\nresult = df.pivot_table(index='Position', aggfunc='count').iloc[:, 0]\ndisplay(Markdown(\"Using `pivot_table`:\"))\ndisplay(result)",
"result = df['Position'].value_counts()\ndisplay(Markdown('Using `value_counts`:'))\ndisplay(result)\nresult = df.groupby(['Position'])['Position'].count()\ndisplay(Markdown('Using `groupby`:'))\ndisplay(result)\nresult = df.pivot_table(index='Position', aggfunc='count').iloc[:, 0]\ndisplay(Markdown('Using `pivot_table`:'))\ndisplay(result)\n",
"<assignment token>\ndisplay(Markdown('Using `value_counts`:'))\ndisplay(result)\n<assignment token>\ndisplay(Markdown('Using `groupby`:'))\ndisplay(result)\n<assignment token>\ndisplay(Markdown('Using `pivot_table`:'))\ndisplay(result)\n",
"<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,929 | 9e087bb6d6705bb8ed469ffaa6434279fb0e6f59 | # 오답
import sys
sys.stdin=open('input.txt','r')
# 수정 본 실행시간 반으로 줄어듬
for t in range(1,int(input())+1):
n, k = map(int,input().split());cnt=0
L=[*map(int,input().split())];q=[(0,-1)]
while q:
a,b=q.pop()
for id,v in enumerate(L):
if id>b:
a+=v
if a>k:
a-=v
if a<k:q.append((a,id))
elif a<k:q.append((a,id))
elif a==k:cnt+=1;print(a,id)
a-=v
print("#%i"%t, cnt)
| [
"# 오답\nimport sys\nsys.stdin=open('input.txt','r')\n\n# 수정 본 실행시간 반으로 줄어듬\nfor t in range(1,int(input())+1):\n n, k = map(int,input().split());cnt=0\n L=[*map(int,input().split())];q=[(0,-1)]\n while q:\n a,b=q.pop()\n for id,v in enumerate(L):\n if id>b:\n a+=v\n if a>k:\n a-=v\n if a<k:q.append((a,id))\n elif a<k:q.append((a,id))\n elif a==k:cnt+=1;print(a,id)\n a-=v\n print(\"#%i\"%t, cnt)\n",
"import sys\nsys.stdin = open('input.txt', 'r')\nfor t in range(1, int(input()) + 1):\n n, k = map(int, input().split())\n cnt = 0\n L = [*map(int, input().split())]\n q = [(0, -1)]\n while q:\n a, b = q.pop()\n for id, v in enumerate(L):\n if id > b:\n a += v\n if a > k:\n a -= v\n if a < k:\n q.append((a, id))\n elif a < k:\n q.append((a, id))\n elif a == k:\n cnt += 1\n print(a, id)\n a -= v\n print('#%i' % t, cnt)\n",
"<import token>\nsys.stdin = open('input.txt', 'r')\nfor t in range(1, int(input()) + 1):\n n, k = map(int, input().split())\n cnt = 0\n L = [*map(int, input().split())]\n q = [(0, -1)]\n while q:\n a, b = q.pop()\n for id, v in enumerate(L):\n if id > b:\n a += v\n if a > k:\n a -= v\n if a < k:\n q.append((a, id))\n elif a < k:\n q.append((a, id))\n elif a == k:\n cnt += 1\n print(a, id)\n a -= v\n print('#%i' % t, cnt)\n",
"<import token>\n<assignment token>\nfor t in range(1, int(input()) + 1):\n n, k = map(int, input().split())\n cnt = 0\n L = [*map(int, input().split())]\n q = [(0, -1)]\n while q:\n a, b = q.pop()\n for id, v in enumerate(L):\n if id > b:\n a += v\n if a > k:\n a -= v\n if a < k:\n q.append((a, id))\n elif a < k:\n q.append((a, id))\n elif a == k:\n cnt += 1\n print(a, id)\n a -= v\n print('#%i' % t, cnt)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,930 | 72926b4c8bff521c7247bccdb71ed130917b250e | #!/usr/bin/env python
# coding:utf-8
"""
@Version: V1.0
@Author: willson
@License: Apache Licence
@Contact: willson.wu@goertek.com
@Site: goertek.com
@Software: PyCharm
@File: __init__.py.py
@Time: 19-1-26 上午9:48
"""
from flask_security.utils import encrypt_password
from myApp import app, store_datastore
from myApp.models import *
def insertCarousel():
"插入轮播图数据"
print("开始插入轮播图数据...")
DataPath = os.path.join(app.root_path, "static/data/carouselList.json")
with open(DataPath, encoding="utf-8") as f:
DataDict = json.load(f)
for one in DataDict["data"]["carouselList"]:
store = Carousel(id=one["carouselId"],
name=one["carouselName"],
imagePath=one["carouselImgUrl"],
publicMsg=one["publicMsg"],
)
db.session.add(store)
db.session.commit()
print("o98k!")
def insertActives():
"""
优惠券类型
* 1.满减
* 2.新店优惠
* 3.折扣商品
* 4.满返代金券
* 5.新用户
* 6.减配送费
* 7.领代金券
* 8.赠送商品
"""
print("开始插入优惠卷类型数据...")
DataDict = {
1: "满减",
2: "新店优惠",
3: "折扣商品",
4: "满返代金券",
5: "新用户",
6: "减配送费",
7: "领代金券",
8: "赠送商品",
}
for key, val in DataDict.items():
actives = Actives(id=key, text=val)
db.session.add(actives)
db.session.commit()
print("o98k!")
def insertSrore():
"插入商家数据"
print("开始插入商家数据...")
# 创建角色表
user_role = Role(name="user", description="普通商家用户")
super_user_role = Role(name="superuser", description="超级管理员")
db.session.add(user_role)
db.session.add(super_user_role)
db.session.commit()
# 超级管理员用户
root_user = store_datastore.create_user(
id=1,
storeName="超级管理员",
publicMsg="💣这是超级管理员字段勿动💣",
email="root",
password=encrypt_password("root"),
roles=[user_role, super_user_role]
)
db.session.add(root_user)
db.session.commit()
DataPath = os.path.join(app.root_path, "static/data/storeList.json")
with open(DataPath, encoding="utf-8") as f:
DataDict = json.load(f)
for one in DataDict["data"]["storeList"]:
store = store_datastore.create_user(
id=one["storeId"],
storeName=one["storeName"],
imagePath=one["storeImgUrl"],
publicMsg=one["publicMsg"],
email="store{}".format(one["storeId"]),
password=encrypt_password("store{}".format(one["storeId"])),
roles=[user_role, ]
)
db.session.add(store)
for coupon_one in one["actives"]:
coupon = Coupon(coupon_name="测试卷",
coupon_num=100,
coupon_content=coupon_one["acticeText"],
store_id=one["storeId"],
actives_id=coupon_one["activeId"],
)
db.session.add(coupon)
db.session.commit()
print("o98k!")
def insertSroreFoodList():
"插入商家菜品数据"
print("开始插入商家菜品数据...")
DataPath = os.path.join(app.root_path, "static/data/storeFoodList.json")
with open(DataPath, encoding="utf-8") as f:
DataDict = json.load(f)
stores = Store.query.filter_by().all()
for store in stores:
if store.id != 1:
for one in DataDict["data"]["storeFood"]:
# 插入类别数据
category_id = int(one["titleId"][5:])
category = Category.query.filter_by(id=category_id).first()
if category is None:
category_name = one["title"]
category = Category(id=category_id, category_name=category_name)
db.session.add(category)
db.session.commit()
for item in one["items"]:
dish = Dish(dish_name=item["name"],
dish_price=item["price"],
dish_description="这是菜",
imagePath=item["foodImgUrl"],
store_id=store.id,
category_id=category_id,
)
db.session.add(dish)
db.session.commit()
print("o98k!")
def Insert():
"插入测试数据"
insertCarousel()
insertActives()
insertSrore()
insertSroreFoodList()
if __name__ == '__main__':
# insertCategories()
insertSroreFoodList()
pass
| [
"#!/usr/bin/env python\n# coding:utf-8\n\"\"\"\n@Version: V1.0\n@Author: willson\n@License: Apache Licence\n@Contact: willson.wu@goertek.com\n@Site: goertek.com\n@Software: PyCharm\n@File: __init__.py.py\n@Time: 19-1-26 上午9:48\n\"\"\"\n\nfrom flask_security.utils import encrypt_password\n\nfrom myApp import app, store_datastore\nfrom myApp.models import *\n\n\ndef insertCarousel():\n \"插入轮播图数据\"\n print(\"开始插入轮播图数据...\")\n DataPath = os.path.join(app.root_path, \"static/data/carouselList.json\")\n with open(DataPath, encoding=\"utf-8\") as f:\n DataDict = json.load(f)\n for one in DataDict[\"data\"][\"carouselList\"]:\n store = Carousel(id=one[\"carouselId\"],\n name=one[\"carouselName\"],\n imagePath=one[\"carouselImgUrl\"],\n publicMsg=one[\"publicMsg\"],\n )\n db.session.add(store)\n db.session.commit()\n print(\"o98k!\")\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print(\"开始插入优惠卷类型数据...\")\n DataDict = {\n 1: \"满减\",\n 2: \"新店优惠\",\n 3: \"折扣商品\",\n 4: \"满返代金券\",\n 5: \"新用户\",\n 6: \"减配送费\",\n 7: \"领代金券\",\n 8: \"赠送商品\",\n }\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print(\"o98k!\")\n\n\ndef insertSrore():\n \"插入商家数据\"\n print(\"开始插入商家数据...\")\n # 创建角色表\n user_role = Role(name=\"user\", description=\"普通商家用户\")\n super_user_role = Role(name=\"superuser\", description=\"超级管理员\")\n db.session.add(user_role)\n db.session.add(super_user_role)\n db.session.commit()\n\n # 超级管理员用户\n root_user = store_datastore.create_user(\n id=1,\n storeName=\"超级管理员\",\n publicMsg=\"💣这是超级管理员字段勿动💣\",\n email=\"root\",\n password=encrypt_password(\"root\"),\n roles=[user_role, super_user_role]\n )\n db.session.add(root_user)\n db.session.commit()\n\n DataPath = os.path.join(app.root_path, \"static/data/storeList.json\")\n with open(DataPath, encoding=\"utf-8\") as f:\n DataDict = json.load(f)\n for one in DataDict[\"data\"][\"storeList\"]:\n store = store_datastore.create_user(\n id=one[\"storeId\"],\n storeName=one[\"storeName\"],\n imagePath=one[\"storeImgUrl\"],\n publicMsg=one[\"publicMsg\"],\n email=\"store{}\".format(one[\"storeId\"]),\n password=encrypt_password(\"store{}\".format(one[\"storeId\"])),\n roles=[user_role, ]\n )\n db.session.add(store)\n for coupon_one in one[\"actives\"]:\n coupon = Coupon(coupon_name=\"测试卷\",\n coupon_num=100,\n coupon_content=coupon_one[\"acticeText\"],\n store_id=one[\"storeId\"],\n actives_id=coupon_one[\"activeId\"],\n )\n db.session.add(coupon)\n db.session.commit()\n print(\"o98k!\")\n\n\ndef insertSroreFoodList():\n \"插入商家菜品数据\"\n print(\"开始插入商家菜品数据...\")\n DataPath = os.path.join(app.root_path, \"static/data/storeFoodList.json\")\n with open(DataPath, encoding=\"utf-8\") as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict[\"data\"][\"storeFood\"]:\n # 插入类别数据\n category_id = int(one[\"titleId\"][5:])\n\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one[\"title\"]\n category = Category(id=category_id, category_name=category_name)\n db.session.add(category)\n db.session.commit()\n\n for item in one[\"items\"]:\n dish = Dish(dish_name=item[\"name\"],\n dish_price=item[\"price\"],\n dish_description=\"这是菜\",\n imagePath=item[\"foodImgUrl\"],\n store_id=store.id,\n category_id=category_id,\n )\n db.session.add(dish)\n db.session.commit()\n print(\"o98k!\")\n\n\ndef Insert():\n \"插入测试数据\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\nif __name__ == '__main__':\n # insertCategories()\n insertSroreFoodList()\n pass\n",
"<docstring token>\nfrom flask_security.utils import encrypt_password\nfrom myApp import app, store_datastore\nfrom myApp.models import *\n\n\ndef insertCarousel():\n \"\"\"插入轮播图数据\"\"\"\n print('开始插入轮播图数据...')\n DataPath = os.path.join(app.root_path, 'static/data/carouselList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['carouselList']:\n store = Carousel(id=one['carouselId'], name=one['carouselName'],\n imagePath=one['carouselImgUrl'], publicMsg=one['publicMsg'])\n db.session.add(store)\n db.session.commit()\n print('o98k!')\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print('开始插入优惠卷类型数据...')\n DataDict = {(1): '满减', (2): '新店优惠', (3): '折扣商品', (4): '满返代金券', (5):\n '新用户', (6): '减配送费', (7): '领代金券', (8): '赠送商品'}\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSrore():\n \"\"\"插入商家数据\"\"\"\n print('开始插入商家数据...')\n user_role = Role(name='user', description='普通商家用户')\n super_user_role = Role(name='superuser', description='超级管理员')\n db.session.add(user_role)\n db.session.add(super_user_role)\n db.session.commit()\n root_user = store_datastore.create_user(id=1, storeName='超级管理员',\n publicMsg='💣这是超级管理员字段勿动💣', email='root', password=encrypt_password(\n 'root'), roles=[user_role, super_user_role])\n db.session.add(root_user)\n db.session.commit()\n DataPath = os.path.join(app.root_path, 'static/data/storeList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['storeList']:\n store = store_datastore.create_user(id=one['storeId'],\n storeName=one['storeName'], imagePath=one['storeImgUrl'],\n publicMsg=one['publicMsg'], email='store{}'.format(one[\n 'storeId']), password=encrypt_password('store{}'.format(one\n ['storeId'])), roles=[user_role])\n db.session.add(store)\n for coupon_one in one['actives']:\n coupon = Coupon(coupon_name='测试卷', coupon_num=100,\n coupon_content=coupon_one['acticeText'], store_id=one[\n 'storeId'], actives_id=coupon_one['activeId'])\n db.session.add(coupon)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\nif __name__ == '__main__':\n insertSroreFoodList()\n pass\n",
"<docstring token>\n<import token>\n\n\ndef insertCarousel():\n \"\"\"插入轮播图数据\"\"\"\n print('开始插入轮播图数据...')\n DataPath = os.path.join(app.root_path, 'static/data/carouselList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['carouselList']:\n store = Carousel(id=one['carouselId'], name=one['carouselName'],\n imagePath=one['carouselImgUrl'], publicMsg=one['publicMsg'])\n db.session.add(store)\n db.session.commit()\n print('o98k!')\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print('开始插入优惠卷类型数据...')\n DataDict = {(1): '满减', (2): '新店优惠', (3): '折扣商品', (4): '满返代金券', (5):\n '新用户', (6): '减配送费', (7): '领代金券', (8): '赠送商品'}\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSrore():\n \"\"\"插入商家数据\"\"\"\n print('开始插入商家数据...')\n user_role = Role(name='user', description='普通商家用户')\n super_user_role = Role(name='superuser', description='超级管理员')\n db.session.add(user_role)\n db.session.add(super_user_role)\n db.session.commit()\n root_user = store_datastore.create_user(id=1, storeName='超级管理员',\n publicMsg='💣这是超级管理员字段勿动💣', email='root', password=encrypt_password(\n 'root'), roles=[user_role, super_user_role])\n db.session.add(root_user)\n db.session.commit()\n DataPath = os.path.join(app.root_path, 'static/data/storeList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['storeList']:\n store = store_datastore.create_user(id=one['storeId'],\n storeName=one['storeName'], imagePath=one['storeImgUrl'],\n publicMsg=one['publicMsg'], email='store{}'.format(one[\n 'storeId']), password=encrypt_password('store{}'.format(one\n ['storeId'])), roles=[user_role])\n db.session.add(store)\n for coupon_one in one['actives']:\n coupon = Coupon(coupon_name='测试卷', coupon_num=100,\n coupon_content=coupon_one['acticeText'], store_id=one[\n 'storeId'], actives_id=coupon_one['activeId'])\n db.session.add(coupon)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\nif __name__ == '__main__':\n insertSroreFoodList()\n pass\n",
"<docstring token>\n<import token>\n\n\ndef insertCarousel():\n \"\"\"插入轮播图数据\"\"\"\n print('开始插入轮播图数据...')\n DataPath = os.path.join(app.root_path, 'static/data/carouselList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['carouselList']:\n store = Carousel(id=one['carouselId'], name=one['carouselName'],\n imagePath=one['carouselImgUrl'], publicMsg=one['publicMsg'])\n db.session.add(store)\n db.session.commit()\n print('o98k!')\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print('开始插入优惠卷类型数据...')\n DataDict = {(1): '满减', (2): '新店优惠', (3): '折扣商品', (4): '满返代金券', (5):\n '新用户', (6): '减配送费', (7): '领代金券', (8): '赠送商品'}\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSrore():\n \"\"\"插入商家数据\"\"\"\n print('开始插入商家数据...')\n user_role = Role(name='user', description='普通商家用户')\n super_user_role = Role(name='superuser', description='超级管理员')\n db.session.add(user_role)\n db.session.add(super_user_role)\n db.session.commit()\n root_user = store_datastore.create_user(id=1, storeName='超级管理员',\n publicMsg='💣这是超级管理员字段勿动💣', email='root', password=encrypt_password(\n 'root'), roles=[user_role, super_user_role])\n db.session.add(root_user)\n db.session.commit()\n DataPath = os.path.join(app.root_path, 'static/data/storeList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['storeList']:\n store = store_datastore.create_user(id=one['storeId'],\n storeName=one['storeName'], imagePath=one['storeImgUrl'],\n publicMsg=one['publicMsg'], email='store{}'.format(one[\n 'storeId']), password=encrypt_password('store{}'.format(one\n ['storeId'])), roles=[user_role])\n db.session.add(store)\n for coupon_one in one['actives']:\n coupon = Coupon(coupon_name='测试卷', coupon_num=100,\n coupon_content=coupon_one['acticeText'], store_id=one[\n 'storeId'], actives_id=coupon_one['activeId'])\n db.session.add(coupon)\n db.session.commit()\n print('o98k!')\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n\n\ndef insertCarousel():\n \"\"\"插入轮播图数据\"\"\"\n print('开始插入轮播图数据...')\n DataPath = os.path.join(app.root_path, 'static/data/carouselList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n for one in DataDict['data']['carouselList']:\n store = Carousel(id=one['carouselId'], name=one['carouselName'],\n imagePath=one['carouselImgUrl'], publicMsg=one['publicMsg'])\n db.session.add(store)\n db.session.commit()\n print('o98k!')\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print('开始插入优惠卷类型数据...')\n DataDict = {(1): '满减', (2): '新店优惠', (3): '折扣商品', (4): '满返代金券', (5):\n '新用户', (6): '减配送费', (7): '领代金券', (8): '赠送商品'}\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print('o98k!')\n\n\n<function token>\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n\n\ndef insertActives():\n \"\"\"\n 优惠券类型\n * 1.满减\n * 2.新店优惠\n * 3.折扣商品\n * 4.满返代金券\n * 5.新用户\n * 6.减配送费\n * 7.领代金券\n * 8.赠送商品\n \"\"\"\n print('开始插入优惠卷类型数据...')\n DataDict = {(1): '满减', (2): '新店优惠', (3): '折扣商品', (4): '满返代金券', (5):\n '新用户', (6): '减配送费', (7): '领代金券', (8): '赠送商品'}\n for key, val in DataDict.items():\n actives = Actives(id=key, text=val)\n db.session.add(actives)\n db.session.commit()\n print('o98k!')\n\n\n<function token>\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef insertSroreFoodList():\n \"\"\"插入商家菜品数据\"\"\"\n print('开始插入商家菜品数据...')\n DataPath = os.path.join(app.root_path, 'static/data/storeFoodList.json')\n with open(DataPath, encoding='utf-8') as f:\n DataDict = json.load(f)\n stores = Store.query.filter_by().all()\n for store in stores:\n if store.id != 1:\n for one in DataDict['data']['storeFood']:\n category_id = int(one['titleId'][5:])\n category = Category.query.filter_by(id=category_id).first()\n if category is None:\n category_name = one['title']\n category = Category(id=category_id, category_name=\n category_name)\n db.session.add(category)\n db.session.commit()\n for item in one['items']:\n dish = Dish(dish_name=item['name'], dish_price=item\n ['price'], dish_description='这是菜', imagePath=\n item['foodImgUrl'], store_id=store.id,\n category_id=category_id)\n db.session.add(dish)\n db.session.commit()\n print('o98k!')\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef Insert():\n \"\"\"插入测试数据\"\"\"\n insertCarousel()\n insertActives()\n insertSrore()\n insertSroreFoodList()\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,931 | a6b3c1423b21c66a94297434a968a8e91d0307bf | nome = input('Digite seu nome completo: ').strip()
print(nome.upper())
print(nome.lower())
print(len(nome.replace(' ', '')))
nome_separado = nome.split()
print(len(nome_separado[0]))
print(nome_separado[0], nome_separado[len(nome_separado) - 1]) # EXTRA - Imprimindo Primeiro e Ultimo Nome | [
"nome = input('Digite seu nome completo: ').strip()\n\nprint(nome.upper())\nprint(nome.lower())\nprint(len(nome.replace(' ', '')))\n\nnome_separado = nome.split()\n\nprint(len(nome_separado[0]))\n\nprint(nome_separado[0], nome_separado[len(nome_separado) - 1]) # EXTRA - Imprimindo Primeiro e Ultimo Nome",
"nome = input('Digite seu nome completo: ').strip()\nprint(nome.upper())\nprint(nome.lower())\nprint(len(nome.replace(' ', '')))\nnome_separado = nome.split()\nprint(len(nome_separado[0]))\nprint(nome_separado[0], nome_separado[len(nome_separado) - 1])\n",
"<assignment token>\nprint(nome.upper())\nprint(nome.lower())\nprint(len(nome.replace(' ', '')))\n<assignment token>\nprint(len(nome_separado[0]))\nprint(nome_separado[0], nome_separado[len(nome_separado) - 1])\n",
"<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,932 | 72a96a4c7c6e745aaf52f3c3bb32e6a19c5a79d0 | # coding=utf-8
"""Plot Tools."""
import matplotlib.pyplot as plt
from sklearn.metrics import auc, roc_curve
import numpy as np
def plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params):
"""
A function plot Roc AUC.
Parameters:
y_true: Array
True label
y_pred_prob: Array
Probability predicted label
show_threshold: Bool
Show threshold
Returns:
figure: Figure
roc_auc: AUC value
"""
figure = plt.figure(figsize=params.get('figsize', (17, 10)))
fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label='ROC curve (area = %0.5f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xticks(np.arange(0.0, 1.1, step=0.1))
plt.yticks(np.arange(0.0, 1.1, step=0.1))
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve')
plt.legend(loc="lower right")
if show_threshold:
ax2 = plt.gca().twinx()
ax2.plot(fpr, thresholds, markeredgecolor='r',
linestyle='dashed', color='r')
ax2.set_ylabel('Threshold', color='r')
ax2.set_ylim([0.0, 1.0])
ax2.set_xlim([0.0, 1.0])
plt.show()
return figure, roc_auc
def plot_multi_roc_curve(y_trues, y_pred_probs, labels, **params):
"""
A function plot Roc AUC.
Parameters:
y_trues: Array of Array
True label
y_pred_probs: Array of Array
Probability predicted label
labels: List
List of label
Returns:
figure: Figure
roc_aucs: List AUC value
"""
figure = plt.figure(figsize=params.get('figsize', (17, 10)))
roc_aucs = []
for y_true, y_pred_prob, label in zip(y_trues, y_pred_probs, labels):
fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)
roc_auc = auc(fpr, tpr)
roc_aucs.append(roc_auc)
plt.plot(fpr, tpr, label=f'{label} ROC curve (area = %0.5f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xticks(np.arange(0.0, 1.1, step=0.1))
plt.yticks(np.arange(0.0, 1.1, step=0.1))
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve')
plt.legend(loc="lower right")
plt.show()
return figure, roc_aucs
| [
"# coding=utf-8\n\"\"\"Plot Tools.\"\"\"\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import auc, roc_curve\nimport numpy as np\n\n\ndef plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_true: Array\n True label\n y_pred_prob: Array\n Probability predicted label\n show_threshold: Bool\n Show threshold\n Returns:\n figure: Figure\n roc_auc: AUC value\n \"\"\"\n\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, label='ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc=\"lower right\")\n if show_threshold:\n ax2 = plt.gca().twinx()\n ax2.plot(fpr, thresholds, markeredgecolor='r',\n linestyle='dashed', color='r')\n ax2.set_ylabel('Threshold', color='r')\n ax2.set_ylim([0.0, 1.0])\n ax2.set_xlim([0.0, 1.0])\n\n plt.show()\n\n return figure, roc_auc\n\n\ndef plot_multi_roc_curve(y_trues, y_pred_probs, labels, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_trues: Array of Array\n True label\n y_pred_probs: Array of Array\n Probability predicted label\n labels: List\n List of label\n Returns:\n figure: Figure\n roc_aucs: List AUC value\n \"\"\"\n\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n roc_aucs = []\n for y_true, y_pred_prob, label in zip(y_trues, y_pred_probs, labels):\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n roc_aucs.append(roc_auc)\n plt.plot(fpr, tpr, label=f'{label} ROC curve (area = %0.5f)' % roc_auc)\n\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc=\"lower right\")\n\n plt.show()\n\n return figure, roc_aucs\n",
"<docstring token>\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import auc, roc_curve\nimport numpy as np\n\n\ndef plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_true: Array\n True label\n y_pred_prob: Array\n Probability predicted label\n show_threshold: Bool\n Show threshold\n Returns:\n figure: Figure\n roc_auc: AUC value\n \"\"\"\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, label='ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc='lower right')\n if show_threshold:\n ax2 = plt.gca().twinx()\n ax2.plot(fpr, thresholds, markeredgecolor='r', linestyle='dashed',\n color='r')\n ax2.set_ylabel('Threshold', color='r')\n ax2.set_ylim([0.0, 1.0])\n ax2.set_xlim([0.0, 1.0])\n plt.show()\n return figure, roc_auc\n\n\ndef plot_multi_roc_curve(y_trues, y_pred_probs, labels, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_trues: Array of Array\n True label\n y_pred_probs: Array of Array\n Probability predicted label\n labels: List\n List of label\n Returns:\n figure: Figure\n roc_aucs: List AUC value\n \"\"\"\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n roc_aucs = []\n for y_true, y_pred_prob, label in zip(y_trues, y_pred_probs, labels):\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n roc_aucs.append(roc_auc)\n plt.plot(fpr, tpr, label=f'{label} ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc='lower right')\n plt.show()\n return figure, roc_aucs\n",
"<docstring token>\n<import token>\n\n\ndef plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_true: Array\n True label\n y_pred_prob: Array\n Probability predicted label\n show_threshold: Bool\n Show threshold\n Returns:\n figure: Figure\n roc_auc: AUC value\n \"\"\"\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, label='ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc='lower right')\n if show_threshold:\n ax2 = plt.gca().twinx()\n ax2.plot(fpr, thresholds, markeredgecolor='r', linestyle='dashed',\n color='r')\n ax2.set_ylabel('Threshold', color='r')\n ax2.set_ylim([0.0, 1.0])\n ax2.set_xlim([0.0, 1.0])\n plt.show()\n return figure, roc_auc\n\n\ndef plot_multi_roc_curve(y_trues, y_pred_probs, labels, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_trues: Array of Array\n True label\n y_pred_probs: Array of Array\n Probability predicted label\n labels: List\n List of label\n Returns:\n figure: Figure\n roc_aucs: List AUC value\n \"\"\"\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n roc_aucs = []\n for y_true, y_pred_prob, label in zip(y_trues, y_pred_probs, labels):\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n roc_aucs.append(roc_auc)\n plt.plot(fpr, tpr, label=f'{label} ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc='lower right')\n plt.show()\n return figure, roc_aucs\n",
"<docstring token>\n<import token>\n<function token>\n\n\ndef plot_multi_roc_curve(y_trues, y_pred_probs, labels, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n y_trues: Array of Array\n True label\n y_pred_probs: Array of Array\n Probability predicted label\n labels: List\n List of label\n Returns:\n figure: Figure\n roc_aucs: List AUC value\n \"\"\"\n figure = plt.figure(figsize=params.get('figsize', (17, 10)))\n roc_aucs = []\n for y_true, y_pred_prob, label in zip(y_trues, y_pred_probs, labels):\n fpr, tpr, thresholds = roc_curve(y_true, y_pred_prob)\n roc_auc = auc(fpr, tpr)\n roc_aucs.append(roc_auc)\n plt.plot(fpr, tpr, label=f'{label} ROC curve (area = %0.5f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.legend(loc='lower right')\n plt.show()\n return figure, roc_aucs\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n"
] | false |
99,933 | 152867d01dd1309a9472762c4e421a2ff7c7105e | #
# @lc app=leetcode id=935 lang=python3
#
# [935] Knight Dialer
#
# @lc code=start
# TAGS: Dynamic Programming
import sys
sys.setrecursionlimit(5010)
class Solution:
# 2800 ms, 24.18%. Time and Space: O(N). Recursion with memoization
def knightDialer(self, n: int) -> int:
future_moves = {1: [6, 8], 2: [7, 7], 0:[4, 4], 3: [4, 8], 4:[0, 9, 3], 6:[0, 1, 7], 7:[2, 6], 8:[1, 1], 9:[2, 4]}
MOD = 10**9 + 7
if n == 1: return 10
#@functools.lru_cache
memo = {}
def dfs(i, depth=1):
if (i, depth) in memo:
return memo[(i, depth)]
if depth == n:
return 1
rv = 0
for move in future_moves[i]:
rv += dfs(move, depth + 1)
memo[(i, depth)] = rv
return rv
ans = 0
for i in range(10):
if i in (3, 5, 6, 9): continue
elif i in (1, 4, 7):
ans += dfs(i)*2
else:# 2 8
ans += dfs(i)
return ans % MOD
# 832 ms, 87.51%. Time: O(N). Space: O(1). DP
# To get to this, think about the time complexity of memoization:
# [0, 1] [1, 1] [2, 1] ... [9, 1]
# [0, 2] [1, 2] [2, 2] ... [9, 2]
# ...
# [0, n] [1, n] [2, n] ... [9, n]
def knightDialer1(self, n: int) -> int:
future_moves = {1: [6, 8], 2: [7, 7], 0:[4, 4], 3: [4, 8], 4:[0, 9, 3], 6:[0, 1, 7], 7:[2, 6], 8:[1, 1], 9:[2, 4]}
MOD = 10**9 + 7
dp = [1]*10
for _ in range(1, n):
new_dp = [0]*10
for i in [0, 1, 2, 3, 4, 6, 7, 8, 9]:
for move in future_moves[i]:
new_dp[i] += dp[move]
new_dp[i] %= MOD
dp = new_dp
return sum(dp) % MOD
# @lc code=end
| [
"#\n# @lc app=leetcode id=935 lang=python3\n#\n# [935] Knight Dialer\n#\n\n# @lc code=start\n# TAGS: Dynamic Programming\nimport sys\nsys.setrecursionlimit(5010)\nclass Solution:\n\n # 2800 ms, 24.18%. Time and Space: O(N). Recursion with memoization\n def knightDialer(self, n: int) -> int:\n future_moves = {1: [6, 8], 2: [7, 7], 0:[4, 4], 3: [4, 8], 4:[0, 9, 3], 6:[0, 1, 7], 7:[2, 6], 8:[1, 1], 9:[2, 4]}\n MOD = 10**9 + 7\n if n == 1: return 10\n\n #@functools.lru_cache \n memo = {}\n def dfs(i, depth=1):\n if (i, depth) in memo:\n return memo[(i, depth)]\n\n if depth == n:\n return 1\n rv = 0\n for move in future_moves[i]:\n rv += dfs(move, depth + 1)\n memo[(i, depth)] = rv\n return rv\n\n ans = 0 \n for i in range(10):\n if i in (3, 5, 6, 9): continue\n elif i in (1, 4, 7):\n ans += dfs(i)*2\n else:# 2 8\n ans += dfs(i)\n return ans % MOD\n \n # 832 ms, 87.51%. Time: O(N). Space: O(1). DP\n # To get to this, think about the time complexity of memoization:\n # [0, 1] [1, 1] [2, 1] ... [9, 1]\n # [0, 2] [1, 2] [2, 2] ... [9, 2]\n # ...\n # [0, n] [1, n] [2, n] ... [9, n]\n def knightDialer1(self, n: int) -> int:\n future_moves = {1: [6, 8], 2: [7, 7], 0:[4, 4], 3: [4, 8], 4:[0, 9, 3], 6:[0, 1, 7], 7:[2, 6], 8:[1, 1], 9:[2, 4]}\n MOD = 10**9 + 7\n dp = [1]*10\n for _ in range(1, n):\n new_dp = [0]*10\n for i in [0, 1, 2, 3, 4, 6, 7, 8, 9]:\n for move in future_moves[i]:\n new_dp[i] += dp[move]\n new_dp[i] %= MOD\n dp = new_dp\n return sum(dp) % MOD\n# @lc code=end\n\n",
"import sys\nsys.setrecursionlimit(5010)\n\n\nclass Solution:\n\n def knightDialer(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n if n == 1:\n return 10\n memo = {}\n\n def dfs(i, depth=1):\n if (i, depth) in memo:\n return memo[i, depth]\n if depth == n:\n return 1\n rv = 0\n for move in future_moves[i]:\n rv += dfs(move, depth + 1)\n memo[i, depth] = rv\n return rv\n ans = 0\n for i in range(10):\n if i in (3, 5, 6, 9):\n continue\n elif i in (1, 4, 7):\n ans += dfs(i) * 2\n else:\n ans += dfs(i)\n return ans % MOD\n\n def knightDialer1(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n dp = [1] * 10\n for _ in range(1, n):\n new_dp = [0] * 10\n for i in [0, 1, 2, 3, 4, 6, 7, 8, 9]:\n for move in future_moves[i]:\n new_dp[i] += dp[move]\n new_dp[i] %= MOD\n dp = new_dp\n return sum(dp) % MOD\n",
"<import token>\nsys.setrecursionlimit(5010)\n\n\nclass Solution:\n\n def knightDialer(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n if n == 1:\n return 10\n memo = {}\n\n def dfs(i, depth=1):\n if (i, depth) in memo:\n return memo[i, depth]\n if depth == n:\n return 1\n rv = 0\n for move in future_moves[i]:\n rv += dfs(move, depth + 1)\n memo[i, depth] = rv\n return rv\n ans = 0\n for i in range(10):\n if i in (3, 5, 6, 9):\n continue\n elif i in (1, 4, 7):\n ans += dfs(i) * 2\n else:\n ans += dfs(i)\n return ans % MOD\n\n def knightDialer1(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n dp = [1] * 10\n for _ in range(1, n):\n new_dp = [0] * 10\n for i in [0, 1, 2, 3, 4, 6, 7, 8, 9]:\n for move in future_moves[i]:\n new_dp[i] += dp[move]\n new_dp[i] %= MOD\n dp = new_dp\n return sum(dp) % MOD\n",
"<import token>\n<code token>\n\n\nclass Solution:\n\n def knightDialer(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n if n == 1:\n return 10\n memo = {}\n\n def dfs(i, depth=1):\n if (i, depth) in memo:\n return memo[i, depth]\n if depth == n:\n return 1\n rv = 0\n for move in future_moves[i]:\n rv += dfs(move, depth + 1)\n memo[i, depth] = rv\n return rv\n ans = 0\n for i in range(10):\n if i in (3, 5, 6, 9):\n continue\n elif i in (1, 4, 7):\n ans += dfs(i) * 2\n else:\n ans += dfs(i)\n return ans % MOD\n\n def knightDialer1(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n dp = [1] * 10\n for _ in range(1, n):\n new_dp = [0] * 10\n for i in [0, 1, 2, 3, 4, 6, 7, 8, 9]:\n for move in future_moves[i]:\n new_dp[i] += dp[move]\n new_dp[i] %= MOD\n dp = new_dp\n return sum(dp) % MOD\n",
"<import token>\n<code token>\n\n\nclass Solution:\n\n def knightDialer(self, n: int) ->int:\n future_moves = {(1): [6, 8], (2): [7, 7], (0): [4, 4], (3): [4, 8],\n (4): [0, 9, 3], (6): [0, 1, 7], (7): [2, 6], (8): [1, 1], (9):\n [2, 4]}\n MOD = 10 ** 9 + 7\n if n == 1:\n return 10\n memo = {}\n\n def dfs(i, depth=1):\n if (i, depth) in memo:\n return memo[i, depth]\n if depth == n:\n return 1\n rv = 0\n for move in future_moves[i]:\n rv += dfs(move, depth + 1)\n memo[i, depth] = rv\n return rv\n ans = 0\n for i in range(10):\n if i in (3, 5, 6, 9):\n continue\n elif i in (1, 4, 7):\n ans += dfs(i) * 2\n else:\n ans += dfs(i)\n return ans % MOD\n <function token>\n",
"<import token>\n<code token>\n\n\nclass Solution:\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<class token>\n"
] | false |
99,934 | bc6a79ed2d6197db15cc9d34198313b3f24e681b | from __future__ import annotations
import os
from xml.etree import ElementTree
from cloudshell.layer_one.core.helper.xml_helper import XMLHelper
from cloudshell.layer_one.core.response.command_response import CommandResponse
ElementTree.register_namespace(
"", "http://schemas.qualisystems.com/ResourceManagement/DriverCommandResult.xsd"
)
def full_path(relative_path: str) -> str:
return os.path.join(os.path.dirname(__file__), relative_path)
class CommandResponsesBuilder:
RESPONSES_TEMPLATE = XMLHelper.read_template(
full_path("templates/responses_template.xml")
)
COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(
full_path("templates/command_response_template.xml")
)
ERROR_RESPONSE = XMLHelper.read_template(full_path("templates/error_response.xml"))
@staticmethod
def _build_command_response_node(
command_response: CommandResponse,
) -> ElementTree.Element:
"""Build command response node."""
command_response_node = XMLHelper.build_node_from_string(
CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE
)
command_response_node.set(
"CommandName", command_response.command_request.command_name
)
command_response_node.set(
"CommandId", command_response.command_request.command_id
)
command_response_node.set("Success", str(command_response.success).lower())
timestamp_node = command_response_node.find("Timestamp")
timestamp_node.text = command_response.timestamp
if command_response.error is not None:
command_response_node.find("Error").text = command_response.error
if command_response.log is not None:
command_response_node.find("Log").text = command_response.log
if command_response.response_info is not None:
command_response_node.append(
command_response.response_info.build_xml_node()
)
else:
command_response_node.append(ElementTree.Element("ResponseInfo"))
return command_response_node
@staticmethod
def build_xml_result(responses: list[CommandResponse]) -> ElementTree.Element:
"""Build responses for list of responses objects."""
responses_node = XMLHelper.build_node_from_string(
CommandResponsesBuilder.RESPONSES_TEMPLATE
)
tree = ElementTree.ElementTree(responses_node)
for command_response in responses:
responses_node.append(
CommandResponsesBuilder._build_command_response_node(command_response)
)
return tree.getroot()
@staticmethod
def to_string(root: ElementTree.Element) -> str:
"""Generate string for xml node."""
return ElementTree.tostring(root, encoding="unicode", method="xml").replace(
"\n", "\r\n"
)
@staticmethod
def build_xml_error(error_code, log_message):
"""Build error response."""
command_response_node = XMLHelper.build_node_from_string(
CommandResponsesBuilder.ERROR_RESPONSE
)
tree = ElementTree.ElementTree(command_response_node)
namespace = XMLHelper.get_node_namespace(command_response_node)
command_response_node.find(f"{namespace}ErrorCode").text = str(error_code)
command_response_node.find(f"{namespace}Log").text = str(log_message)
return tree.getroot()
| [
"from __future__ import annotations\n\nimport os\nfrom xml.etree import ElementTree\n\nfrom cloudshell.layer_one.core.helper.xml_helper import XMLHelper\nfrom cloudshell.layer_one.core.response.command_response import CommandResponse\n\nElementTree.register_namespace(\n \"\", \"http://schemas.qualisystems.com/ResourceManagement/DriverCommandResult.xsd\"\n)\n\n\ndef full_path(relative_path: str) -> str:\n return os.path.join(os.path.dirname(__file__), relative_path)\n\n\nclass CommandResponsesBuilder:\n RESPONSES_TEMPLATE = XMLHelper.read_template(\n full_path(\"templates/responses_template.xml\")\n )\n COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(\n full_path(\"templates/command_response_template.xml\")\n )\n ERROR_RESPONSE = XMLHelper.read_template(full_path(\"templates/error_response.xml\"))\n\n @staticmethod\n def _build_command_response_node(\n command_response: CommandResponse,\n ) -> ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE\n )\n command_response_node.set(\n \"CommandName\", command_response.command_request.command_name\n )\n command_response_node.set(\n \"CommandId\", command_response.command_request.command_id\n )\n command_response_node.set(\"Success\", str(command_response.success).lower())\n\n timestamp_node = command_response_node.find(\"Timestamp\")\n timestamp_node.text = command_response.timestamp\n\n if command_response.error is not None:\n command_response_node.find(\"Error\").text = command_response.error\n\n if command_response.log is not None:\n command_response_node.find(\"Log\").text = command_response.log\n\n if command_response.response_info is not None:\n command_response_node.append(\n command_response.response_info.build_xml_node()\n )\n else:\n command_response_node.append(ElementTree.Element(\"ResponseInfo\"))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]) -> ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE\n )\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(\n CommandResponsesBuilder._build_command_response_node(command_response)\n )\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) -> str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding=\"unicode\", method=\"xml\").replace(\n \"\\n\", \"\\r\\n\"\n )\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE\n )\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f\"{namespace}ErrorCode\").text = str(error_code)\n command_response_node.find(f\"{namespace}Log\").text = str(log_message)\n return tree.getroot()\n",
"from __future__ import annotations\nimport os\nfrom xml.etree import ElementTree\nfrom cloudshell.layer_one.core.helper.xml_helper import XMLHelper\nfrom cloudshell.layer_one.core.response.command_response import CommandResponse\nElementTree.register_namespace('',\n 'http://schemas.qualisystems.com/ResourceManagement/DriverCommandResult.xsd'\n )\n\n\ndef full_path(relative_path: str) ->str:\n return os.path.join(os.path.dirname(__file__), relative_path)\n\n\nclass CommandResponsesBuilder:\n RESPONSES_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/responses_template.xml'))\n COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/command_response_template.xml'))\n ERROR_RESPONSE = XMLHelper.read_template(full_path(\n 'templates/error_response.xml'))\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) ->str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding='unicode', method='xml'\n ).replace('\\n', '\\r\\n')\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\nElementTree.register_namespace('',\n 'http://schemas.qualisystems.com/ResourceManagement/DriverCommandResult.xsd'\n )\n\n\ndef full_path(relative_path: str) ->str:\n return os.path.join(os.path.dirname(__file__), relative_path)\n\n\nclass CommandResponsesBuilder:\n RESPONSES_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/responses_template.xml'))\n COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/command_response_template.xml'))\n ERROR_RESPONSE = XMLHelper.read_template(full_path(\n 'templates/error_response.xml'))\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) ->str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding='unicode', method='xml'\n ).replace('\\n', '\\r\\n')\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\n<code token>\n\n\ndef full_path(relative_path: str) ->str:\n return os.path.join(os.path.dirname(__file__), relative_path)\n\n\nclass CommandResponsesBuilder:\n RESPONSES_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/responses_template.xml'))\n COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/command_response_template.xml'))\n ERROR_RESPONSE = XMLHelper.read_template(full_path(\n 'templates/error_response.xml'))\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) ->str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding='unicode', method='xml'\n ).replace('\\n', '\\r\\n')\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n RESPONSES_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/responses_template.xml'))\n COMMAND_RESPONSE_TEMPLATE = XMLHelper.read_template(full_path(\n 'templates/command_response_template.xml'))\n ERROR_RESPONSE = XMLHelper.read_template(full_path(\n 'templates/error_response.xml'))\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) ->str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding='unicode', method='xml'\n ).replace('\\n', '\\r\\n')\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n <assignment token>\n <assignment token>\n <assignment token>\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n\n @staticmethod\n def to_string(root: ElementTree.Element) ->str:\n \"\"\"Generate string for xml node.\"\"\"\n return ElementTree.tostring(root, encoding='unicode', method='xml'\n ).replace('\\n', '\\r\\n')\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n <assignment token>\n <assignment token>\n <assignment token>\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n <function token>\n\n @staticmethod\n def build_xml_error(error_code, log_message):\n \"\"\"Build error response.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.ERROR_RESPONSE)\n tree = ElementTree.ElementTree(command_response_node)\n namespace = XMLHelper.get_node_namespace(command_response_node)\n command_response_node.find(f'{namespace}ErrorCode').text = str(\n error_code)\n command_response_node.find(f'{namespace}Log').text = str(log_message)\n return tree.getroot()\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n <assignment token>\n <assignment token>\n <assignment token>\n\n @staticmethod\n def _build_command_response_node(command_response: CommandResponse\n ) ->ElementTree.Element:\n \"\"\"Build command response node.\"\"\"\n command_response_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.COMMAND_RESPONSE_TEMPLATE)\n command_response_node.set('CommandName', command_response.\n command_request.command_name)\n command_response_node.set('CommandId', command_response.\n command_request.command_id)\n command_response_node.set('Success', str(command_response.success).\n lower())\n timestamp_node = command_response_node.find('Timestamp')\n timestamp_node.text = command_response.timestamp\n if command_response.error is not None:\n command_response_node.find('Error').text = command_response.error\n if command_response.log is not None:\n command_response_node.find('Log').text = command_response.log\n if command_response.response_info is not None:\n command_response_node.append(command_response.response_info.\n build_xml_node())\n else:\n command_response_node.append(ElementTree.Element('ResponseInfo'))\n return command_response_node\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n @staticmethod\n def build_xml_result(responses: list[CommandResponse]\n ) ->ElementTree.Element:\n \"\"\"Build responses for list of responses objects.\"\"\"\n responses_node = XMLHelper.build_node_from_string(\n CommandResponsesBuilder.RESPONSES_TEMPLATE)\n tree = ElementTree.ElementTree(responses_node)\n for command_response in responses:\n responses_node.append(CommandResponsesBuilder.\n _build_command_response_node(command_response))\n return tree.getroot()\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<function token>\n\n\nclass CommandResponsesBuilder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n",
"<import token>\n<code token>\n<function token>\n<class token>\n"
] | false |
99,935 | 71ddbe711aeabf84ecf9c32197ac4e17b21ddba4 | from django.contrib import admin
from . models import csv_data
from . models import temp_ssdata
# Register your models here.
admin.site.register(csv_data)
admin.site.register(temp_ssdata) | [
"from django.contrib import admin\nfrom . models import csv_data\nfrom . models import temp_ssdata\n# Register your models here.\n\nadmin.site.register(csv_data)\nadmin.site.register(temp_ssdata)",
"from django.contrib import admin\nfrom .models import csv_data\nfrom .models import temp_ssdata\nadmin.site.register(csv_data)\nadmin.site.register(temp_ssdata)\n",
"<import token>\nadmin.site.register(csv_data)\nadmin.site.register(temp_ssdata)\n",
"<import token>\n<code token>\n"
] | false |
99,936 | 0892d2bd363ae7a15e05aab651e5310ccb23362a | import numpy as np
import pandas as pd
from scipy import stats
from util.caching import cache_today
# FIXME: There are more exact significance tests with more resolving power for our
# cases, e.g. Barnard's or Boschloo's tests.
def binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs):
if table is None:
if not isinstance(counts, np.ndarray):
counts = np.asarray(counts)
if not isinstance(frequencies, np.ndarray):
frequencies = np.asarray(frequencies)
table = np.nan_to_num(np.vstack([
(1 - frequencies) * counts,
frequencies * counts,
]))
if isinstance(table, pd.DataFrame):
table = table.values
pv = np.nan
if table.min() >= chi_min:
# fisher_exact slow as molasses for large Np; chi2 _should_ be a reasonable
# approximation if Np>5 for all N, p.
pv = stats.chi2_contingency(table)[1]
else:
# fisher_exact was taking 60-240s in some cases based on specific inputs.
# it's been restricted down enough at this point that it's fast enough
# in general, but we might be being overly cautious here.
@cache_today
def __fisher_exact(table):
return stats.fisher_exact(table)[1]
pv = __fisher_exact(table)
return pv
def _normal_map(original_s, std_s, prior_mean, prior_std):
corrected_s = ((original_s * prior_std**2) + (prior_mean * std_s**2)) / \
( prior_std**2 + std_s**2)
if isinstance(std_s, pd.Series):
corrected_s[std_s == np.inf] = prior_mean
elif std_s == np.inf:
corrected_s = prior_mean
return corrected_s
def _binom_std(sample, p):
if sample == 0:
return np.inf
elif pd.isnull(sample):
return np.inf
return stats.binom.std(sample, p=p) / sample
def _map_corrected_pct(original_s, sample_s, overall_mean, prior_sample=50):
if isinstance(overall_mean, pd.Series):
std_df = pd.DataFrame({ "sample": sample_s, "overall_mean": overall_mean })
std_s = std_df.apply(lambda row: _binom_std(row["sample"], row["overall_mean"]), axis=1)
elif isinstance(sample_s, pd.Series):
std_s = sample_s.apply(_binom_std, p=overall_mean)
elif isinstance(sample_s, (int, float)):
std_s = _binom_std(sample_s, overall_mean)
else:
raise ValueError()
# Doing a poor man's maximum a posteriori estimate of a percentage using the overall sample
# mean as the prior. https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation#Example
#
# Instead of the full set, we use GAUSSIAN_PRIOR_SAMPLE to model the prior's variance. To
# intuitively interpret this, observe that the prior contributes the same amount as the sample
# if the sample has GAUSSIAN_PRIOR_SAMPLE elements.
prior_std = _binom_std(prior_sample, overall_mean)
corrected_s = _normal_map(original_s, std_s, overall_mean, prior_std)
return corrected_s, std_s
| [
"import numpy as np\nimport pandas as pd\nfrom scipy import stats\n\nfrom util.caching import cache_today\n\n\n# FIXME: There are more exact significance tests with more resolving power for our\n# cases, e.g. Barnard's or Boschloo's tests.\ndef binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs):\n if table is None:\n if not isinstance(counts, np.ndarray):\n counts = np.asarray(counts)\n if not isinstance(frequencies, np.ndarray):\n frequencies = np.asarray(frequencies)\n\n table = np.nan_to_num(np.vstack([\n (1 - frequencies) * counts,\n frequencies * counts,\n ]))\n if isinstance(table, pd.DataFrame):\n table = table.values\n\n pv = np.nan\n if table.min() >= chi_min:\n # fisher_exact slow as molasses for large Np; chi2 _should_ be a reasonable\n # approximation if Np>5 for all N, p.\n pv = stats.chi2_contingency(table)[1]\n\n else:\n # fisher_exact was taking 60-240s in some cases based on specific inputs.\n # it's been restricted down enough at this point that it's fast enough\n # in general, but we might be being overly cautious here.\n @cache_today\n def __fisher_exact(table):\n return stats.fisher_exact(table)[1]\n pv = __fisher_exact(table)\n\n return pv\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = ((original_s * prior_std**2) + (prior_mean * std_s**2)) / \\\n ( prior_std**2 + std_s**2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\ndef _binom_std(sample, p):\n if sample == 0:\n return np.inf\n elif pd.isnull(sample):\n return np.inf\n return stats.binom.std(sample, p=p) / sample\n\ndef _map_corrected_pct(original_s, sample_s, overall_mean, prior_sample=50):\n if isinstance(overall_mean, pd.Series):\n std_df = pd.DataFrame({ \"sample\": sample_s, \"overall_mean\": overall_mean })\n std_s = std_df.apply(lambda row: _binom_std(row[\"sample\"], row[\"overall_mean\"]), axis=1)\n elif isinstance(sample_s, pd.Series):\n std_s = sample_s.apply(_binom_std, p=overall_mean)\n elif isinstance(sample_s, (int, float)):\n std_s = _binom_std(sample_s, overall_mean)\n else:\n raise ValueError()\n\n # Doing a poor man's maximum a posteriori estimate of a percentage using the overall sample\n # mean as the prior. https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation#Example\n #\n # Instead of the full set, we use GAUSSIAN_PRIOR_SAMPLE to model the prior's variance. To\n # intuitively interpret this, observe that the prior contributes the same amount as the sample\n # if the sample has GAUSSIAN_PRIOR_SAMPLE elements.\n prior_std = _binom_std(prior_sample, overall_mean)\n corrected_s = _normal_map(original_s, std_s, overall_mean, prior_std)\n\n return corrected_s, std_s\n",
"import numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom util.caching import cache_today\n\n\ndef binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs\n ):\n if table is None:\n if not isinstance(counts, np.ndarray):\n counts = np.asarray(counts)\n if not isinstance(frequencies, np.ndarray):\n frequencies = np.asarray(frequencies)\n table = np.nan_to_num(np.vstack([(1 - frequencies) * counts, \n frequencies * counts]))\n if isinstance(table, pd.DataFrame):\n table = table.values\n pv = np.nan\n if table.min() >= chi_min:\n pv = stats.chi2_contingency(table)[1]\n else:\n\n @cache_today\n def __fisher_exact(table):\n return stats.fisher_exact(table)[1]\n pv = __fisher_exact(table)\n return pv\n\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = (original_s * prior_std ** 2 + prior_mean * std_s ** 2) / (\n prior_std ** 2 + std_s ** 2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\n\ndef _binom_std(sample, p):\n if sample == 0:\n return np.inf\n elif pd.isnull(sample):\n return np.inf\n return stats.binom.std(sample, p=p) / sample\n\n\ndef _map_corrected_pct(original_s, sample_s, overall_mean, prior_sample=50):\n if isinstance(overall_mean, pd.Series):\n std_df = pd.DataFrame({'sample': sample_s, 'overall_mean':\n overall_mean})\n std_s = std_df.apply(lambda row: _binom_std(row['sample'], row[\n 'overall_mean']), axis=1)\n elif isinstance(sample_s, pd.Series):\n std_s = sample_s.apply(_binom_std, p=overall_mean)\n elif isinstance(sample_s, (int, float)):\n std_s = _binom_std(sample_s, overall_mean)\n else:\n raise ValueError()\n prior_std = _binom_std(prior_sample, overall_mean)\n corrected_s = _normal_map(original_s, std_s, overall_mean, prior_std)\n return corrected_s, std_s\n",
"<import token>\n\n\ndef binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs\n ):\n if table is None:\n if not isinstance(counts, np.ndarray):\n counts = np.asarray(counts)\n if not isinstance(frequencies, np.ndarray):\n frequencies = np.asarray(frequencies)\n table = np.nan_to_num(np.vstack([(1 - frequencies) * counts, \n frequencies * counts]))\n if isinstance(table, pd.DataFrame):\n table = table.values\n pv = np.nan\n if table.min() >= chi_min:\n pv = stats.chi2_contingency(table)[1]\n else:\n\n @cache_today\n def __fisher_exact(table):\n return stats.fisher_exact(table)[1]\n pv = __fisher_exact(table)\n return pv\n\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = (original_s * prior_std ** 2 + prior_mean * std_s ** 2) / (\n prior_std ** 2 + std_s ** 2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\n\ndef _binom_std(sample, p):\n if sample == 0:\n return np.inf\n elif pd.isnull(sample):\n return np.inf\n return stats.binom.std(sample, p=p) / sample\n\n\ndef _map_corrected_pct(original_s, sample_s, overall_mean, prior_sample=50):\n if isinstance(overall_mean, pd.Series):\n std_df = pd.DataFrame({'sample': sample_s, 'overall_mean':\n overall_mean})\n std_s = std_df.apply(lambda row: _binom_std(row['sample'], row[\n 'overall_mean']), axis=1)\n elif isinstance(sample_s, pd.Series):\n std_s = sample_s.apply(_binom_std, p=overall_mean)\n elif isinstance(sample_s, (int, float)):\n std_s = _binom_std(sample_s, overall_mean)\n else:\n raise ValueError()\n prior_std = _binom_std(prior_sample, overall_mean)\n corrected_s = _normal_map(original_s, std_s, overall_mean, prior_std)\n return corrected_s, std_s\n",
"<import token>\n\n\ndef binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs\n ):\n if table is None:\n if not isinstance(counts, np.ndarray):\n counts = np.asarray(counts)\n if not isinstance(frequencies, np.ndarray):\n frequencies = np.asarray(frequencies)\n table = np.nan_to_num(np.vstack([(1 - frequencies) * counts, \n frequencies * counts]))\n if isinstance(table, pd.DataFrame):\n table = table.values\n pv = np.nan\n if table.min() >= chi_min:\n pv = stats.chi2_contingency(table)[1]\n else:\n\n @cache_today\n def __fisher_exact(table):\n return stats.fisher_exact(table)[1]\n pv = __fisher_exact(table)\n return pv\n\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = (original_s * prior_std ** 2 + prior_mean * std_s ** 2) / (\n prior_std ** 2 + std_s ** 2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\n\ndef _binom_std(sample, p):\n if sample == 0:\n return np.inf\n elif pd.isnull(sample):\n return np.inf\n return stats.binom.std(sample, p=p) / sample\n\n\n<function token>\n",
"<import token>\n<function token>\n\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = (original_s * prior_std ** 2 + prior_mean * std_s ** 2) / (\n prior_std ** 2 + std_s ** 2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\n\ndef _binom_std(sample, p):\n if sample == 0:\n return np.inf\n elif pd.isnull(sample):\n return np.inf\n return stats.binom.std(sample, p=p) / sample\n\n\n<function token>\n",
"<import token>\n<function token>\n\n\ndef _normal_map(original_s, std_s, prior_mean, prior_std):\n corrected_s = (original_s * prior_std ** 2 + prior_mean * std_s ** 2) / (\n prior_std ** 2 + std_s ** 2)\n if isinstance(std_s, pd.Series):\n corrected_s[std_s == np.inf] = prior_mean\n elif std_s == np.inf:\n corrected_s = prior_mean\n return corrected_s\n\n\n<function token>\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,937 | 662cb7300294342a812a13cf2132502ee45aad7c | import sys, os
from lxml import objectify
usage = """
Usage is:
py admx2oma.py <your.admx> <ADMX-OMA-URI>
<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file
Take care, the OMA-URI is case sensitive.
<your.admx> : The admx file you ingested
"""
def run():
if len(sys.argv) < 3:
print(usage)
sys.exit()
admxFile = sys.argv[1]
admxOMA_URI = sys.argv[2]
if not os.path.exists(admxFile):
print("file not found: " + admxFile)
sys.exit()
templatestring = "./<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>"
catHierarchie = {}
try:
(AppName, SettingType, id_or_admxName) = admxOMA_URI.partition("/ADMXInstall/")[2].split("/")
except BaseException:
print()
print("ERROR: Bad OMA-URI: " + admxOMA_URI)
print(usage)
sys.exit()
admx = objectify.parse(admxFile)
r = admx.getroot()
for category in r.categories.getchildren():
ref = category.parentCategory.get('ref') if hasattr(category, "parentCategory") else ":"
catHierarchie[category.get("name")] = ref
for policy in r.policies.findall("policy", namespaces=r.nsmap):
out = templatestring
out = out.replace("<policy>", policy.get("name"))
hierarchie = policy.parentCategory.get("ref")
nextCat = catHierarchie[policy.parentCategory.get("ref")]
while nextCat.find(":") == -1:
hierarchie = '~'.join((nextCat, hierarchie))
if not nextCat in catHierarchie:
break
nextCat = catHierarchie[nextCat]
hierarchie = '~'.join((AppName, SettingType, hierarchie))
out = out.replace("<area>", hierarchie)
p = PolicyOutput(policy.get("name"))
if policy.get("class") in ("Both", "User"):
p.omaUser = out.replace("<scope>", "User")
if policy.get("class") in ("Both", "Machine"):
p.omaDevice = out.replace("<scope>", "Device")
if hasattr(policy, "elements"):
for element in policy.elements.getchildren():
v = PolicyOutput.PolicyValue(element.get('id'), element.tag, element.get('valueName') or element.get('id'), element.get('required'))
p.values.append(v)
if element.tag in ('enum'):
for item in element.getchildren():
val = item.value.getchildren()[0]
v.valEnumOptions.append(str(val.get("value") if val.get("value") is not None else val.text))
v.value = v.valEnumOptions[0]
if element.tag in ('boolean'):
v.valEnumOptions.append('true')
v.valEnumOptions.append('false')
v.value = v.valEnumOptions[0]
p.print()
class PolicyOutput:
class PolicyValue:
def __init__(self, valID = '', valType = 'text', valName = None, required = None, value = ''):
self.valID = valID
self.valType = valType
self.valName = valName or valID
self.value = value
self.valEnumOptions = []
self.required = required
def __init__(self, name = ""):
self.polName = name
self.omaDevice = 'No device policy'
self.omaUser = 'No user policy'
self.values = []
templatestring = "./<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>"
def print(self):
print(polTemplate.format(**self.__dict__))
dataTagList = []
for value in self.values:
dataTagList.append(dataTagTemplate.format(**value.__dict__))
out = {}
out.update({'valEnumOptionsOut': '(%s)'% '|'.join(value.valEnumOptions) if len(value.valEnumOptions) else ''})
out.update({'requiredOut': 'required' if value.required else 'optional'})
out.update({'dataTag': dataTagList[-1]})
out.update(value.__dict__)
print(valTemplate.format(**out))
dataTagList.insert(0, '') if len(dataTagList) else dataTagList
print(recordTemplate.format(**{'dataTags': '\n'.join(dataTagList)}))
polTemplate = """
===============================
Policy: {polName}
===============================
{omaUser}
{omaDevice}
Enabled value: <enabled/>
Disabled value: <disabled/>
""".rstrip()
polTemplate = """
===============================
Policy: {polName}
===============================
{omaUser}
{omaDevice}
(<enabled/>|<disabled/>)
""".rstrip()
dataTagTemplate = """
<data id='{valID}' value='{value}'/>
""".strip()
valTemplate = """
-------------------------------
{valName} ({requiredOut})
Value type: {valType} {valEnumOptionsOut}
{dataTag}
""".strip()
valTemplate = """
-------------------------------
Key Name: {valName}
Key ID: {valID}
Value type: {valType} {valEnumOptionsOut}
""".strip()
recordTemplate = """
----------- Example -----------
<enabled/>{dataTags}
""".strip()
if __name__ == "__main__":
run()
| [
"import sys, os\nfrom lxml import objectify\n\nusage = \"\"\"\nUsage is:\npy admx2oma.py <your.admx> <ADMX-OMA-URI>\n<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file\n Take care, the OMA-URI is case sensitive.\n<your.admx> : The admx file you ingested\n\n\"\"\"\n\ndef run():\n if len(sys.argv) < 3:\n print(usage)\n sys.exit()\n\n admxFile = sys.argv[1]\n admxOMA_URI = sys.argv[2]\n\n if not os.path.exists(admxFile):\n print(\"file not found: \" + admxFile)\n sys.exit()\n\n templatestring = \"./<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>\"\n catHierarchie = {}\n try:\n (AppName, SettingType, id_or_admxName) = admxOMA_URI.partition(\"/ADMXInstall/\")[2].split(\"/\")\n except BaseException:\n print()\n print(\"ERROR: Bad OMA-URI: \" + admxOMA_URI)\n print(usage)\n sys.exit()\n\n admx = objectify.parse(admxFile)\n r = admx.getroot()\n for category in r.categories.getchildren():\n ref = category.parentCategory.get('ref') if hasattr(category, \"parentCategory\") else \":\"\n catHierarchie[category.get(\"name\")] = ref\n\n for policy in r.policies.findall(\"policy\", namespaces=r.nsmap):\n out = templatestring\n out = out.replace(\"<policy>\", policy.get(\"name\"))\n\n hierarchie = policy.parentCategory.get(\"ref\")\n nextCat = catHierarchie[policy.parentCategory.get(\"ref\")]\n while nextCat.find(\":\") == -1:\n hierarchie = '~'.join((nextCat, hierarchie))\n if not nextCat in catHierarchie:\n break\n nextCat = catHierarchie[nextCat]\n hierarchie = '~'.join((AppName, SettingType, hierarchie))\n \n out = out.replace(\"<area>\", hierarchie)\n\n p = PolicyOutput(policy.get(\"name\"))\n \n if policy.get(\"class\") in (\"Both\", \"User\"):\n p.omaUser = out.replace(\"<scope>\", \"User\")\n if policy.get(\"class\") in (\"Both\", \"Machine\"):\n p.omaDevice = out.replace(\"<scope>\", \"Device\")\n \n if hasattr(policy, \"elements\"):\n for element in policy.elements.getchildren():\n v = PolicyOutput.PolicyValue(element.get('id'), element.tag, element.get('valueName') or element.get('id'), element.get('required'))\n p.values.append(v)\n if element.tag in ('enum'):\n for item in element.getchildren():\n val = item.value.getchildren()[0]\n v.valEnumOptions.append(str(val.get(\"value\") if val.get(\"value\") is not None else val.text))\n v.value = v.valEnumOptions[0]\n if element.tag in ('boolean'):\n v.valEnumOptions.append('true')\n v.valEnumOptions.append('false')\n v.value = v.valEnumOptions[0]\n p.print()\n\n\nclass PolicyOutput:\n class PolicyValue:\n def __init__(self, valID = '', valType = 'text', valName = None, required = None, value = ''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n \n def __init__(self, name = \"\"):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = \"./<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>\"\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)'% '|'.join(value.valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n \n\npolTemplate = \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\nEnabled value: <enabled/>\nDisabled value: <disabled/>\n\"\"\".rstrip()\n\npolTemplate = \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\n(<enabled/>|<disabled/>)\n\"\"\".rstrip()\n\ndataTagTemplate = \"\"\"\n<data id='{valID}' value='{value}'/>\n\"\"\".strip()\n\nvalTemplate = \"\"\"\n-------------------------------\n{valName} ({requiredOut})\nValue type: {valType} {valEnumOptionsOut}\n{dataTag}\n\"\"\".strip()\n\nvalTemplate = \"\"\"\n-------------------------------\nKey Name: {valName}\nKey ID: {valID}\nValue type: {valType} {valEnumOptionsOut}\n\"\"\".strip()\n\nrecordTemplate = \"\"\"\n----------- Example -----------\n<enabled/>{dataTags}\n\"\"\".strip()\n\nif __name__ == \"__main__\":\n run()\n\n\n\n\n\n",
"import sys, os\nfrom lxml import objectify\nusage = \"\"\"\nUsage is:\npy admx2oma.py <your.admx> <ADMX-OMA-URI>\n<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file\n Take care, the OMA-URI is case sensitive.\n<your.admx> : The admx file you ingested\n\n\"\"\"\n\n\ndef run():\n if len(sys.argv) < 3:\n print(usage)\n sys.exit()\n admxFile = sys.argv[1]\n admxOMA_URI = sys.argv[2]\n if not os.path.exists(admxFile):\n print('file not found: ' + admxFile)\n sys.exit()\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n catHierarchie = {}\n try:\n AppName, SettingType, id_or_admxName = admxOMA_URI.partition(\n '/ADMXInstall/')[2].split('/')\n except BaseException:\n print()\n print('ERROR: Bad OMA-URI: ' + admxOMA_URI)\n print(usage)\n sys.exit()\n admx = objectify.parse(admxFile)\n r = admx.getroot()\n for category in r.categories.getchildren():\n ref = category.parentCategory.get('ref') if hasattr(category,\n 'parentCategory') else ':'\n catHierarchie[category.get('name')] = ref\n for policy in r.policies.findall('policy', namespaces=r.nsmap):\n out = templatestring\n out = out.replace('<policy>', policy.get('name'))\n hierarchie = policy.parentCategory.get('ref')\n nextCat = catHierarchie[policy.parentCategory.get('ref')]\n while nextCat.find(':') == -1:\n hierarchie = '~'.join((nextCat, hierarchie))\n if not nextCat in catHierarchie:\n break\n nextCat = catHierarchie[nextCat]\n hierarchie = '~'.join((AppName, SettingType, hierarchie))\n out = out.replace('<area>', hierarchie)\n p = PolicyOutput(policy.get('name'))\n if policy.get('class') in ('Both', 'User'):\n p.omaUser = out.replace('<scope>', 'User')\n if policy.get('class') in ('Both', 'Machine'):\n p.omaDevice = out.replace('<scope>', 'Device')\n if hasattr(policy, 'elements'):\n for element in policy.elements.getchildren():\n v = PolicyOutput.PolicyValue(element.get('id'), element.tag,\n element.get('valueName') or element.get('id'), element.\n get('required'))\n p.values.append(v)\n if element.tag in 'enum':\n for item in element.getchildren():\n val = item.value.getchildren()[0]\n v.valEnumOptions.append(str(val.get('value') if val\n .get('value') is not None else val.text))\n v.value = v.valEnumOptions[0]\n if element.tag in 'boolean':\n v.valEnumOptions.append('true')\n v.valEnumOptions.append('false')\n v.value = v.valEnumOptions[0]\n p.print()\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n\n def __init__(self, name=''):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\npolTemplate = (\n \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\nEnabled value: <enabled/>\nDisabled value: <disabled/>\n\"\"\"\n .rstrip())\npolTemplate = (\n \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\n(<enabled/>|<disabled/>)\n\"\"\"\n .rstrip())\ndataTagTemplate = \"\"\"\n<data id='{valID}' value='{value}'/>\n\"\"\".strip()\nvalTemplate = (\n \"\"\"\n-------------------------------\n{valName} ({requiredOut})\nValue type: {valType} {valEnumOptionsOut}\n{dataTag}\n\"\"\"\n .strip())\nvalTemplate = (\n \"\"\"\n-------------------------------\nKey Name: {valName}\nKey ID: {valID}\nValue type: {valType} {valEnumOptionsOut}\n\"\"\"\n .strip())\nrecordTemplate = (\"\"\"\n----------- Example -----------\n<enabled/>{dataTags}\n\"\"\"\n .strip())\nif __name__ == '__main__':\n run()\n",
"<import token>\nusage = \"\"\"\nUsage is:\npy admx2oma.py <your.admx> <ADMX-OMA-URI>\n<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file\n Take care, the OMA-URI is case sensitive.\n<your.admx> : The admx file you ingested\n\n\"\"\"\n\n\ndef run():\n if len(sys.argv) < 3:\n print(usage)\n sys.exit()\n admxFile = sys.argv[1]\n admxOMA_URI = sys.argv[2]\n if not os.path.exists(admxFile):\n print('file not found: ' + admxFile)\n sys.exit()\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n catHierarchie = {}\n try:\n AppName, SettingType, id_or_admxName = admxOMA_URI.partition(\n '/ADMXInstall/')[2].split('/')\n except BaseException:\n print()\n print('ERROR: Bad OMA-URI: ' + admxOMA_URI)\n print(usage)\n sys.exit()\n admx = objectify.parse(admxFile)\n r = admx.getroot()\n for category in r.categories.getchildren():\n ref = category.parentCategory.get('ref') if hasattr(category,\n 'parentCategory') else ':'\n catHierarchie[category.get('name')] = ref\n for policy in r.policies.findall('policy', namespaces=r.nsmap):\n out = templatestring\n out = out.replace('<policy>', policy.get('name'))\n hierarchie = policy.parentCategory.get('ref')\n nextCat = catHierarchie[policy.parentCategory.get('ref')]\n while nextCat.find(':') == -1:\n hierarchie = '~'.join((nextCat, hierarchie))\n if not nextCat in catHierarchie:\n break\n nextCat = catHierarchie[nextCat]\n hierarchie = '~'.join((AppName, SettingType, hierarchie))\n out = out.replace('<area>', hierarchie)\n p = PolicyOutput(policy.get('name'))\n if policy.get('class') in ('Both', 'User'):\n p.omaUser = out.replace('<scope>', 'User')\n if policy.get('class') in ('Both', 'Machine'):\n p.omaDevice = out.replace('<scope>', 'Device')\n if hasattr(policy, 'elements'):\n for element in policy.elements.getchildren():\n v = PolicyOutput.PolicyValue(element.get('id'), element.tag,\n element.get('valueName') or element.get('id'), element.\n get('required'))\n p.values.append(v)\n if element.tag in 'enum':\n for item in element.getchildren():\n val = item.value.getchildren()[0]\n v.valEnumOptions.append(str(val.get('value') if val\n .get('value') is not None else val.text))\n v.value = v.valEnumOptions[0]\n if element.tag in 'boolean':\n v.valEnumOptions.append('true')\n v.valEnumOptions.append('false')\n v.value = v.valEnumOptions[0]\n p.print()\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n\n def __init__(self, name=''):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\npolTemplate = (\n \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\nEnabled value: <enabled/>\nDisabled value: <disabled/>\n\"\"\"\n .rstrip())\npolTemplate = (\n \"\"\"\n===============================\nPolicy: {polName}\n===============================\n{omaUser}\n{omaDevice}\n(<enabled/>|<disabled/>)\n\"\"\"\n .rstrip())\ndataTagTemplate = \"\"\"\n<data id='{valID}' value='{value}'/>\n\"\"\".strip()\nvalTemplate = (\n \"\"\"\n-------------------------------\n{valName} ({requiredOut})\nValue type: {valType} {valEnumOptionsOut}\n{dataTag}\n\"\"\"\n .strip())\nvalTemplate = (\n \"\"\"\n-------------------------------\nKey Name: {valName}\nKey ID: {valID}\nValue type: {valType} {valEnumOptionsOut}\n\"\"\"\n .strip())\nrecordTemplate = (\"\"\"\n----------- Example -----------\n<enabled/>{dataTags}\n\"\"\"\n .strip())\nif __name__ == '__main__':\n run()\n",
"<import token>\n<assignment token>\n\n\ndef run():\n if len(sys.argv) < 3:\n print(usage)\n sys.exit()\n admxFile = sys.argv[1]\n admxOMA_URI = sys.argv[2]\n if not os.path.exists(admxFile):\n print('file not found: ' + admxFile)\n sys.exit()\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n catHierarchie = {}\n try:\n AppName, SettingType, id_or_admxName = admxOMA_URI.partition(\n '/ADMXInstall/')[2].split('/')\n except BaseException:\n print()\n print('ERROR: Bad OMA-URI: ' + admxOMA_URI)\n print(usage)\n sys.exit()\n admx = objectify.parse(admxFile)\n r = admx.getroot()\n for category in r.categories.getchildren():\n ref = category.parentCategory.get('ref') if hasattr(category,\n 'parentCategory') else ':'\n catHierarchie[category.get('name')] = ref\n for policy in r.policies.findall('policy', namespaces=r.nsmap):\n out = templatestring\n out = out.replace('<policy>', policy.get('name'))\n hierarchie = policy.parentCategory.get('ref')\n nextCat = catHierarchie[policy.parentCategory.get('ref')]\n while nextCat.find(':') == -1:\n hierarchie = '~'.join((nextCat, hierarchie))\n if not nextCat in catHierarchie:\n break\n nextCat = catHierarchie[nextCat]\n hierarchie = '~'.join((AppName, SettingType, hierarchie))\n out = out.replace('<area>', hierarchie)\n p = PolicyOutput(policy.get('name'))\n if policy.get('class') in ('Both', 'User'):\n p.omaUser = out.replace('<scope>', 'User')\n if policy.get('class') in ('Both', 'Machine'):\n p.omaDevice = out.replace('<scope>', 'Device')\n if hasattr(policy, 'elements'):\n for element in policy.elements.getchildren():\n v = PolicyOutput.PolicyValue(element.get('id'), element.tag,\n element.get('valueName') or element.get('id'), element.\n get('required'))\n p.values.append(v)\n if element.tag in 'enum':\n for item in element.getchildren():\n val = item.value.getchildren()[0]\n v.valEnumOptions.append(str(val.get('value') if val\n .get('value') is not None else val.text))\n v.value = v.valEnumOptions[0]\n if element.tag in 'boolean':\n v.valEnumOptions.append('true')\n v.valEnumOptions.append('false')\n v.value = v.valEnumOptions[0]\n p.print()\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n\n def __init__(self, name=''):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\n<assignment token>\nif __name__ == '__main__':\n run()\n",
"<import token>\n<assignment token>\n\n\ndef run():\n if len(sys.argv) < 3:\n print(usage)\n sys.exit()\n admxFile = sys.argv[1]\n admxOMA_URI = sys.argv[2]\n if not os.path.exists(admxFile):\n print('file not found: ' + admxFile)\n sys.exit()\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n catHierarchie = {}\n try:\n AppName, SettingType, id_or_admxName = admxOMA_URI.partition(\n '/ADMXInstall/')[2].split('/')\n except BaseException:\n print()\n print('ERROR: Bad OMA-URI: ' + admxOMA_URI)\n print(usage)\n sys.exit()\n admx = objectify.parse(admxFile)\n r = admx.getroot()\n for category in r.categories.getchildren():\n ref = category.parentCategory.get('ref') if hasattr(category,\n 'parentCategory') else ':'\n catHierarchie[category.get('name')] = ref\n for policy in r.policies.findall('policy', namespaces=r.nsmap):\n out = templatestring\n out = out.replace('<policy>', policy.get('name'))\n hierarchie = policy.parentCategory.get('ref')\n nextCat = catHierarchie[policy.parentCategory.get('ref')]\n while nextCat.find(':') == -1:\n hierarchie = '~'.join((nextCat, hierarchie))\n if not nextCat in catHierarchie:\n break\n nextCat = catHierarchie[nextCat]\n hierarchie = '~'.join((AppName, SettingType, hierarchie))\n out = out.replace('<area>', hierarchie)\n p = PolicyOutput(policy.get('name'))\n if policy.get('class') in ('Both', 'User'):\n p.omaUser = out.replace('<scope>', 'User')\n if policy.get('class') in ('Both', 'Machine'):\n p.omaDevice = out.replace('<scope>', 'Device')\n if hasattr(policy, 'elements'):\n for element in policy.elements.getchildren():\n v = PolicyOutput.PolicyValue(element.get('id'), element.tag,\n element.get('valueName') or element.get('id'), element.\n get('required'))\n p.values.append(v)\n if element.tag in 'enum':\n for item in element.getchildren():\n val = item.value.getchildren()[0]\n v.valEnumOptions.append(str(val.get('value') if val\n .get('value') is not None else val.text))\n v.value = v.valEnumOptions[0]\n if element.tag in 'boolean':\n v.valEnumOptions.append('true')\n v.valEnumOptions.append('false')\n v.value = v.valEnumOptions[0]\n p.print()\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n\n def __init__(self, name=''):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n\n def __init__(self, name=''):\n self.polName = name\n self.omaDevice = 'No device policy'\n self.omaUser = 'No user policy'\n self.values = []\n templatestring = './<scope>/Vendor/MSFT/Policy/Config/<area>/<policy>'\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n <function token>\n\n def print(self):\n print(polTemplate.format(**self.__dict__))\n dataTagList = []\n for value in self.values:\n dataTagList.append(dataTagTemplate.format(**value.__dict__))\n out = {}\n out.update({'valEnumOptionsOut': '(%s)' % '|'.join(value.\n valEnumOptions) if len(value.valEnumOptions) else ''})\n out.update({'requiredOut': 'required' if value.required else\n 'optional'})\n out.update({'dataTag': dataTagList[-1]})\n out.update(value.__dict__)\n print(valTemplate.format(**out))\n dataTagList.insert(0, '') if len(dataTagList) else dataTagList\n print(recordTemplate.format(**{'dataTags': '\\n'.join(dataTagList)}))\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\nclass PolicyOutput:\n\n\n class PolicyValue:\n\n def __init__(self, valID='', valType='text', valName=None, required\n =None, value=''):\n self.valID = valID\n self.valType = valType\n self.valName = valName or valID\n self.value = value\n self.valEnumOptions = []\n self.required = required\n <function token>\n <function token>\n\n\n<assignment token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n<class token>\n<assignment token>\n<code token>\n"
] | false |
99,938 | 082d740bfa2ed2fcb4fba11d6f269a715abd1354 | # -*- coding: utf-8 -*-
import sys
import os
import re
import time
"""
Python Nagios extensions
"""
__author__ = "Drew Stinnett"
__copyright__ = "Copyright 2008, Drew Stinnett"
__credits__ = ["Drew Stinnett", "Pall Sigurdsson"]
__license__ = "GPL"
__version__ = "0.4"
__maintainer__ = "Pall Sigurdsson"
__email__ = "palli@opensource.is"
__status__ = "Development"
def debug(text):
debug = True
if debug: print text
class config:
"""
Parse and write nagios config files
"""
def __init__(self, cfg_file = "/etc/nagios/nagios.cfg"):
self.cfg_file = cfg_file # Main configuration file
self.cfg_files = [] # List of other configuration files
self.data = {} # dict of every known object definition
self.errors = [] # List of ParserErrors
self.item_list = None
self.item_cache = None
self.maincfg_values = [] # The contents of main nagios.cfg
self.resource_values = [] # The contents of any resource_files
# If nagios.cfg is not set, lets do some minor autodiscover.
if self.cfg_file is None:
possible_files = ('/etc/nagios/nagios.cfg','/etc/nagios3/nagios.cfg','/usr/local/nagios/nagios.cfg','/nagios/etc/nagios/nagios.cfg')
for file in possible_files:
if os.path.isfile(file):
self.cfg_file = file
## This is a pure listof all the key/values in the config files. It
## shouldn't be useful until the items in it are parsed through with the proper
## 'use' relationships
self.pre_object_list = []
self.post_object_list = []
self.object_type_keys = {
'hostgroup':'hostgroup_name',
'hostextinfo':'host_name',
'host':'host_name',
'service':'name',
'servicegroup':'servicegroup_name',
'contact':'contact_name',
'contactgroup':'contactgroup_name',
'timeperiod':'timeperiod_name',
'command':'command_name',
#'service':['host_name','description'],
}
if not os.path.isfile(self.cfg_file):
raise ParserError("Main Nagios config not found. %s does not exist\n" % self.cfg_file)
def _has_template(self, target):
"""
Determine if an item has a template associated with it
"""
if target.has_key('use'):
return True
else:
return None
def _get_hostgroup(self, hostgroup_name):
for hostgroup in self.data['all_hostgroup']:
if hostgroup.has_key('hostgroup_name') and hostgroup['hostgroup_name'] == hostgroup_name:
return hostgroup
return None
def _get_key(self, object_type, user_key = None):
"""
Return the correct 'key' for an item. This is mainly a helper method
for other methods in this class. It is used to shorten code repitition
"""
if not user_key and not self.object_type_keys.has_key(object_type):
raise ParserError("Unknown key for object type: %s\n" % object_type)
## Use a default key
if not user_key:
user_key = self.object_type_keys[object_type]
return user_key
def _get_item(self, item_name, item_type):
"""
Return an item from a list
"""
# create local cache for performance optimizations. TODO: Rewrite functions that call this function
if not self.item_list:
self.item_list = self.pre_object_list
self.item_cache = {}
for item in self.item_list:
if not item.has_key('name'):
continue
name = item['name']
tmp_item_type = (item['meta']['object_type'])
if not self.item_cache.has_key( tmp_item_type ):
self.item_cache[tmp_item_type] = {}
self.item_cache[tmp_item_type][name] = item
try:
return self.item_cache[item_type][item_name]
except:
return None
if self.item_cache[item_type].has_key(item_name):
return self.item_cache[item_type][item_name]
return None
for test_item in self.item_list:
## Skip items without a name
if not test_item.has_key('name'):
continue
## Make sure there isn't an infinite loop going on
try:
if (test_item['name'] == item_name) and (test_item['meta']['object_type'] == item_type):
return test_item
except:
raise ParserError("Loop detected, exiting", item=test_item)
## If we make it this far, it means there is no matching item
return None
def _apply_template(self, original_item):
"""
Apply all attributes of item named parent_name to "original_item".
"""
# TODO: Performance optimization. Don't recursively call _apply_template on hosts we have already
# applied templates to. This needs more work.
if not original_item.has_key('use'):
return original_item
object_type = original_item['meta']['object_type']
# Performance tweak, if item has been parsed. Lets not do it again
if original_item.has_key('name') and self.item_apply_cache[object_type].has_key( original_item['name'] ):
return self.item_apply_cache[object_type][ original_item['name'] ]
# End of performance tweak
parent_names = original_item['use'].split(',')
parent_items = []
for parent_name in parent_names:
parent_item = self._get_item( parent_name, object_type )
if parent_item == None:
error_string = "error in %s\n" % (original_item['meta']['filename'])
error_string = error_string + "Can not find any %s named %s\n" % (object_type,parent_name)
error_string = error_string + self.print_conf(original_item)
self.errors.append( ParserError(error_string,item=original_item) )
continue
# Parent item probably has use flags on its own. So lets apply to parent first
parent_item = self._apply_template( parent_item )
parent_items.append( parent_item )
for parent_item in parent_items:
for k,v in parent_item.iteritems():
if k == 'use':
continue
if k == 'register':
continue
if k == 'meta':
continue
if k == 'name':
continue
if not original_item['meta']['inherited_attributes'].has_key(k):
original_item['meta']['inherited_attributes'][k] = v
if not original_item.has_key(k):
original_item[k] = v
original_item['meta']['template_fields'].append(k)
if original_item.has_key('name'):
self.item_apply_cache[object_type][ original_item['name'] ] = original_item
return original_item
def _get_items_in_file(self, filename):
"""
Return all items in the given file
"""
return_list = []
for k in self.data.keys():
for item in self[k]:
if item['meta']['filename'] == filename:
return_list.append(item)
return return_list
def get_new_item(self, object_type, filename):
''' Returns an empty item with all necessary metadata '''
current = {}
current['meta'] = {}
current['meta']['object_type'] = object_type
current['meta']['filename'] = filename
current['meta']['template_fields'] = []
current['meta']['needs_commit'] = None
current['meta']['delete_me'] = None
current['meta']['defined_attributes'] = {}
current['meta']['inherited_attributes'] = {}
current['meta']['raw_definition'] = ""
return current
def _load_file(self, filename):
## Set globals (This is stolen from the perl module)
append = ""
type = None
current = None
in_definition = {}
tmp_buffer = []
for line in open(filename, 'rb').readlines():
## Cleanup and line skips
line = line.strip()
if line == "":
continue
if line[0] == "#" or line[0] == ';':
continue
# append saved text to the current line
if append:
append += ' '
line = append + line;
append = None
# end of object definition
if line.find("}") != -1:
in_definition = None
append = line.split("}", 1)[1]
tmp_buffer.append( line )
try:
current['meta']['raw_definition'] = '\n'.join( tmp_buffer )
except:
print "hmm?"
self.pre_object_list.append(current)
## Destroy the Nagios Object
current = None
continue
# beginning of object definition
boo_re = re.compile("define\s+(\w+)\s*{?(.*)$")
m = boo_re.search(line)
if m:
tmp_buffer = [line]
object_type = m.groups()[0]
current = self.get_new_item(object_type, filename)
if in_definition:
raise ParserError("Error: Unexpected start of object definition in file '%s' on line $line_no. Make sure you close preceding objects before starting a new one.\n" % filename)
## Start off an object
in_definition = True
append = m.groups()[1]
continue
else:
tmp_buffer.append( ' ' + line )
## save whatever's left in the buffer for the next iteration
if not in_definition:
append = line
continue
## this is an attribute inside an object definition
if in_definition:
#(key, value) = line.split(None, 1)
tmp = line.split(None, 1)
if len(tmp) > 1:
(key, value) = tmp
else:
key = tmp[0]
value = ""
## Strip out in-line comments
if value.find(";") != -1:
value = value.split(";", 1)[0]
## Clean info
key = key.strip()
value = value.strip()
## Rename some old values that may be in the configuration
## This can probably be removed in the future to increase performance
if (current['meta']['object_type'] == 'service') and key == 'description':
key = 'service_description'
current[key] = value
current['meta']['defined_attributes'][key] = value
## Something is wrong in the config
else:
raise ParserError("Error: Unexpected token in file '%s'" % filename)
## Something is wrong in the config
if in_definition:
raise ParserError("Error: Unexpected EOF in file '%s'" % filename)
def _locate_item(self, item):
"""
This is a helper function for anyone who wishes to modify objects. It takes "item", locates the
file which is configured in, and locates exactly the lines which contain that definition.
Returns tuple:
(everything_before, object_definition, everything_after, filename)
everything_before(string) - Every line in filename before object was defined
everything_after(string) - Every line in "filename" after object was defined
object_definition - exact configuration of the object as it appears in "filename"
filename - file in which the object was written to
Raises:
ValueError if object was not found in "filename"
"""
if item['meta'].has_key("filename"):
filename = item['meta']['filename']
else:
raise ValueError("item does not have a filename")
file = open(filename)
object_has_been_found = False
everything_before = [] # Every line before our object definition
everything_after = [] # Every line after our object definition
object_definition = [] # List of every line of our object definition
i_am_within_definition = False
for line in file.readlines():
if object_has_been_found:
'If we have found an object, lets just spool to the end'
everything_after.append( line )
continue
tmp = line.split(None, 1)
if len(tmp) == 0:
'empty line'
keyword = ''
rest = ''
if len(tmp) == 1:
'single word on the line'
keyword = tmp[0]
rest = ''
if len(tmp) > 1:
keyword,rest = tmp[0],tmp[1]
keyword = keyword.strip()
# If we reach a define statement, we log every line to a special buffer
# When define closes, we parse the object and see if it is the object we
# want to modify
if keyword == 'define':
current_object_type = rest.split(None,1)[0]
current_object_type = current_object_type.strip(';')
current_object_type = current_object_type.strip('{')
current_object_type = current_object_type.strip()
tmp_buffer = []
i_am_within_definition = True
if i_am_within_definition == True:
tmp_buffer.append( line )
else:
everything_before.append( line )
if len(keyword) > 0 and keyword[0] == '}':
i_am_within_definition = False
current_definition = self.get_new_item(object_type=current_object_type, filename=filename)
for i in tmp_buffer:
i = i.strip()
tmp = i.split(None, 1)
if len(tmp) == 1:
k = tmp[0]
v = ''
elif len(tmp) > 1:
k,v = tmp[0],tmp[1]
v = v.split(';',1)[0]
v = v.strip()
else: continue # skip empty lines
if k.startswith('#'): continue
if k.startswith(';'): continue
if k.startswith('define'): continue
if k.startswith('}'): continue
current_definition[k] = v
current_definition = self._apply_template(current_definition)
# Compare objects
if self.compareObjects( item, current_definition ) == True:
'This is the object i am looking for'
object_has_been_found = True
object_definition = tmp_buffer
else:
'This is not the item you are looking for'
everything_before += tmp_buffer
if object_has_been_found:
return (everything_before, object_definition, everything_after, filename)
else:
raise ValueError("We could not find object in %s\n%s" % (filename,item))
def _modify_object(self, item, field_name=None, new_value=None, new_field_name=None, new_item=None, make_comments=True):
'''
Helper function for object_* functions. Locates "item" and changes the line which contains field_name.
If new_value and new_field_name are both None, the attribute is removed.
Arguments:
item(dict) -- The item to be modified
field_name(str) -- The field_name to modify (if any)
new_field_name(str) -- If set, field_name will be renamed
new_value(str) -- If set the value of field_name will be changed
new_item(str) -- If set, whole object will be replaced with this string
make_comments -- If set, put pynag-branded comments where changes have been made
Returns:
True on success
Raises:
ValueError if object or field_name is not found
IOError is save is unsuccessful.
'''
if field_name is None and new_item is None:
raise ValueError("either field_name or new_item must be set")
everything_before,object_definition, everything_after, filename = self._locate_item(item)
if new_item is not None:
'We have instruction on how to write new object, so we dont need to parse it'
change = True
object_definition = [new_item]
else:
change = None
for i in range( len(object_definition)):
tmp = object_definition[i].split(None, 1)
if len(tmp) == 0: continue
if len(tmp) == 1: value = ''
if len(tmp) == 2: value = tmp[1]
k = tmp[0].strip()
if k == field_name:
'Attribute was found, lets change this line'
if not new_field_name and not new_value:
'We take it that we are supposed to remove this attribute'
change = object_definition.pop(i)
break
elif new_field_name:
'Field name has changed'
k = new_field_name
if new_value:
'value has changed '
value = new_value
# Here we do the actual change
change = "\t%-30s%s\n" % (k, value)
object_definition[i] = change
break
if not change:
'Attribute was not found. Lets add it'
change = "\t%-30s%s\n" % (field_name, new_value)
object_definition.insert(i,change)
# Lets put a banner in front of our item
if make_comments:
comment = '# Edited by PyNag on %s\n' % time.ctime()
if len(everything_before) > 0:
last_line_before = everything_before[-1]
if last_line_before.startswith('# Edited by PyNag on'):
everything_before.pop() # remove this line
object_definition.insert(0, comment )
# Here we overwrite the config-file, hoping not to ruin anything
buffer = "%s%s%s" % (''.join(everything_before), ''.join(object_definition), ''.join(everything_after))
file = open(filename,'w')
file.write( buffer )
file.close()
return True
def item_rewrite(self, item, str_new_item):
"""
Completely rewrites item with string provided.
Arguments:
item -- Item that is to be rewritten
str_new_item -- str representation of the new item
Examples:
item_rewrite( item, "define service {\n name example-service \n register 0 \n }\n" )
Returns:
True on success
Raises:
ValueError if object is not found
IOError if save fails
"""
return self._modify_object(item=item, new_item=str_new_item)
def item_remove(self, item):
"""
Completely rewrites item with string provided.
Arguments:
item -- Item that is to be rewritten
str_new_item -- str representation of the new item
Examples:
item_rewrite( item, "define service {\n name example-service \n register 0 \n }\n" )
Returns:
True on success
Raises:
ValueError if object is not found
IOError if save fails
"""
return self._modify_object(item=item, new_item="")
def item_edit_field(self, item, field_name, new_value):
"""
Modifies one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
Example usage:
edit_object( item, field_name="host_name", new_value="examplehost.example.com")
Returns:
True on success
Raises:
ValueError if object is not found
IOError if save fails
"""
return self._modify_object(item, field_name=field_name, new_value=new_value)
def item_remove_field(self, item, field_name):
"""
Removes one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
Example usage:
item_remove_field( item, field_name="contactgroups" )
Returns:
True on success
Raises:
ValueError if object is not found
IOError if save fails
"""
return self._modify_object(item=item, field_name=field_name, new_value=None, new_field_name=None)
def item_rename_field(self, item, old_field_name, new_field_name):
"""
Renames a field of a (currently existing) item. Changes are immediate (i.e. there is no commit).
Example usage:
item_rename_field(item, old_field_name="normal_check_interval", new_field_name="check_interval")
Returns:
True on success
Raises:
ValueError if object is not found
IOError if save fails
"""
return self._modify_object(item=item, field_name=old_field_name, new_field_name=new_field_name)
def item_add(self, item, filename):
"""
Adds a new object to a specified config file
Arguments:
item -- Item to be created
filename -- Filename that we are supposed to write to
Returns:
True on success
Raises:
IOError on failed save
"""
if not 'meta' in item:
item['meta'] = {}
item['meta']['filename'] = filename
# Create directory if it does not already exist
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
os.makedirs(dirname)
buffer = self.print_conf( item )
file = open(filename,'a')
file.write( buffer )
file.close()
return True
def edit_object(self,item, field_name, new_value):
"""
Modifies a (currently existing) item. Changes are immediate (i.e. there is no commit)
Example Usage: edit_object( item, field_name="host_name", new_value="examplehost.example.com")
THIS FUNCTION IS DEPRECATED. USE item_edit_field() instead
"""
return self.item_edit_field(item=item, field_name=field_name, new_value=new_value)
def compareObjects(self, item1, item2):
"""
Compares two items. Returns true if they are equal"
"""
keys1 = item1.keys()
keys2 = item2.keys()
keys1.sort()
keys2.sort()
result=True
if keys1 != keys2:
return False
for key in keys1:
if key == 'meta': continue
key1 = item1[key]
key2 = item2[key]
# For our purpose, 30 is equal to 30.000
if key == 'check_interval':
key1 = int(float(key1))
key2 = int(float(key2))
if key1 != key2:
result = False
if result == False: return False
return True
def edit_service(self, target_host, service_description, field_name, new_value):
"""
Edit a service's attributes
"""
original_object = self.get_service(target_host, service_description)
if original_object == None:
raise ParserError("Service not found")
return config.edit_object( original_object, field_name, new_value)
def _get_list(self, object, key):
"""
Return a comma list from an item
Example:
_get_list(Foo_object, host_name)
define service {
service_description Foo
host_name larry,curly,moe
}
return
['larry','curly','moe']
"""
if type(object) != type({}):
raise ParserError("%s is not a dictionary\n" % object)
# return []
if not object.has_key(key):
return []
return_list = []
if object[key].find(",") != -1:
for name in object[key].split(","):
return_list.append(name)
else:
return_list.append(object[key])
## Alphabetize
return_list.sort()
return return_list
def delete_object(self, object_type, object_name, user_key = None):
"""
Delete object from configuration files.
"""
object_key = self._get_key(object_type,user_key)
target_object = None
k = 'all_%s' % object_type
for item in self.data[k]:
if not item.has_key(object_key):
continue
## If the object matches, mark it for deletion
if item[object_key] == object_name:
self.data[k].remove(item)
item['meta']['delete_me'] = True
item['meta']['needs_commit'] = True
self.data[k].append(item)
## Commit the delete
self.commit()
return True
## Only make it here if the object isn't found
return None
def delete_service(self, service_description, host_name):
"""
Delete service from configuration
"""
for item in self.data['all_service']:
if (item['service_description'] == service_description) and (host_name in self._get_active_hosts(item)):
self.data['all_service'].remove(item)
item['meta']['delete_me'] = True
item['meta']['needs_commit'] = True
self.data['all_service'].append(item)
return True
def delete_host(self, object_name, user_key = None):
"""
Delete a host
"""
return self.delete_object('host',object_name, user_key = user_key)
def delete_hostgroup(self, object_name, user_key = None):
"""
Delete a hostgroup
"""
return self.delete_object('hostgroup',object_name, user_key = user_key)
def get_object(self, object_type, object_name, user_key = None):
"""
Return a complete object dictionary
"""
object_key = self._get_key(object_type,user_key)
target_object = None
#print object_type
for item in self.data['all_%s' % object_type]:
## Skip items without the specified key
if not item.has_key(object_key):
continue
if item[object_key] == object_name:
target_object = item
## This is for multi-key items
return target_object
def get_host(self, object_name, user_key = None):
"""
Return a host object
"""
return self.get_object('host',object_name, user_key = user_key)
def get_servicegroup(self, object_name, user_key = None):
"""
Return a Servicegroup object
"""
return self.get_object('servicegroup',object_name, user_key = user_key)
def get_contact(self, object_name, user_key = None):
"""
Return a Contact object
"""
return self.get_object('contact',object_name, user_key = user_key)
def get_contactgroup(self, object_name, user_key = None):
"""
Return a Contactgroup object
"""
return self.get_object('contactgroup',object_name, user_key = user_key)
def get_timeperiod(self, object_name, user_key = None):
"""
Return a Timeperiod object
"""
return self.get_object('timeperiod',object_name, user_key = user_key)
def get_command(self, object_name, user_key = None):
"""
Return a Command object
"""
return self.get_object('command',object_name, user_key = user_key)
def get_hostgroup(self, object_name, user_key = None):
"""
Return a hostgroup object
"""
return self.get_object('hostgroup',object_name, user_key = user_key)
def get_service(self, target_host, service_description):
"""
Return a service object. This has to be seperate from the 'get_object'
method, because it requires more than one key
"""
for item in self.data['all_service']:
## Skip service with no service_description
if not item.has_key('service_description'):
continue
## Skip non-matching services
if item['service_description'] != service_description:
continue
if target_host in self._get_active_hosts(item):
return item
return None
def _append_use(self, source_item, name):
"""
Append any unused values from 'name' to the dict 'item'
"""
## Remove the 'use' key
if source_item.has_key('use'):
del source_item['use']
for possible_item in self.pre_object_list:
if possible_item.has_key('name'):
## Start appending to the item
for k,v in possible_item.iteritems():
try:
if k == 'use':
source_item = self._append_use(source_item, v)
except:
raise ParserError("Recursion error on %s %s" % (source_item, v) )
## Only add the item if it doesn't already exist
if not source_item.has_key(k):
source_item[k] = v
return source_item
def _post_parse(self):
self.item_list = None
self.item_apply_cache = {} # This is performance tweak used by _apply_template
for raw_item in self.pre_object_list:
# Performance tweak, make sure hashmap exists for this object_type
object_type = raw_item['meta']['object_type']
if not self.item_apply_cache.has_key( object_type ):
self.item_apply_cache[ object_type ] = {}
# Tweak ends
if raw_item.has_key('use'):
raw_item = self._apply_template( raw_item )
self.post_object_list.append(raw_item)
## Add the items to the class lists.
for list_item in self.post_object_list:
type_list_name = "all_%s" % list_item['meta']['object_type']
if not self.data.has_key(type_list_name):
self.data[type_list_name] = []
self.data[type_list_name].append(list_item)
def commit(self):
"""
Write any changes that have been made to it's appropriate file
"""
## Loops through ALL items
for k in self.data.keys():
for item in self[k]:
## If the object needs committing, commit it!
if item['meta']['needs_commit']:
## Create file contents as an empty string
file_contents = ""
## find any other items that may share this config file
extra_items = self._get_items_in_file(item['meta']['filename'])
if len(extra_items) > 0:
for commit_item in extra_items:
## Ignore files that are already set to be deleted:w
if commit_item['meta']['delete_me']:
continue
## Make sure we aren't adding this thing twice
if item != commit_item:
file_contents += self.print_conf(commit_item)
## This is the actual item that needs commiting
if not item['meta']['delete_me']:
file_contents += self.print_conf(item)
## Write the file
f = open(item['meta']['filename'], 'w')
f.write(file_contents)
f.close()
## Recreate the item entry without the commit flag
self.data[k].remove(item)
item['meta']['needs_commit'] = None
self.data[k].append(item)
def flag_all_commit(self):
"""
Flag every item in the configuration to be committed
This should probably only be used for debugging purposes
"""
for k in self.data.keys():
index = 0
for item in self[k]:
self.data[k][index]['meta']['needs_commit'] = True
index += 1
def print_conf(self, item):
"""
Return a string that can be used in a configuration file
"""
output = ""
## Header, to go on all files
output += "# Configuration file %s\n" % item['meta']['filename']
output += "# Edited by PyNag on %s\n" % time.ctime()
## Some hostgroup information
if item['meta'].has_key('hostgroup_list'):
output += "# Hostgroups: %s\n" % ",".join(item['meta']['hostgroup_list'])
## Some hostgroup information
if item['meta'].has_key('service_list'):
output += "# Services: %s\n" % ",".join(item['meta']['service_list'])
## Some hostgroup information
if item['meta'].has_key('service_members'):
output += "# Service Members: %s\n" % ",".join(item['meta']['service_members'])
if len(item['meta']['template_fields']) != 0:
output += "# Values from templates:\n"
for k in item['meta']['template_fields']:
output += "#\t %-30s %-30s\n" % (k, item[k])
output += "\n"
output += "define %s {\n" % item['meta']['object_type']
for k, v in item.iteritems():
if k != 'meta':
if k not in item['meta']['template_fields']:
output += "\t %-30s %-30s\n" % (k,v)
output += "}\n\n"
return output
def _load_static_file(self, filename):
"""Load a general config file (like nagios.cfg) that has key=value config file format. Ignore comments
Returns: a [ (key,value), (key,value) ] list
"""
result = []
for line in open(filename).readlines():
## Strip out new line characters
line = line.strip()
## Skip blank lines
if line == "":
continue
## Skip comments
if line[0] == "#" or line[0] == ';':
continue
key, value = line.split("=", 1)
result.append( (key, value) )
return result
def needs_reload(self):
"Returns True if Nagios service needs reload of cfg files"
new_timestamps = self.get_timestamps()
for k,v in self.maincfg_values:
if k == 'lock_file': lockfile = v
if not os.path.isfile(lockfile): return False
lockfile = new_timestamps.pop(lockfile)
for k,v in new_timestamps.items():
if int(v) > lockfile: return True
return False
def needs_reparse(self):
"Returns True if any Nagios configuration file has changed since last parse()"
new_timestamps = self.get_timestamps()
if len(new_timestamps) != len( self.timestamps ):
return True
for k,v in new_timestamps.items():
if self.timestamps[k] != v:
return True
return False
def parse(self):
"""
Load the nagios.cfg file and parse it up
"""
self.maincfg_values = self._load_static_file(self.cfg_file)
self.cfg_files = self.get_cfg_files()
self.resource_values = self.get_resources()
self.timestamps = self.get_timestamps()
## This loads everything into
for cfg_file in self.cfg_files:
self._load_file(cfg_file)
self._post_parse()
def get_timestamps(self):
"Returns a hash map of all nagios related files and their timestamps"
files = {}
files[self.cfg_file] = None
for k,v in self.maincfg_values:
if k == 'resource_file' or k == 'lock_file':
files[v] = None
for i in self.get_cfg_files():
files[i] = None
# Now lets lets get timestamp of every file
for k,v in files.items():
if not os.path.isfile(k): continue
files[k] = os.stat(k).st_mtime
return files
def get_resources(self):
"Returns a list of every private resources from nagios.cfg"
resources = []
for config_object,config_value in self.maincfg_values:
if config_object == 'resource_file' and os.path.isfile(config_value):
resources += self._load_static_file(config_value)
return resources
def extended_parse(self):
"""
This parse is used after the initial parse() command is run. It is
only needed if you want extended meta information about hosts or other objects
"""
## Do the initial parsing
self.parse()
## First, cycle through the hosts, and append hostgroup information
index = 0
for host in self.data['all_host']:
if host.has_key('register') and host['register'] == '0': continue
if not host.has_key('host_name'): continue
if not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):
self.data['all_host'][index]['meta']['hostgroup_list'] = []
## Append any hostgroups that are directly listed in the host definition
if host.has_key('hostgroups'):
for hostgroup_name in self._get_list(host, 'hostgroups'):
if not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):
self.data['all_host'][index]['meta']['hostgroup_list'] = []
if hostgroup_name not in self.data['all_host'][index]['meta']['hostgroup_list']:
self.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup_name)
## Append any services which reference this host
service_list = []
for service in self.data['all_service']:
if service.has_key('register') and service['register'] == '0': continue
if not service.has_key('service_description'): continue
if host['host_name'] in self._get_active_hosts(service):
service_list.append(service['service_description'])
self.data['all_host'][index]['meta']['service_list'] = service_list
## Increment count
index += 1
## Loop through all hostgroups, appending them to their respective hosts
for hostgroup in self.data['all_hostgroup']:
for member in self._get_list(hostgroup,'members'):
index = 0
for host in self.data['all_host']:
if not host.has_key('host_name'): continue
## Skip members that do not match
if host['host_name'] == member:
## Create the meta var if it doesn' exist
if not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):
self.data['all_host'][index]['meta']['hostgroup_list'] = []
if hostgroup['hostgroup_name'] not in self.data['all_host'][index]['meta']['hostgroup_list']:
self.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup['hostgroup_name'])
## Increment count
index += 1
## Expand service membership
index = 0
for service in self.data['all_service']:
service_members = []
## Find a list of hosts to negate from the final list
self.data['all_service'][index]['meta']['service_members'] = self._get_active_hosts(service)
## Increment count
index += 1
def _get_active_hosts(self, object):
"""
Given an object, return a list of active hosts. This will exclude hosts that ar negated with a "!"
"""
## First, generate the negation list
negate_hosts = []
## Hostgroups
if object.has_key("hostgroup_name"):
for hostgroup_name in self._get_list(object, 'hostgroup_name'):
if hostgroup_name[0] == "!":
hostgroup_obj = self.get_hostgroup(hostgroup_name[1:])
negate_hosts.extend(self._get_list(hostgroup_obj,'members'))
## Host Names
if object.has_key("host_name"):
for host_name in self._get_list(object, 'host_name'):
if host_name[0] == "!":
negate_hosts.append(host_name[1:])
## Now get hosts that are actually listed
active_hosts = []
## Hostgroups
if object.has_key("hostgroup_name"):
for hostgroup_name in self._get_list(object, 'hostgroup_name'):
if hostgroup_name[0] != "!":
active_hosts.extend(self._get_list(self.get_hostgroup(hostgroup_name),'members'))
## Host Names
if object.has_key("host_name"):
for host_name in self._get_list(object, 'host_name'):
if host_name[0] != "!":
active_hosts.append(host_name)
## Combine the lists
return_hosts = []
for active_host in active_hosts:
if active_host not in negate_hosts:
return_hosts.append(active_host)
return return_hosts
def get_cfg_files(self):
"""
Return a list of all cfg files used in this configuration
Example:
print get_cfg_files()
['/etc/nagios/hosts/host1.cfg','/etc/nagios/hosts/host2.cfg',...]
"""
cfg_files = []
for config_object, config_value in self.maincfg_values:
## Add cfg_file objects to cfg file list
if config_object == "cfg_file" and os.path.isfile(config_value):
cfg_files.append(config_value)
## Parse all files in a cfg directory
if config_object == "cfg_dir":
directories = []
raw_file_list = []
directories.append( config_value )
# Walk through every subdirectory and add to our list
while len(directories) > 0:
current_directory = directories.pop(0)
# Nagios doesnt care if cfg_dir exists or not, so why should we ?
if not os.path.isdir( current_directory ): continue
list = os.listdir(current_directory)
for item in list:
# Append full path to file
item = "%s" % (os.path.join(current_directory, item.strip() ) )
if os.path.islink( item ):
item = os.readlink( item )
if os.path.isdir(item):
directories.append( item )
if raw_file_list.count( item ) < 1:
raw_file_list.append( item )
for raw_file in raw_file_list:
if raw_file.endswith('.cfg'):
if os.path.exists(raw_file):
'Nagios doesnt care if cfg_file exists or not, so we will not throws errors'
cfg_files.append(raw_file)
return cfg_files
def get_object_types(self):
''' Returns a list of all discovered object types '''
return map(lambda x: re.sub("all_","", x), self.data.keys())
def cleanup(self):
"""
This cleans up dead configuration files
"""
for filename in self.cfg_files:
if os.path.isfile(filename):
size = os.stat(filename)[6]
if size == 0:
os.remove(filename)
return True
def __setitem__(self, key, item):
self.data[key] = item
def __getitem__(self, key):
return self.data[key]
class status:
def __init__(self, filename = "/var/log/nagios/status.dat"):
if not os.path.isfile(filename):
raise ParserError("status.dat file %s not found." % filename)
self.filename = filename
self.data = {}
def parse(self):
## Set globals (This is stolen from the perl module)
type = None
for line in open(self.filename, 'rb').readlines():
## Cleanup and line skips
line = line.strip()
if line == "":
continue
if line[0] == "#" or line[0] == ';':
continue
if line.find("{") != -1:
status = {}
status['meta'] = {}
status['meta']['type'] = line.split("{")[0].strip()
continue
if line.find("}") != -1:
if not self.data.has_key(status['meta']['type']):
self.data[status['meta']['type']] = []
self.data[status['meta']['type']].append(status)
continue
(key, value) = line.split("=", 1)
status[key] = value
def __setitem__(self, key, item):
self.data[key] = item
def __getitem__(self, key):
return self.data[key]
class ParserError(Exception):
def __init__(self, message, item=None):
self.message = message
self.item = item
def __str__(self):
return repr(self.message)
if __name__ == '__main__':
c=config('/etc/nagios/nagios.cfg')
c.parse()
print c.get_object_types()
print c.needs_reload()
#for i in c.data['all_host']:
# print i['meta']
| [
"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport re\nimport time\n\n\"\"\"\nPython Nagios extensions\n\"\"\"\n\n__author__ = \"Drew Stinnett\"\n__copyright__ = \"Copyright 2008, Drew Stinnett\"\n__credits__ = [\"Drew Stinnett\", \"Pall Sigurdsson\"]\n__license__ = \"GPL\"\n__version__ = \"0.4\"\n__maintainer__ = \"Pall Sigurdsson\"\n__email__ = \"palli@opensource.is\"\n__status__ = \"Development\"\n\ndef debug(text):\n\tdebug = True\n\tif debug: print text\n\n\nclass config:\n\t\"\"\"\n\tParse and write nagios config files\n\t\"\"\"\n\tdef __init__(self, cfg_file = \"/etc/nagios/nagios.cfg\"):\n\n\t\tself.cfg_file = cfg_file # Main configuration file\n\t\tself.cfg_files = [] # List of other configuration files\n\t\tself.data = {} # dict of every known object definition\n\t\tself.errors = [] # List of ParserErrors\n\t\tself.item_list = None\n\t\tself.item_cache = None\n\t\tself.maincfg_values = [] # The contents of main nagios.cfg\n\t\tself.resource_values = [] # The contents of any resource_files\n\t\t\n\t\t# If nagios.cfg is not set, lets do some minor autodiscover.\n\t\tif self.cfg_file is None:\n\t\t\tpossible_files = ('/etc/nagios/nagios.cfg','/etc/nagios3/nagios.cfg','/usr/local/nagios/nagios.cfg','/nagios/etc/nagios/nagios.cfg')\n\t\t\tfor file in possible_files:\n\t\t\t\tif os.path.isfile(file):\n\t\t\t\t\tself.cfg_file = file\n\t\t## This is a pure listof all the key/values in the config files. It\n\t\t## shouldn't be useful until the items in it are parsed through with the proper\n\t\t## 'use' relationships\n\t\tself.pre_object_list = []\n\t\tself.post_object_list = []\n\t\tself.object_type_keys = {\n\t\t\t'hostgroup':'hostgroup_name',\n\t\t\t'hostextinfo':'host_name',\n\t\t\t'host':'host_name',\n\t\t\t'service':'name',\n\t\t\t'servicegroup':'servicegroup_name',\n\t\t\t'contact':'contact_name',\n\t\t\t'contactgroup':'contactgroup_name',\n\t\t\t'timeperiod':'timeperiod_name',\n\t\t\t'command':'command_name',\n\t\t\t#'service':['host_name','description'],\n\t\t}\n\n\t\tif not os.path.isfile(self.cfg_file):\n\t\t\traise ParserError(\"Main Nagios config not found. %s does not exist\\n\" % self.cfg_file)\n\n\tdef _has_template(self, target):\n\t\t\"\"\"\n\t\tDetermine if an item has a template associated with it\n\t\t\"\"\"\n\t\tif target.has_key('use'):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn None\n\n\tdef _get_hostgroup(self, hostgroup_name):\n\t\tfor hostgroup in self.data['all_hostgroup']:\n\t\t\tif hostgroup.has_key('hostgroup_name') and hostgroup['hostgroup_name'] == hostgroup_name:\n\t\t\t\treturn hostgroup\n\t\treturn None\n\tdef _get_key(self, object_type, user_key = None):\n\t\t\"\"\"\n\t\tReturn the correct 'key' for an item. This is mainly a helper method\n\t\tfor other methods in this class. It is used to shorten code repitition\n\t\t\"\"\"\n\t\tif not user_key and not self.object_type_keys.has_key(object_type):\n\t\t\traise ParserError(\"Unknown key for object type: %s\\n\" % object_type)\n\n\t\t## Use a default key\n\t\tif not user_key:\n\t\t\tuser_key = self.object_type_keys[object_type]\n\n\t\treturn user_key\n\t\n\tdef _get_item(self, item_name, item_type):\n\t\t\"\"\" \n \t\tReturn an item from a list\n \t\t\"\"\"\n\t\t# create local cache for performance optimizations. TODO: Rewrite functions that call this function\n\t\tif not self.item_list:\n\t\t\tself.item_list = self.pre_object_list\n\t\t\tself.item_cache = {}\n\t\t\tfor item in self.item_list:\n\t\t\t\tif not item.has_key('name'):\n\t\t\t\t\tcontinue\n\t\t\t\tname = item['name']\n\t\t\t\ttmp_item_type = (item['meta']['object_type'])\n\t\t\t\tif not self.item_cache.has_key( tmp_item_type ):\n\t\t\t\t\tself.item_cache[tmp_item_type] = {}\n\t\t\t\tself.item_cache[tmp_item_type][name] = item\n\t\ttry:\n\t\t\treturn self.item_cache[item_type][item_name]\n\t\texcept:\n\t\t\treturn None\n\t\tif self.item_cache[item_type].has_key(item_name):\n\t\t\treturn self.item_cache[item_type][item_name]\n\t\treturn None\n\t\tfor test_item in self.item_list: \n\t\t\t## Skip items without a name\n\t\t\tif not test_item.has_key('name'):\n\t\t\t\tcontinue\n\n\t\t\t## Make sure there isn't an infinite loop going on\n\t\t\ttry:\n\t\t\t\tif (test_item['name'] == item_name) and (test_item['meta']['object_type'] == item_type):\n\t\t\t\t\treturn test_item\n\t\t\texcept:\n\t\t\t\traise ParserError(\"Loop detected, exiting\", item=test_item)\n\t\t\t\n\t\t## If we make it this far, it means there is no matching item\n\t\treturn None\n\n\tdef _apply_template(self, original_item):\n\t\t\"\"\"\n\t\tApply all attributes of item named parent_name to \"original_item\".\n\t\t\"\"\"\n\t\t# TODO: Performance optimization. Don't recursively call _apply_template on hosts we have already\n\t\t# applied templates to. This needs more work.\n\t\tif not original_item.has_key('use'):\n\t\t\treturn original_item\n\t\tobject_type = original_item['meta']['object_type']\n\t\t# Performance tweak, if item has been parsed. Lets not do it again\n\t\tif original_item.has_key('name') and self.item_apply_cache[object_type].has_key( original_item['name'] ):\n\t\t\treturn self.item_apply_cache[object_type][ original_item['name'] ]\n\t\t# End of performance tweak\n\t\tparent_names = original_item['use'].split(',')\n\t\tparent_items = []\n\t\tfor parent_name in parent_names:\n\t\t\tparent_item = self._get_item( parent_name, object_type )\n\t\t\tif parent_item == None: \n\t\t\t\terror_string = \"error in %s\\n\" % (original_item['meta']['filename'])\n\t\t\t\terror_string = error_string + \"Can not find any %s named %s\\n\" % (object_type,parent_name)\n\t\t\t\terror_string = error_string + self.print_conf(original_item)\n\t\t\t\tself.errors.append( ParserError(error_string,item=original_item) )\n\t\t\t\tcontinue\n\t\t\t# Parent item probably has use flags on its own. So lets apply to parent first\n\t\t\tparent_item = self._apply_template( parent_item )\n\t\t\tparent_items.append( parent_item )\n\t\tfor parent_item in parent_items:\n\t\t\tfor k,v in parent_item.iteritems():\n\t\t\t\tif k == 'use':\n\t\t\t\t\tcontinue\n\t\t\t\tif k == 'register':\n\t\t\t\t\tcontinue\n\t\t\t\tif k == 'meta':\n\t\t\t\t\tcontinue\n\t\t\t\tif k == 'name':\n\t\t\t\t\tcontinue\n\t\t\t\tif not original_item['meta']['inherited_attributes'].has_key(k):\n\t\t\t\t\toriginal_item['meta']['inherited_attributes'][k] = v\n\t\t\t\tif not original_item.has_key(k):\n\t\t\t\t\toriginal_item[k] = v\n\t\t\t\t\toriginal_item['meta']['template_fields'].append(k)\n\t\tif original_item.has_key('name'):\n\t\t\tself.item_apply_cache[object_type][ original_item['name'] ] = original_item\n\t\treturn original_item\n\n\t\t\t\n\tdef _get_items_in_file(self, filename):\n\t\t\"\"\"\n\t\tReturn all items in the given file\n\t\t\"\"\"\n\t\treturn_list = []\n\t\t\t\t\n\t\tfor k in self.data.keys():\n\t\t\tfor item in self[k]:\n\t\t\t\tif item['meta']['filename'] == filename:\n\t\t\t\t\treturn_list.append(item)\n\t\treturn return_list\n\tdef get_new_item(self, object_type, filename):\n\t\t''' Returns an empty item with all necessary metadata '''\n\t\tcurrent = {}\n\t\tcurrent['meta'] = {}\n\t\tcurrent['meta']['object_type'] = object_type\n\t\tcurrent['meta']['filename'] = filename\n\t\tcurrent['meta']['template_fields'] = []\n\t\tcurrent['meta']['needs_commit'] = None\n\t\tcurrent['meta']['delete_me'] = None\n\t\tcurrent['meta']['defined_attributes'] = {}\n\t\tcurrent['meta']['inherited_attributes'] = {}\n\t\tcurrent['meta']['raw_definition'] = \"\"\n\t\treturn current\n\n\tdef _load_file(self, filename):\n\t\t## Set globals (This is stolen from the perl module)\n\t\tappend = \"\"\n\t\ttype = None\n\t\tcurrent = None\n\t\tin_definition = {}\n\t\ttmp_buffer = []\n\n\t\tfor line in open(filename, 'rb').readlines():\n\n\t\t\t## Cleanup and line skips\n\t\t\tline = line.strip()\n\t\t\tif line == \"\":\n\t\t\t\tcontinue\n\t\t\tif line[0] == \"#\" or line[0] == ';':\n\t\t\t\tcontinue\n\n\t\t\t# append saved text to the current line\n\t\t\tif append:\n\t\t\t\tappend += ' '\n\t\t\t\tline = append + line;\n\t\t\t\tappend = None\n\n\t\t\t# end of object definition\n\t\t\tif line.find(\"}\") != -1:\n\n\t\t\t\tin_definition = None\n\t\t\t\tappend = line.split(\"}\", 1)[1]\n\t\t\t\t\n\t\t\t\ttmp_buffer.append( line )\n\t\t\t\ttry:\n\t\t\t\t\tcurrent['meta']['raw_definition'] = '\\n'.join( tmp_buffer )\n\t\t\t\texcept:\n\t\t\t\t\tprint \"hmm?\"\n\t\t\t\tself.pre_object_list.append(current)\n\n\n\t\t\t\t## Destroy the Nagios Object\n\t\t\t\tcurrent = None\n\t\t\t\tcontinue\n\n\t\t\t# beginning of object definition\n\t\t\tboo_re = re.compile(\"define\\s+(\\w+)\\s*{?(.*)$\")\n\t\t\tm = boo_re.search(line)\n\t\t\tif m:\n\t\t\t\ttmp_buffer = [line]\n\t\t\t\tobject_type = m.groups()[0]\n\t\t\t\tcurrent = self.get_new_item(object_type, filename)\n\n\n\t\t\t\tif in_definition:\n\t\t\t\t\traise ParserError(\"Error: Unexpected start of object definition in file '%s' on line $line_no. Make sure you close preceding objects before starting a new one.\\n\" % filename)\n\n\t\t\t\t## Start off an object\n\t\t\t\tin_definition = True\n\t\t\t\tappend = m.groups()[1]\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\ttmp_buffer.append( ' ' + line )\n\n\t\t\t## save whatever's left in the buffer for the next iteration\n\t\t\tif not in_definition:\n\t\t\t\tappend = line\n\t\t\t\tcontinue\n\n\t\t\t## this is an attribute inside an object definition\n\t\t\tif in_definition:\n\t\t\t\t#(key, value) = line.split(None, 1)\n\t\t\t\ttmp = line.split(None, 1)\n\t\t\t\tif len(tmp) > 1:\n\t\t\t\t\t(key, value) = tmp\n\t\t\t\telse:\n\t\t\t\t\tkey = tmp[0]\n\t\t\t\t\tvalue = \"\"\n\n\t\t\t\t## Strip out in-line comments\n\t\t\t\tif value.find(\";\") != -1:\n\t\t\t\t\tvalue = value.split(\";\", 1)[0]\n\n\t\t\t\t## Clean info\n\t\t\t\tkey = key.strip()\n\t\t\t\tvalue = value.strip()\n\n\t\t\t\t## Rename some old values that may be in the configuration\n\t\t\t\t## This can probably be removed in the future to increase performance\n\t\t\t\tif (current['meta']['object_type'] == 'service') and key == 'description':\n\t\t\t\t\tkey = 'service_description'\n\n\t\t\t\tcurrent[key] = value\n\t\t\t\tcurrent['meta']['defined_attributes'][key] = value\n\t\t\t## Something is wrong in the config\n\t\t\telse:\n\t\t\t\traise ParserError(\"Error: Unexpected token in file '%s'\" % filename)\n\n\t\t## Something is wrong in the config\n\t\tif in_definition:\n\t\t\traise ParserError(\"Error: Unexpected EOF in file '%s'\" % filename)\n\n\tdef _locate_item(self, item):\n\t\t\"\"\"\n\t\tThis is a helper function for anyone who wishes to modify objects. It takes \"item\", locates the\n\t\tfile which is configured in, and locates exactly the lines which contain that definition.\n\t\t\n\t\tReturns tuple:\n\t\t\t(everything_before, object_definition, everything_after, filename)\n\t\t\teverything_before(string) - Every line in filename before object was defined\n\t\t\teverything_after(string) - Every line in \"filename\" after object was defined\n\t\t\tobject_definition - exact configuration of the object as it appears in \"filename\"\n\t\t\tfilename - file in which the object was written to\n\t\tRaises:\n\t\t\tValueError if object was not found in \"filename\"\n\t\t\"\"\"\n\t\tif item['meta'].has_key(\"filename\"):\n\t\t\tfilename = item['meta']['filename']\n\t\telse:\n\t\t\traise ValueError(\"item does not have a filename\")\n\t\tfile = open(filename)\n\t\tobject_has_been_found = False\n\t\teverything_before = [] # Every line before our object definition\n\t\teverything_after = [] # Every line after our object definition\n\t\tobject_definition = [] # List of every line of our object definition\n\t\ti_am_within_definition = False\n\t\tfor line in file.readlines():\n\t\t\tif object_has_been_found:\n\t\t\t\t'If we have found an object, lets just spool to the end'\n\t\t\t\teverything_after.append( line )\n\t\t\t\tcontinue\n\t\t\ttmp = line.split(None, 1)\n\t\t\tif len(tmp) == 0:\n\t\t\t\t'empty line'\n\t\t\t\tkeyword = ''\n\t\t\t\trest = ''\n\t\t\tif len(tmp) == 1:\n\t\t\t\t'single word on the line'\n\t\t\t\tkeyword = tmp[0]\n\t\t\t\trest = ''\n\t\t\tif len(tmp) > 1:\n\t\t\t\tkeyword,rest = tmp[0],tmp[1]\n\t\t\tkeyword = keyword.strip()\n\t\t\t# If we reach a define statement, we log every line to a special buffer\n\t\t\t# When define closes, we parse the object and see if it is the object we\n\t\t\t# want to modify\n\t\t\tif keyword == 'define':\n\t\t\t\tcurrent_object_type = rest.split(None,1)[0]\n\t\t\t\tcurrent_object_type = current_object_type.strip(';')\n\t\t\t\tcurrent_object_type = current_object_type.strip('{')\n\t\t\t\tcurrent_object_type = current_object_type.strip()\n\t\t\t\ttmp_buffer = []\n\t\t\t\ti_am_within_definition = True\n\t\t\tif i_am_within_definition == True:\n\t\t\t\ttmp_buffer.append( line )\n\t\t\telse:\n\t\t\t\teverything_before.append( line )\n\t\t\tif len(keyword) > 0 and keyword[0] == '}':\n\t\t\t\ti_am_within_definition = False\n\t\t\t\t\n\t\t\t\tcurrent_definition = self.get_new_item(object_type=current_object_type, filename=filename)\n\t\t\t\tfor i in tmp_buffer:\n\t\t\t\t\ti = i.strip()\n\t\t\t\t\ttmp = i.split(None, 1)\n\t\t\t\t\tif len(tmp) == 1:\n\t\t\t\t\t\tk = tmp[0]\n\t\t\t\t\t\tv = ''\n\t\t\t\t\telif len(tmp) > 1:\n\t\t\t\t\t\tk,v = tmp[0],tmp[1]\n\t\t\t\t\t\tv = v.split(';',1)[0]\n\t\t\t\t\t\tv = v.strip()\n\t\t\t\t\telse: continue # skip empty lines\n\t\t\t\t\t\n\t\t\t\t\tif k.startswith('#'): continue\n\t\t\t\t\tif k.startswith(';'): continue\n\t\t\t\t\tif k.startswith('define'): continue\n\t\t\t\t\tif k.startswith('}'): continue\n\t\t\t\t\t\n\t\t\t\t\tcurrent_definition[k] = v\n\t\t\t\t\tcurrent_definition = self._apply_template(current_definition)\n\t\t\t\t# Compare objects\n\t\t\t\tif self.compareObjects( item, current_definition ) == True:\n\t\t\t\t\t'This is the object i am looking for'\n\t\t\t\t\tobject_has_been_found = True\n\t\t\t\t\tobject_definition = tmp_buffer\n\t\t\t\telse:\n\t\t\t\t\t'This is not the item you are looking for'\n\t\t\t\t\teverything_before += tmp_buffer\n\t\tif object_has_been_found:\n\t\t\treturn (everything_before, object_definition, everything_after, filename)\n\t\telse:\n\t\t\traise ValueError(\"We could not find object in %s\\n%s\" % (filename,item))\n\tdef _modify_object(self, item, field_name=None, new_value=None, new_field_name=None, new_item=None, make_comments=True):\n\t\t'''\n\t\tHelper function for object_* functions. Locates \"item\" and changes the line which contains field_name.\n\t\tIf new_value and new_field_name are both None, the attribute is removed.\n\t\t\n\t\tArguments:\n\t\t\titem(dict) -- The item to be modified\n\t\t\tfield_name(str) -- The field_name to modify (if any)\n\t\t\tnew_field_name(str) -- If set, field_name will be renamed\n\t\t\tnew_value(str) -- If set the value of field_name will be changed\n\t\t\tnew_item(str) -- If set, whole object will be replaced with this string\n\t\t\tmake_comments -- If set, put pynag-branded comments where changes have been made\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object or field_name is not found\n\t\t\tIOError is save is unsuccessful.\n\t\t'''\n\t\tif field_name is None and new_item is None:\n\t\t\traise ValueError(\"either field_name or new_item must be set\")\n\t\teverything_before,object_definition, everything_after, filename = self._locate_item(item)\n\t\tif new_item is not None:\n\t\t\t'We have instruction on how to write new object, so we dont need to parse it'\n\t\t\tchange = True\n\t\t\tobject_definition = [new_item]\n\t\telse:\n\t\t\tchange = None\n\t\t\tfor i in range( len(object_definition)):\n\t\t\t\ttmp = object_definition[i].split(None, 1)\n\t\t\t\tif len(tmp) == 0: continue\n\t\t\t\tif len(tmp) == 1: value = ''\n\t\t\t\tif len(tmp) == 2: value = tmp[1]\n\t\t\t\tk = tmp[0].strip()\n\t\t\t\tif k == field_name:\n\t\t\t\t\t'Attribute was found, lets change this line'\n\t\t\t\t\tif not new_field_name and not new_value:\n\t\t\t\t\t\t'We take it that we are supposed to remove this attribute'\n\t\t\t\t\t\tchange = object_definition.pop(i)\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif new_field_name:\n\t\t\t\t\t\t'Field name has changed'\n\t\t\t\t\t\tk = new_field_name\n\t\t\t\t\tif new_value:\n\t\t\t\t\t\t'value has changed '\n\t\t\t\t\t\tvalue = new_value\n\t\t\t\t\t# Here we do the actual change\t\n\t\t\t\t\tchange = \"\\t%-30s%s\\n\" % (k, value)\n\t\t\t\t\tobject_definition[i] = change\n\t\t\t\t\tbreak\n\t\t\tif not change:\n\t\t\t\t\t'Attribute was not found. Lets add it'\n\t\t\t\t\tchange = \"\\t%-30s%s\\n\" % (field_name, new_value)\n\t\t\t\t\tobject_definition.insert(i,change)\n\t\t# Lets put a banner in front of our item\n\t\tif make_comments:\n\t\t\tcomment = '# Edited by PyNag on %s\\n' % time.ctime()\n\t\t\tif len(everything_before) > 0:\n\t\t\t\tlast_line_before = everything_before[-1]\n\t\t\t\tif last_line_before.startswith('# Edited by PyNag on'):\n\t\t\t\t\teverything_before.pop() # remove this line\n\t\t\tobject_definition.insert(0, comment )\n\t\t# Here we overwrite the config-file, hoping not to ruin anything\n\t\tbuffer = \"%s%s%s\" % (''.join(everything_before), ''.join(object_definition), ''.join(everything_after))\n\t\tfile = open(filename,'w')\n\t\tfile.write( buffer )\n\t\tfile.close()\n\t\treturn True\t\t\n\tdef item_rewrite(self, item, str_new_item):\n\t\t\"\"\"\n\t\tCompletely rewrites item with string provided.\n\t\t\n\t\tArguments:\n\t\t\titem -- Item that is to be rewritten\n\t\t\tstr_new_item -- str representation of the new item\n\t\tExamples:\n\t\t\titem_rewrite( item, \"define service {\\n name example-service \\n register 0 \\n }\\n\" )\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object is not found\n\t\t\tIOError if save fails\n\t\t\"\"\"\n\t\treturn self._modify_object(item=item, new_item=str_new_item)\n\tdef item_remove(self, item):\n\t\t\"\"\"\n\t\tCompletely rewrites item with string provided.\n\t\t\n\t\tArguments:\n\t\t\titem -- Item that is to be rewritten\n\t\t\tstr_new_item -- str representation of the new item\n\t\tExamples:\n\t\t\titem_rewrite( item, \"define service {\\n name example-service \\n register 0 \\n }\\n\" )\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object is not found\n\t\t\tIOError if save fails\n\t\t\"\"\"\n\t\treturn self._modify_object(item=item, new_item=\"\")\n\n\tdef item_edit_field(self, item, field_name, new_value):\n\t\t\"\"\"\n\t\tModifies one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)\n\t\t\n\t\tExample usage:\n\t\t\tedit_object( item, field_name=\"host_name\", new_value=\"examplehost.example.com\")\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object is not found\n\t\t\tIOError if save fails\n\t\t\"\"\"\n\t\treturn self._modify_object(item, field_name=field_name, new_value=new_value)\n\t\n\tdef item_remove_field(self, item, field_name):\n\t\t\"\"\"\n\t\tRemoves one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)\n\t\t\n\t\tExample usage:\n\t\t\titem_remove_field( item, field_name=\"contactgroups\" )\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object is not found\n\t\t\tIOError if save fails\n\t\t\"\"\"\n\t\treturn self._modify_object(item=item, field_name=field_name, new_value=None, new_field_name=None)\n\t\n\tdef item_rename_field(self, item, old_field_name, new_field_name):\n\t\t\"\"\"\n\t\tRenames a field of a (currently existing) item. Changes are immediate (i.e. there is no commit).\n\t\t\n\t\tExample usage:\n\t\t\titem_rename_field(item, old_field_name=\"normal_check_interval\", new_field_name=\"check_interval\")\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tValueError if object is not found\n\t\t\tIOError if save fails\n\t\t\"\"\"\n\t\treturn self._modify_object(item=item, field_name=old_field_name, new_field_name=new_field_name)\n\tdef item_add(self, item, filename):\n\t\t\"\"\"\n\t\tAdds a new object to a specified config file\n\t\t\n\t\tArguments:\n\t\t\titem -- Item to be created\n\t\t\tfilename -- Filename that we are supposed to write to\n\t\tReturns:\n\t\t\tTrue on success\n\t\tRaises:\n\t\t\tIOError on failed save\n\t\t\"\"\"\n\t\tif not 'meta' in item:\n\t\t\titem['meta'] = {}\n\t\titem['meta']['filename'] = filename\n\t\t\n\t\t# Create directory if it does not already exist\t\t\t\t\n\t\tdirname = os.path.dirname(filename)\n\t\tif not os.path.isdir(dirname):\n\t\t\tos.makedirs(dirname)\n\n\t\tbuffer = self.print_conf( item )\n\t\tfile = open(filename,'a')\n\t\tfile.write( buffer )\n\t\tfile.close()\n\t\treturn True\t\t\n\t\t\t\n\tdef edit_object(self,item, field_name, new_value):\n\t\t\"\"\"\n\t\tModifies a (currently existing) item. Changes are immediate (i.e. there is no commit)\n\t\t\n\t\tExample Usage: edit_object( item, field_name=\"host_name\", new_value=\"examplehost.example.com\")\n\t\t\n\t\tTHIS FUNCTION IS DEPRECATED. USE item_edit_field() instead\n\t\t\"\"\"\n\t\treturn self.item_edit_field(item=item, field_name=field_name, new_value=new_value)\n\n\tdef compareObjects(self, item1, item2):\n\t\t\"\"\"\n\t\tCompares two items. Returns true if they are equal\"\n\t\t\"\"\"\n\t\tkeys1 = item1.keys()\n\t\tkeys2 = item2.keys()\n\t\tkeys1.sort()\n\t\tkeys2.sort()\n\t\tresult=True\n\t\tif keys1 != keys2:\n\t\t\treturn False\n\t\tfor key in keys1:\n\t\t\tif key == 'meta': continue\n\t\t\tkey1 = item1[key]\n\t\t\tkey2 = item2[key]\n\t\t\t# For our purpose, 30 is equal to 30.000\n\t\t\tif key == 'check_interval':\n\t\t\t\tkey1 = int(float(key1))\n\t\t\t\tkey2 = int(float(key2))\n\t\t\tif key1 != key2:\n\t\t\t\tresult = False\n\t\tif result == False: return False\n\t\treturn True\n\tdef edit_service(self, target_host, service_description, field_name, new_value):\n\t\t\"\"\"\n\t\tEdit a service's attributes\n\t\t\"\"\"\n\n\t\toriginal_object = self.get_service(target_host, service_description)\n\t\tif original_object == None:\n\t\t\traise ParserError(\"Service not found\")\n\t\treturn config.edit_object( original_object, field_name, new_value)\n\n\n\tdef _get_list(self, object, key):\n\t\t\"\"\"\n\t\tReturn a comma list from an item\n\n\t\tExample:\n\n\t\t_get_list(Foo_object, host_name)\n\t\tdefine service {\n\t\t\tservice_description Foo\n\t\t\thost_name\t\t\tlarry,curly,moe\n\t\t}\n\n\t\treturn\n\t\t['larry','curly','moe']\n\t\t\"\"\"\n\t\tif type(object) != type({}):\n\t\t\traise ParserError(\"%s is not a dictionary\\n\" % object)\n\t\t\t# return []\n\t\tif not object.has_key(key):\n\t\t\treturn []\n\n\t\treturn_list = []\n\n\t\tif object[key].find(\",\") != -1:\n\t\t\tfor name in object[key].split(\",\"):\n\t\t\t\treturn_list.append(name)\n\t\telse:\n\t\t\treturn_list.append(object[key])\n\n\t\t## Alphabetize\n\t\treturn_list.sort()\n\n\t\treturn return_list\n\t\t\n\tdef delete_object(self, object_type, object_name, user_key = None):\n\t\t\"\"\"\n\t\tDelete object from configuration files.\n\t\t\"\"\"\n\t\tobject_key = self._get_key(object_type,user_key)\n\n\t\ttarget_object = None\n\t\tk = 'all_%s' % object_type\n\t\tfor item in self.data[k]:\n\t\t\tif not item.has_key(object_key):\n\t\t\t\tcontinue\n\n\t\t\t## If the object matches, mark it for deletion\n\t\t\tif item[object_key] == object_name:\n\t\t\t\tself.data[k].remove(item)\n\t\t\t\titem['meta']['delete_me'] = True\n\t\t\t\titem['meta']['needs_commit'] = True\n\t\t\t\tself.data[k].append(item)\n\n\t\t\t\t## Commit the delete\n\t\t\t\tself.commit()\n\t\t\t\treturn True\n\n\t\t## Only make it here if the object isn't found\n\t\treturn None\n\n\tdef delete_service(self, service_description, host_name):\n\t\t\"\"\"\n\t\tDelete service from configuration\n\t\t\"\"\"\n\t\tfor item in self.data['all_service']:\n\t\t\tif (item['service_description'] == service_description) and (host_name in self._get_active_hosts(item)):\n\t\t\t\tself.data['all_service'].remove(item)\n\t\t\t\titem['meta']['delete_me'] = True\n\t\t\t\titem['meta']['needs_commit'] = True\n\t\t\t\tself.data['all_service'].append(item)\n\n\t\t\t\treturn True\n\n\tdef delete_host(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tDelete a host\n\t\t\"\"\"\n\t\treturn self.delete_object('host',object_name, user_key = user_key)\n\n\tdef delete_hostgroup(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tDelete a hostgroup\n\t\t\"\"\"\n\t\treturn self.delete_object('hostgroup',object_name, user_key = user_key)\n\n\tdef get_object(self, object_type, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a complete object dictionary\n\t\t\"\"\"\n\t\tobject_key = self._get_key(object_type,user_key)\n\n\t\ttarget_object = None\n\n\t\t#print object_type\n\t\tfor item in self.data['all_%s' % object_type]:\n\t\t\t## Skip items without the specified key\n\t\t\tif not item.has_key(object_key):\n\t\t\t\tcontinue\n\t\t\tif item[object_key] == object_name:\n\t\t\t\ttarget_object = item\n\t\t\t## This is for multi-key items\n\t\treturn target_object\n\n\tdef get_host(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a host object\n\t\t\"\"\"\n\t\treturn self.get_object('host',object_name, user_key = user_key)\n\n\tdef get_servicegroup(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a Servicegroup object\n\t\t\"\"\"\n\t\treturn self.get_object('servicegroup',object_name, user_key = user_key)\n\n\tdef get_contact(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a Contact object\n\t\t\"\"\"\n\t\treturn self.get_object('contact',object_name, user_key = user_key)\n\n\tdef get_contactgroup(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a Contactgroup object\n\t\t\"\"\"\n\t\treturn self.get_object('contactgroup',object_name, user_key = user_key)\n\n\tdef get_timeperiod(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a Timeperiod object\n\t\t\"\"\"\n\t\treturn self.get_object('timeperiod',object_name, user_key = user_key)\n\n\tdef get_command(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a Command object\n\t\t\"\"\"\n\t\treturn self.get_object('command',object_name, user_key = user_key)\n\n\tdef get_hostgroup(self, object_name, user_key = None):\n\t\t\"\"\"\n\t\tReturn a hostgroup object\n\t\t\"\"\"\n\t\treturn self.get_object('hostgroup',object_name, user_key = user_key)\n\n\tdef get_service(self, target_host, service_description):\n\t\t\"\"\"\n\t\tReturn a service object. This has to be seperate from the 'get_object'\n\t\tmethod, because it requires more than one key\n\t\t\"\"\"\n\t\tfor item in self.data['all_service']:\n\t\t\t## Skip service with no service_description\n\t\t\tif not item.has_key('service_description'):\n\t\t\t\tcontinue\n\t\t\t## Skip non-matching services\n\t\t\tif item['service_description'] != service_description:\n\t\t\t\tcontinue\n\n\t\t\tif target_host in self._get_active_hosts(item):\n\t\t\t\treturn item\n\n\t\treturn None\n\n\tdef _append_use(self, source_item, name):\n\t\t\"\"\"\n\t\tAppend any unused values from 'name' to the dict 'item'\n\t\t\"\"\"\n\t\t## Remove the 'use' key\n\t\tif source_item.has_key('use'):\n\t\t\tdel source_item['use']\n\t\t\n\t\tfor possible_item in self.pre_object_list:\n\t\t\tif possible_item.has_key('name'):\n\t\t\t\t## Start appending to the item\n\t\t\t\tfor k,v in possible_item.iteritems():\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif k == 'use':\n\t\t\t\t\t\t\tsource_item = self._append_use(source_item, v)\n\t\t\t\t\texcept:\n\t\t\t\t\t\traise ParserError(\"Recursion error on %s %s\" % (source_item, v) )\n\n\n\t\t\t\t\t## Only add the item if it doesn't already exist\n\t\t\t\t\tif not source_item.has_key(k):\n\t\t\t\t\t\tsource_item[k] = v\n\t\treturn source_item\n\n\tdef _post_parse(self):\n\t\tself.item_list = None\n\t\tself.item_apply_cache = {} # This is performance tweak used by _apply_template\n\t\tfor raw_item in self.pre_object_list:\n\t\t\t# Performance tweak, make sure hashmap exists for this object_type\n\t\t\tobject_type = raw_item['meta']['object_type']\n\t\t\tif not self.item_apply_cache.has_key( object_type ):\n\t\t\t\tself.item_apply_cache[ object_type ] = {}\n\t\t\t# Tweak ends\n\t\t\tif raw_item.has_key('use'):\n\t\t\t\traw_item = self._apply_template( raw_item )\n\t\t\tself.post_object_list.append(raw_item)\n\t\t## Add the items to the class lists. \n\t\tfor list_item in self.post_object_list:\n\t\t\ttype_list_name = \"all_%s\" % list_item['meta']['object_type']\n\t\t\tif not self.data.has_key(type_list_name):\n\t\t\t\tself.data[type_list_name] = []\n\n\t\t\tself.data[type_list_name].append(list_item)\n\tdef commit(self):\n\t\t\"\"\"\n\t\tWrite any changes that have been made to it's appropriate file\n\t\t\"\"\"\n\t\t## Loops through ALL items\n\t\tfor k in self.data.keys():\n\t\t\tfor item in self[k]:\n\n\t\t\t\t## If the object needs committing, commit it!\n\t\t\t\tif item['meta']['needs_commit']:\n\t\t\t\t\t## Create file contents as an empty string\n\t\t\t\t\tfile_contents = \"\"\n\n\t\t\t\t\t## find any other items that may share this config file\n\t\t\t\t\textra_items = self._get_items_in_file(item['meta']['filename'])\n\t\t\t\t\tif len(extra_items) > 0:\n\t\t\t\t\t\tfor commit_item in extra_items:\n\t\t\t\t\t\t\t## Ignore files that are already set to be deleted:w\n\t\t\t\t\t\t\tif commit_item['meta']['delete_me']:\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t## Make sure we aren't adding this thing twice\n\t\t\t\t\t\t\tif item != commit_item:\n\t\t\t\t\t\t\t\tfile_contents += self.print_conf(commit_item)\n\n\t\t\t\t\t## This is the actual item that needs commiting\n\t\t\t\t\tif not item['meta']['delete_me']:\n\t\t\t\t\t\tfile_contents += self.print_conf(item)\n\n\t\t\t\t\t## Write the file\n\t\t\t\t\tf = open(item['meta']['filename'], 'w')\n\t\t\t\t\tf.write(file_contents)\n\t\t\t\t\tf.close()\n\n\t\t\t\t\t## Recreate the item entry without the commit flag\n\t\t\t\t\tself.data[k].remove(item)\n\t\t\t\t\titem['meta']['needs_commit'] = None\n\t\t\t\t\tself.data[k].append(item)\n\n\tdef flag_all_commit(self):\n\t\t\"\"\"\n\t\tFlag every item in the configuration to be committed\n\t\tThis should probably only be used for debugging purposes\n\t\t\"\"\"\n\t\tfor k in self.data.keys():\n\t\t\tindex = 0\n\t\t\tfor item in self[k]:\n\t\t\t\tself.data[k][index]['meta']['needs_commit'] = True\n\t\t\t\tindex += 1\n\n\tdef print_conf(self, item):\n\t\t\"\"\"\n\t\tReturn a string that can be used in a configuration file\n\t\t\"\"\"\n\t\toutput = \"\"\n\t\t## Header, to go on all files\n\t\toutput += \"# Configuration file %s\\n\" % item['meta']['filename']\n\t\toutput += \"# Edited by PyNag on %s\\n\" % time.ctime()\n\n\t\t## Some hostgroup information\n\t\tif item['meta'].has_key('hostgroup_list'):\n\t\t\toutput += \"# Hostgroups: %s\\n\" % \",\".join(item['meta']['hostgroup_list'])\n\n\t\t## Some hostgroup information\n\t\tif item['meta'].has_key('service_list'):\n\t\t\toutput += \"# Services: %s\\n\" % \",\".join(item['meta']['service_list'])\n\n\t\t## Some hostgroup information\n\t\tif item['meta'].has_key('service_members'):\n\t\t\toutput += \"# Service Members: %s\\n\" % \",\".join(item['meta']['service_members'])\n\n\t\tif len(item['meta']['template_fields']) != 0:\n\t\t\toutput += \"# Values from templates:\\n\"\n\t\tfor k in item['meta']['template_fields']:\n\t\t\toutput += \"#\\t %-30s %-30s\\n\" % (k, item[k])\n\t\toutput += \"\\n\"\n\t\toutput += \"define %s {\\n\" % item['meta']['object_type']\n\t\tfor k, v in item.iteritems():\n\t\t\tif k != 'meta':\n\t\t\t\tif k not in item['meta']['template_fields']:\n\t\t\t\t\toutput += \"\\t %-30s %-30s\\n\" % (k,v)\n\t\t\n\t\toutput += \"}\\n\\n\"\n\t\treturn output\n\n\n\tdef _load_static_file(self, filename):\n\t\t\"\"\"Load a general config file (like nagios.cfg) that has key=value config file format. Ignore comments\n\t\t\n\t\tReturns: a [ (key,value), (key,value) ] list\n\t\t\"\"\"\n\t\tresult = []\n\t\tfor line in open(filename).readlines():\n\t\t\t## Strip out new line characters\n\t\t\tline = line.strip()\n\n\t\t\t## Skip blank lines\n\t\t\tif line == \"\":\n\t\t\t\tcontinue\n\n\t\t\t## Skip comments\n\t\t\tif line[0] == \"#\" or line[0] == ';':\n\t\t\t\tcontinue\n\t\t\tkey, value = line.split(\"=\", 1)\n\t\t\tresult.append( (key, value) )\n\t\treturn result\n\tdef needs_reload(self):\n\t\t\"Returns True if Nagios service needs reload of cfg files\"\n\t\tnew_timestamps = self.get_timestamps()\n\t\tfor k,v in self.maincfg_values:\n\t\t\tif k == 'lock_file': lockfile = v\n\t\tif not os.path.isfile(lockfile): return False\n\t\tlockfile = new_timestamps.pop(lockfile)\n\t\tfor k,v in new_timestamps.items():\n\t\t\tif int(v) > lockfile: return True\n\t\treturn False \n\tdef needs_reparse(self):\n\t\t\"Returns True if any Nagios configuration file has changed since last parse()\"\n\t\tnew_timestamps = self.get_timestamps()\n\t\tif len(new_timestamps) != len( self.timestamps ):\n\t\t\treturn True\n\t\tfor k,v in new_timestamps.items():\n\t\t\tif self.timestamps[k] != v:\n\t\t\t\treturn True\n\t\treturn False\n\tdef parse(self):\n\t\t\"\"\"\n\t\tLoad the nagios.cfg file and parse it up\n\t\t\"\"\"\n\t\tself.maincfg_values = self._load_static_file(self.cfg_file)\n\t\t\n\t\tself.cfg_files = self.get_cfg_files()\n\t\t\n\t\tself.resource_values = self.get_resources()\n\t\t\n\t\tself.timestamps = self.get_timestamps()\n\t\t\n\t\t## This loads everything into\n\t\tfor cfg_file in self.cfg_files:\n\t\t\tself._load_file(cfg_file)\n\n\t\tself._post_parse()\n\tdef get_timestamps(self):\n\t\t\"Returns a hash map of all nagios related files and their timestamps\"\n\t\tfiles = {}\n\t\tfiles[self.cfg_file] = None\n\t\tfor k,v in self.maincfg_values:\n\t\t\tif k == 'resource_file' or k == 'lock_file':\n\t\t\t\tfiles[v] = None\n\t\tfor i in self.get_cfg_files():\n\t\t\tfiles[i] = None\n\t\t# Now lets lets get timestamp of every file\n\t\tfor k,v in files.items():\n\t\t\tif not os.path.isfile(k): continue\n\t\t\tfiles[k] = os.stat(k).st_mtime\n\t\treturn files\n\tdef get_resources(self):\n\t\t\"Returns a list of every private resources from nagios.cfg\"\n\t\tresources = []\n\t\tfor config_object,config_value in self.maincfg_values:\n\t\t\tif config_object == 'resource_file' and os.path.isfile(config_value):\n\t\t\t\tresources += self._load_static_file(config_value)\n\t\treturn resources\n\n\tdef extended_parse(self):\n\t\t\"\"\"\n\t\tThis parse is used after the initial parse() command is run. It is\n\t\tonly needed if you want extended meta information about hosts or other objects\n\t\t\"\"\"\n\t\t## Do the initial parsing\n\t\tself.parse()\n\n\t\t## First, cycle through the hosts, and append hostgroup information\n\t\tindex = 0\n\t\tfor host in self.data['all_host']:\n\t\t\tif host.has_key('register') and host['register'] == '0': continue\n\t\t\tif not host.has_key('host_name'): continue\n\t\t\tif not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):\n\t\t\t\tself.data['all_host'][index]['meta']['hostgroup_list'] = []\n\n\t\t\t## Append any hostgroups that are directly listed in the host definition\n\t\t\tif host.has_key('hostgroups'):\n\t\t\t\tfor hostgroup_name in self._get_list(host, 'hostgroups'):\n\t\t\t\t\tif not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):\n\t\t\t\t\t\tself.data['all_host'][index]['meta']['hostgroup_list'] = []\n\t\t\t\t\tif hostgroup_name not in self.data['all_host'][index]['meta']['hostgroup_list']:\n\t\t\t\t\t\tself.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup_name)\n\n\t\t\t## Append any services which reference this host\n\t\t\tservice_list = []\n\t\t\tfor service in self.data['all_service']:\n\t\t\t\tif service.has_key('register') and service['register'] == '0': continue\n\t\t\t\tif not service.has_key('service_description'): continue\n\t\t\t\tif host['host_name'] in self._get_active_hosts(service):\n\t\t\t\t\tservice_list.append(service['service_description'])\n\t\t\tself.data['all_host'][index]['meta']['service_list'] = service_list\n\t\t\t\t\t\n\n\t\t\t## Increment count\n\t\t\tindex += 1\n\n\t\t## Loop through all hostgroups, appending them to their respective hosts\n\t\tfor hostgroup in self.data['all_hostgroup']:\n\n\t\t\tfor member in self._get_list(hostgroup,'members'):\n\t\t\t\tindex = 0\n\t\t\t\tfor host in self.data['all_host']:\n\t\t\t\t\tif not host.has_key('host_name'): continue\n\n\t\t\t\t\t## Skip members that do not match\n\t\t\t\t\tif host['host_name'] == member:\n\n\t\t\t\t\t\t## Create the meta var if it doesn' exist\n\t\t\t\t\t\tif not self.data['all_host'][index]['meta'].has_key('hostgroup_list'):\n\t\t\t\t\t\t\tself.data['all_host'][index]['meta']['hostgroup_list'] = []\n\n\t\t\t\t\t\tif hostgroup['hostgroup_name'] not in self.data['all_host'][index]['meta']['hostgroup_list']:\n\t\t\t\t\t\t\tself.data['all_host'][index]['meta']['hostgroup_list'].append(hostgroup['hostgroup_name'])\n\n\t\t\t\t\t## Increment count\n\t\t\t\t\tindex += 1\n\n\t\t## Expand service membership\n\t\tindex = 0\n\t\tfor service in self.data['all_service']:\n\t\t\tservice_members = []\n\n\t\t\t## Find a list of hosts to negate from the final list\n\t\t\tself.data['all_service'][index]['meta']['service_members'] = self._get_active_hosts(service)\n\n\t\t\t## Increment count\n\t\t\tindex += 1\n\n\tdef _get_active_hosts(self, object):\n\t\t\"\"\"\n\t\tGiven an object, return a list of active hosts. This will exclude hosts that ar negated with a \"!\"\n\t\t\"\"\"\n\t\t## First, generate the negation list\n\t\tnegate_hosts = []\n\n\t\t## Hostgroups\n\t\tif object.has_key(\"hostgroup_name\"):\n\n\t\t\tfor hostgroup_name in self._get_list(object, 'hostgroup_name'):\n\t\t\t\tif hostgroup_name[0] == \"!\":\n\t\t\t\t\thostgroup_obj = self.get_hostgroup(hostgroup_name[1:])\n\t\t\t\t\tnegate_hosts.extend(self._get_list(hostgroup_obj,'members'))\n\n\t\t## Host Names\n\t\tif object.has_key(\"host_name\"):\n\t\t\tfor host_name in self._get_list(object, 'host_name'):\n\t\t\t\tif host_name[0] == \"!\":\n\t\t\t\t\tnegate_hosts.append(host_name[1:])\n\n\n\t\t## Now get hosts that are actually listed\n\t\tactive_hosts = []\n\n\t\t## Hostgroups\n\t\tif object.has_key(\"hostgroup_name\"):\n\n\t\t\tfor hostgroup_name in self._get_list(object, 'hostgroup_name'):\n\t\t\t\tif hostgroup_name[0] != \"!\":\n\t\t\t\t\tactive_hosts.extend(self._get_list(self.get_hostgroup(hostgroup_name),'members'))\n\n\t\t## Host Names\n\t\tif object.has_key(\"host_name\"):\n\t\t\tfor host_name in self._get_list(object, 'host_name'):\n\t\t\t\tif host_name[0] != \"!\":\n\t\t\t\t\tactive_hosts.append(host_name)\n\n\t\t## Combine the lists\n\t\treturn_hosts = []\n\t\tfor active_host in active_hosts:\n\t\t\tif active_host not in negate_hosts:\n\t\t\t\treturn_hosts.append(active_host)\n\n\t\treturn return_hosts\n\n\tdef get_cfg_files(self):\n\t\t\"\"\"\n\t\tReturn a list of all cfg files used in this configuration\n\n\t\tExample:\n\t\tprint get_cfg_files()\n\t\t['/etc/nagios/hosts/host1.cfg','/etc/nagios/hosts/host2.cfg',...]\n\t\t\"\"\"\n\t\tcfg_files = []\n\t\tfor config_object, config_value in self.maincfg_values:\n\t\t\t\n\t\t\t## Add cfg_file objects to cfg file list\n\t\t\tif config_object == \"cfg_file\" and os.path.isfile(config_value):\n\t\t\t\t\tcfg_files.append(config_value)\n\n\t\t\t## Parse all files in a cfg directory\n\t\t\tif config_object == \"cfg_dir\":\n\t\t\t\tdirectories = []\n\t\t\t\traw_file_list = []\n\t\t\t\tdirectories.append( config_value )\n\t\t\t\t# Walk through every subdirectory and add to our list\n\t\t\t\twhile len(directories) > 0:\n\t\t\t\t\tcurrent_directory = directories.pop(0)\n\t\t\t\t\t# Nagios doesnt care if cfg_dir exists or not, so why should we ?\n\t\t\t\t\tif not os.path.isdir( current_directory ): continue\n\t\t\t\t\tlist = os.listdir(current_directory)\n\t\t\t\t\tfor item in list:\n\t\t\t\t\t\t# Append full path to file\n\t\t\t\t\t\titem = \"%s\" % (os.path.join(current_directory, item.strip() ) )\n\t\t\t\t\t\tif os.path.islink( item ):\n\t\t\t\t\t\t\titem = os.readlink( item )\n\t\t\t\t\t\tif os.path.isdir(item):\n\t\t\t\t\t\t\tdirectories.append( item )\n\t\t\t\t\t\tif raw_file_list.count( item ) < 1:\n\t\t\t\t\t\t\traw_file_list.append( item )\n\t\t\t\tfor raw_file in raw_file_list:\n\t\t\t\t\tif raw_file.endswith('.cfg'):\n\t\t\t\t\t\tif os.path.exists(raw_file):\n\t\t\t\t\t\t\t'Nagios doesnt care if cfg_file exists or not, so we will not throws errors'\n\t\t\t\t\t\t\tcfg_files.append(raw_file)\n\n\t\treturn cfg_files\n\tdef get_object_types(self):\n\t\t''' Returns a list of all discovered object types '''\n\t\treturn map(lambda x: re.sub(\"all_\",\"\", x), self.data.keys())\n\tdef cleanup(self):\n\t\t\"\"\"\n\t\tThis cleans up dead configuration files\n\t\t\"\"\"\n\t\tfor filename in self.cfg_files:\n\t\t\tif os.path.isfile(filename):\n\t\t\t\tsize = os.stat(filename)[6]\n\t\t\t\tif size == 0:\n\t\t\t\t\tos.remove(filename)\n\n\t\treturn True\n\n\tdef __setitem__(self, key, item):\n\t\tself.data[key] = item\n\n\tdef __getitem__(self, key):\n\t\treturn self.data[key]\n\nclass status:\n\n\tdef __init__(self, filename = \"/var/log/nagios/status.dat\"):\n\n\t\tif not os.path.isfile(filename):\n\t\t\traise ParserError(\"status.dat file %s not found.\" % filename)\n\n\t\tself.filename = filename\n\t\tself.data = {}\n\n\tdef parse(self):\n\t\t## Set globals (This is stolen from the perl module)\n\t\ttype = None\n\n\t\tfor line in open(self.filename, 'rb').readlines():\n\n\t\t\t## Cleanup and line skips\n\t\t\tline = line.strip()\n\t\t\tif line == \"\":\n\t\t\t\tcontinue\n\t\t\tif line[0] == \"#\" or line[0] == ';':\n\t\t\t\tcontinue\n\n\t\t\tif line.find(\"{\") != -1:\n\n\t\t\t\tstatus = {}\n\t\t\t\tstatus['meta'] = {}\n\t\t\t\tstatus['meta']['type'] = line.split(\"{\")[0].strip()\n\t\t\t\tcontinue\n\n\t\t\tif line.find(\"}\") != -1:\n\t\t\t\tif not self.data.has_key(status['meta']['type']):\n\t\t\t\t\tself.data[status['meta']['type']] = []\n\t\n\t\t\t\tself.data[status['meta']['type']].append(status)\n\t\t\t\tcontinue\n\n\t\t\t(key, value) = line.split(\"=\", 1)\n\t\t\tstatus[key] = value\n\n\n\tdef __setitem__(self, key, item):\n\t\tself.data[key] = item\n\n\tdef __getitem__(self, key):\n\t\treturn self.data[key]\n\nclass ParserError(Exception):\n\tdef __init__(self, message, item=None):\n\t\tself.message = message\n\t\tself.item = item\n\tdef __str__(self):\n\t\treturn repr(self.message)\n\nif __name__ == '__main__':\n\tc=config('/etc/nagios/nagios.cfg')\n\tc.parse()\n\tprint c.get_object_types()\n\tprint c.needs_reload()\n\t#for i in c.data['all_host']:\n\t#\tprint i['meta']\n"
] | true |
99,939 | 88215fda2071e16e59da7f27e603ebff1a9fe7d5 | from http import HTTPStatus
from peewee import DoesNotExist, IntegrityError
from playhouse.shortcuts import dict_to_model, model_to_dict
from api.helpers import add_extra_info_to_dict, to_utc_datetime
from api.models import DataSource, DataSourceToken, User
class UserService():
def get_user_by_id(self, user_id: int, to_dict: bool = False):
"""Get user by user_id
Arguments:
user_id {int} -- Id of user
Raises:
ValueError: User not found with given user_id
Returns:
User -- User object
"""
try:
if to_dict:
return model_to_dict(User.get_by_id(user_id))
return User.get_by_id(user_id)
except DoesNotExist:
raise ValueError(HTTPStatus.NOT_FOUND,
'User with id {} does not exist'.format(user_id))
def get_user_by_username(self, username: str):
"""Get user by username
Arguments:
username {str} -- Username
Raises:
ValueError: User not found with given username
Returns:
User -- User object
"""
try:
return model_to_dict(
User.select().where(User.username == username).get())
except DoesNotExist:
raise ValueError(
HTTPStatus.NOT_FOUND,
'User with username {} does not exist'.format(username))
except Exception:
raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,
'Internal server error')
def get_user_by_email(self, email: str):
"""Get user by email
Arguments:
email {str} -- Email
Raises:
ValueError: User not found with given email
Returns:
User -- User object
"""
try:
return model_to_dict(
User.select().where(User.email == email).get())
except DoesNotExist:
raise ValueError(HTTPStatus.NOT_FOUND,
'User with email {} does not exist'.format(email))
except Exception:
raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,
'Internal server error')
def get_data_source_by_user(self, username: str = None, id: int = None):
"""Retrieves data source from an user
Arguments:
username {str} -- Optional Username
id {int} -- Optional Id of user
Returns:
DataSource[] -- An array of data sources
"""
all_data_sources_from_user_array = []
user = None
try:
try:
if username is not None:
user = dict_to_model(
User, UserService.get_user_by_username(self, username))
elif id is not None:
user = dict_to_model(User,
UserService.get_user_by_id(self, id))
except Exception:
raise
if user is not None:
for data_source in DataSource.select(
DataSource, user).where(DataSource.user == user):
all_data_sources_from_user_array.append(
model_to_dict(data_source))
return all_data_sources_from_user_array
except Exception:
raise
def create_user(self, email: str, username=None):
"""Creates a new user
Arguments:
email {str} -- email of user
Keyword Arguments:
username {str} -- Optional: username of user (default: {None})
Raises:
ValueError: Email is required
BaseException: Internal server error
Returns:
User -- Newly created user
"""
join_date = to_utc_datetime()
last_login_date = to_utc_datetime()
try:
if username is not None:
return model_to_dict(
User.create(username=username,
email=email,
join_date=join_date,
last_login_date=last_login_date))
else:
return model_to_dict(
User.create(email=email,
join_date=join_date,
last_login_date=last_login_date))
except IntegrityError:
if email is None:
raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')
else:
raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')
except Exception:
raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,
'Internal server error')
def set_username(self, user_id: int, username: str):
"""Sets the username of the logged in user
Arguments:
user_id {int} -- User id
username {str} -- new username
"""
user: User = UserService.get_user_by_id(self, user_id)
if user is not None and username is not None:
if user.username is None:
user.username = username
try:
user.save()
return model_to_dict(user)
except BaseException:
raise ValueError(HTTPStatus.CONFLICT,
'Username already exists')
else:
raise ValueError(HTTPStatus.NOT_MODIFIED,
'Username can only be set once')
else:
raise ValueError(HTTPStatus.BAD_REQUEST, 'Username is required')
def get_data_source_tokens_by_user(self, user_id: int):
"""Get data source tokens by user
Arguments:
user_id {int} -- User id
Returns:
DataSourceToken[] -- An array of data source tokens objects
"""
all_data_source_tokens_array = []
user = None
try:
user: User = UserService.get_user_by_id(self, user_id)
except Exception:
raise
try:
for data_source_token in DataSourceToken.select(
DataSourceToken,
user).where(DataSourceToken.user_id == user_id):
all_data_source_tokens_array.append(
model_to_dict(data_source_token, recurse=False))
return all_data_source_tokens_array
except Exception:
raise
def deactivate_token_of_user(self, user_id: int,
data_source_token_id: int):
"""Deactivates the token of the user
Arguments:
user_id {int} -- User id
data_source_token_id {int} -- Token id
Returns:
DataSourceToken -- Deactivated DataSourceToken object
"""
try:
data_source_token = DataSourceToken.get(
(DataSourceToken.id == data_source_token_id) &
(DataSourceToken.user_id == user_id))
if data_source_token.is_active:
data_source_token.is_active = False
data_source_token.deactivated_since = to_utc_datetime()
data_source_token.save()
return model_to_dict(data_source_token, recurse=False)
else:
return_dict = model_to_dict(data_source_token, recurse=False)
return_dict = add_extra_info_to_dict(
return_dict, 'message',
f'Token with id {data_source_token_id} has already been '
f'deactivated.'
)
return return_dict
except DoesNotExist:
raise ValueError(
HTTPStatus.NOT_FOUND,
'Unable to find data source token given user and token id')
| [
"from http import HTTPStatus\n\nfrom peewee import DoesNotExist, IntegrityError\nfrom playhouse.shortcuts import dict_to_model, model_to_dict\n\nfrom api.helpers import add_extra_info_to_dict, to_utc_datetime\nfrom api.models import DataSource, DataSourceToken, User\n\n\nclass UserService():\n def get_user_by_id(self, user_id: int, to_dict: bool = False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(\n User.select().where(User.username == username).get())\n except DoesNotExist:\n raise ValueError(\n HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(\n User.select().where(User.email == email).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_data_source_by_user(self, username: str = None, id: int = None):\n \"\"\"Retrieves data source from an user\n\n Arguments:\n username {str} -- Optional Username\n id {int} -- Optional Id of user\n\n Returns:\n DataSource[] -- An array of data sources\n \"\"\"\n all_data_sources_from_user_array = []\n user = None\n try:\n try:\n if username is not None:\n user = dict_to_model(\n User, UserService.get_user_by_username(self, username))\n elif id is not None:\n user = dict_to_model(User,\n UserService.get_user_by_id(self, id))\n except Exception:\n raise\n\n if user is not None:\n for data_source in DataSource.select(\n DataSource, user).where(DataSource.user == user):\n all_data_sources_from_user_array.append(\n model_to_dict(data_source))\n return all_data_sources_from_user_array\n except Exception:\n raise\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(\n User.create(username=username,\n email=email,\n join_date=join_date,\n last_login_date=last_login_date))\n else:\n return model_to_dict(\n User.create(email=email,\n join_date=join_date,\n last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def set_username(self, user_id: int, username: str):\n \"\"\"Sets the username of the logged in user\n\n Arguments:\n user_id {int} -- User id\n username {str} -- new username\n \"\"\"\n user: User = UserService.get_user_by_id(self, user_id)\n if user is not None and username is not None:\n if user.username is None:\n user.username = username\n try:\n user.save()\n return model_to_dict(user)\n except BaseException:\n raise ValueError(HTTPStatus.CONFLICT,\n 'Username already exists')\n else:\n raise ValueError(HTTPStatus.NOT_MODIFIED,\n 'Username can only be set once')\n else:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Username is required')\n\n def get_data_source_tokens_by_user(self, user_id: int):\n \"\"\"Get data source tokens by user\n\n Arguments:\n user_id {int} -- User id\n\n Returns:\n DataSourceToken[] -- An array of data source tokens objects\n \"\"\"\n all_data_source_tokens_array = []\n user = None\n try:\n user: User = UserService.get_user_by_id(self, user_id)\n except Exception:\n raise\n\n try:\n for data_source_token in DataSourceToken.select(\n DataSourceToken,\n user).where(DataSourceToken.user_id == user_id):\n all_data_source_tokens_array.append(\n model_to_dict(data_source_token, recurse=False))\n return all_data_source_tokens_array\n except Exception:\n raise\n\n def deactivate_token_of_user(self, user_id: int,\n data_source_token_id: int):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get(\n (DataSourceToken.id == data_source_token_id) &\n (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(\n return_dict, 'message',\n f'Token with id {data_source_token_id} has already been '\n f'deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(\n HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"from http import HTTPStatus\nfrom peewee import DoesNotExist, IntegrityError\nfrom playhouse.shortcuts import dict_to_model, model_to_dict\nfrom api.helpers import add_extra_info_to_dict, to_utc_datetime\nfrom api.models import DataSource, DataSourceToken, User\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.username ==\n username).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_data_source_by_user(self, username: str=None, id: int=None):\n \"\"\"Retrieves data source from an user\n\n Arguments:\n username {str} -- Optional Username\n id {int} -- Optional Id of user\n\n Returns:\n DataSource[] -- An array of data sources\n \"\"\"\n all_data_sources_from_user_array = []\n user = None\n try:\n try:\n if username is not None:\n user = dict_to_model(User, UserService.\n get_user_by_username(self, username))\n elif id is not None:\n user = dict_to_model(User, UserService.get_user_by_id(\n self, id))\n except Exception:\n raise\n if user is not None:\n for data_source in DataSource.select(DataSource, user).where(\n DataSource.user == user):\n all_data_sources_from_user_array.append(model_to_dict(\n data_source))\n return all_data_sources_from_user_array\n except Exception:\n raise\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def set_username(self, user_id: int, username: str):\n \"\"\"Sets the username of the logged in user\n\n Arguments:\n user_id {int} -- User id\n username {str} -- new username\n \"\"\"\n user: User = UserService.get_user_by_id(self, user_id)\n if user is not None and username is not None:\n if user.username is None:\n user.username = username\n try:\n user.save()\n return model_to_dict(user)\n except BaseException:\n raise ValueError(HTTPStatus.CONFLICT,\n 'Username already exists')\n else:\n raise ValueError(HTTPStatus.NOT_MODIFIED,\n 'Username can only be set once')\n else:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Username is required')\n\n def get_data_source_tokens_by_user(self, user_id: int):\n \"\"\"Get data source tokens by user\n\n Arguments:\n user_id {int} -- User id\n\n Returns:\n DataSourceToken[] -- An array of data source tokens objects\n \"\"\"\n all_data_source_tokens_array = []\n user = None\n try:\n user: User = UserService.get_user_by_id(self, user_id)\n except Exception:\n raise\n try:\n for data_source_token in DataSourceToken.select(DataSourceToken,\n user).where(DataSourceToken.user_id == user_id):\n all_data_source_tokens_array.append(model_to_dict(\n data_source_token, recurse=False))\n return all_data_source_tokens_array\n except Exception:\n raise\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.username ==\n username).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_data_source_by_user(self, username: str=None, id: int=None):\n \"\"\"Retrieves data source from an user\n\n Arguments:\n username {str} -- Optional Username\n id {int} -- Optional Id of user\n\n Returns:\n DataSource[] -- An array of data sources\n \"\"\"\n all_data_sources_from_user_array = []\n user = None\n try:\n try:\n if username is not None:\n user = dict_to_model(User, UserService.\n get_user_by_username(self, username))\n elif id is not None:\n user = dict_to_model(User, UserService.get_user_by_id(\n self, id))\n except Exception:\n raise\n if user is not None:\n for data_source in DataSource.select(DataSource, user).where(\n DataSource.user == user):\n all_data_sources_from_user_array.append(model_to_dict(\n data_source))\n return all_data_sources_from_user_array\n except Exception:\n raise\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def set_username(self, user_id: int, username: str):\n \"\"\"Sets the username of the logged in user\n\n Arguments:\n user_id {int} -- User id\n username {str} -- new username\n \"\"\"\n user: User = UserService.get_user_by_id(self, user_id)\n if user is not None and username is not None:\n if user.username is None:\n user.username = username\n try:\n user.save()\n return model_to_dict(user)\n except BaseException:\n raise ValueError(HTTPStatus.CONFLICT,\n 'Username already exists')\n else:\n raise ValueError(HTTPStatus.NOT_MODIFIED,\n 'Username can only be set once')\n else:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Username is required')\n\n def get_data_source_tokens_by_user(self, user_id: int):\n \"\"\"Get data source tokens by user\n\n Arguments:\n user_id {int} -- User id\n\n Returns:\n DataSourceToken[] -- An array of data source tokens objects\n \"\"\"\n all_data_source_tokens_array = []\n user = None\n try:\n user: User = UserService.get_user_by_id(self, user_id)\n except Exception:\n raise\n try:\n for data_source_token in DataSourceToken.select(DataSourceToken,\n user).where(DataSourceToken.user_id == user_id):\n all_data_source_tokens_array.append(model_to_dict(\n data_source_token, recurse=False))\n return all_data_source_tokens_array\n except Exception:\n raise\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.username ==\n username).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_data_source_by_user(self, username: str=None, id: int=None):\n \"\"\"Retrieves data source from an user\n\n Arguments:\n username {str} -- Optional Username\n id {int} -- Optional Id of user\n\n Returns:\n DataSource[] -- An array of data sources\n \"\"\"\n all_data_sources_from_user_array = []\n user = None\n try:\n try:\n if username is not None:\n user = dict_to_model(User, UserService.\n get_user_by_username(self, username))\n elif id is not None:\n user = dict_to_model(User, UserService.get_user_by_id(\n self, id))\n except Exception:\n raise\n if user is not None:\n for data_source in DataSource.select(DataSource, user).where(\n DataSource.user == user):\n all_data_sources_from_user_array.append(model_to_dict(\n data_source))\n return all_data_sources_from_user_array\n except Exception:\n raise\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def set_username(self, user_id: int, username: str):\n \"\"\"Sets the username of the logged in user\n\n Arguments:\n user_id {int} -- User id\n username {str} -- new username\n \"\"\"\n user: User = UserService.get_user_by_id(self, user_id)\n if user is not None and username is not None:\n if user.username is None:\n user.username = username\n try:\n user.save()\n return model_to_dict(user)\n except BaseException:\n raise ValueError(HTTPStatus.CONFLICT,\n 'Username already exists')\n else:\n raise ValueError(HTTPStatus.NOT_MODIFIED,\n 'Username can only be set once')\n else:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Username is required')\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.username ==\n username).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_data_source_by_user(self, username: str=None, id: int=None):\n \"\"\"Retrieves data source from an user\n\n Arguments:\n username {str} -- Optional Username\n id {int} -- Optional Id of user\n\n Returns:\n DataSource[] -- An array of data sources\n \"\"\"\n all_data_sources_from_user_array = []\n user = None\n try:\n try:\n if username is not None:\n user = dict_to_model(User, UserService.\n get_user_by_username(self, username))\n elif id is not None:\n user = dict_to_model(User, UserService.get_user_by_id(\n self, id))\n except Exception:\n raise\n if user is not None:\n for data_source in DataSource.select(DataSource, user).where(\n DataSource.user == user):\n all_data_sources_from_user_array.append(model_to_dict(\n data_source))\n return all_data_sources_from_user_array\n except Exception:\n raise\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n\n def get_user_by_username(self, username: str):\n \"\"\"Get user by username\n\n Arguments:\n username {str} -- Username\n\n Raises:\n ValueError: User not found with given username\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.username ==\n username).get())\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with username {} does not exist'.format(username))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n <function token>\n\n def get_user_by_email(self, email: str):\n \"\"\"Get user by email\n\n Arguments:\n email {str} -- Email\n\n Raises:\n ValueError: User not found with given email\n\n Returns:\n User -- User object\n \"\"\"\n try:\n return model_to_dict(User.select().where(User.email == email).get()\n )\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with email {} does not exist'.format(email))\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n\n def get_user_by_id(self, user_id: int, to_dict: bool=False):\n \"\"\"Get user by user_id\n\n Arguments:\n user_id {int} -- Id of user\n\n Raises:\n ValueError: User not found with given user_id\n\n Returns:\n User -- User object\n \"\"\"\n try:\n if to_dict:\n return model_to_dict(User.get_by_id(user_id))\n return User.get_by_id(user_id)\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'User with id {} does not exist'.format(user_id))\n <function token>\n <function token>\n <function token>\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n <function token>\n <function token>\n <function token>\n <function token>\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n\n def deactivate_token_of_user(self, user_id: int, data_source_token_id: int\n ):\n \"\"\"Deactivates the token of the user\n\n Arguments:\n user_id {int} -- User id\n data_source_token_id {int} -- Token id\n\n Returns:\n DataSourceToken -- Deactivated DataSourceToken object\n \"\"\"\n try:\n data_source_token = DataSourceToken.get((DataSourceToken.id ==\n data_source_token_id) & (DataSourceToken.user_id == user_id))\n if data_source_token.is_active:\n data_source_token.is_active = False\n data_source_token.deactivated_since = to_utc_datetime()\n data_source_token.save()\n return model_to_dict(data_source_token, recurse=False)\n else:\n return_dict = model_to_dict(data_source_token, recurse=False)\n return_dict = add_extra_info_to_dict(return_dict, 'message',\n f'Token with id {data_source_token_id} has already been deactivated.'\n )\n return return_dict\n except DoesNotExist:\n raise ValueError(HTTPStatus.NOT_FOUND,\n 'Unable to find data source token given user and token id')\n",
"<import token>\n\n\nclass UserService:\n <function token>\n <function token>\n <function token>\n <function token>\n\n def create_user(self, email: str, username=None):\n \"\"\"Creates a new user\n\n Arguments:\n email {str} -- email of user\n\n Keyword Arguments:\n username {str} -- Optional: username of user (default: {None})\n\n Raises:\n ValueError: Email is required\n BaseException: Internal server error\n\n Returns:\n User -- Newly created user\n \"\"\"\n join_date = to_utc_datetime()\n last_login_date = to_utc_datetime()\n try:\n if username is not None:\n return model_to_dict(User.create(username=username, email=\n email, join_date=join_date, last_login_date=\n last_login_date))\n else:\n return model_to_dict(User.create(email=email, join_date=\n join_date, last_login_date=last_login_date))\n except IntegrityError:\n if email is None:\n raise ValueError(HTTPStatus.BAD_REQUEST, 'Email is required')\n else:\n raise ValueError(HTTPStatus.CONFLICT, 'Email already exists')\n except Exception:\n raise BaseException(HTTPStatus.INTERNAL_SERVER_ERROR,\n 'Internal server error')\n <function token>\n <function token>\n <function token>\n",
"<import token>\n\n\nclass UserService:\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<class token>\n"
] | false |
99,940 | 416fe1a39b6acd1cfc63b9be8932965ec9792a9d | #Makes dataset for tensorflow (possibility, might not do it)
def NNDataSet(num_testers,mispercievedSeq, mispercievedRan):
AOIfile=open("AOIMetricsSequential.csv","r")
#AOIfileR=open("AOIMetricsRandom.csv","r")
file = open("NN_SVMData/EmotionDataSequentialAll.csv","w")
fileP = open("NN_SVMData/EmotionDataSequentialPercievedAll.csv","w")
fileA = open("NN_SVMData/EmotionDataAll.csv","w")
attributes = ["AU1","AU2","AU4","AU6","AU7","AU9","AU12","AU15","AU16","AU20","AU23","AU26","Left","Lower","Right","Upper","class"]
mispercieved = mispercievedSeq
keys = list(mispercieved.keys())
for element in attributes:
if element != "class":
fileA.write(element+",")
else:
fileA.write(element)
fileA.write("\n")
for element in attributes:
if element != "class":
file.write(element+",")
fileP.write(element+",")
else:
file.write(element)
fileP.write(element)
file.write("\n")
fileP.write("\n")
for k in range(2):
index = 0
done = False
while not done:
line = AOIfile.readline()
if line == "":
break
if "_DIS_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
fileA.write(st+",Negative\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Negative\n")
if "_HAP_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Positive\n")
fileA.write(st+",Positive\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Positive\n")
if "_ANG_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
fileA.write(st+",Negative\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Negative\n")
if "_FEA_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
fileA.write(st+",Negative\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Negative\n")
if "_NEU_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Neutral\n")
fileA.write(st+",Neutral\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Neutral\n")
if "_SAD_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line = AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
fileA.write(st+",Negative\n")
if index not in mispercieved[keys[i]]:
fileP.write(st+",Negative\n")
if k == 0:
file.close()
file = open("NN_SVMData/EmotionDataRandomAll.csv","w")
fileP.close()
fileP = open("NN_SVMData/EmotionDataRandomPercievedAll.csv","w")
AOIfile.close()
AOIfile = open("AOIMetricsRandom.csv","r")
for element in attributes:
if element != "class":
file.write(element+",")
fileP.write(element+",")
else:
file.write(element)
fileP.write(element)
mispercieved = mispercievedRan
keys = list(mispercieved.keys())
file.write("\n")
fileP.write("\n")
fileA.close()
file.close()
fileP.close()
AOIfile.close()
#Make Weka dataset for simple labels, positive, negative neutral emotions
def simpleData(num_testers,type,mispercieved):
AOIfile=open("AOIMetrics"+type+".csv","r")
fileP = open("WekaData/Weka"+type+"PercievedAllSimple.arff","w")
file = open("WekaData/Weka"+type+"AllSimple.arff","w")
attributes = ["AU1","AU2","AU4","AU6","AU7","AU9","AU12","AU15","AU16","AU20","AU23","AU26","Left","Lower","Right","Upper","class"]
file.write("@relation emotion\n")
fileP.write("@relation emotion\n")
fileP.write("\n")
file.write("\n")
#Write the attributes in the correct format
for i in range(len(attributes)-1):
file.write("@attribute "+attributes[i]+" numeric\n")
fileP.write("@attribute "+attributes[i]+" numeric\n")
file.write("@attribute "+attributes[len(attributes)-1]+"{Positive,Negative,Neutral}\n")
fileP.write("@attribute "+attributes[len(attributes)-1]+"{Positive,Negative,Neutral}\n")
file.write("\n@data\n")
fileP.write("\n@data\n")
k = list(mispercieved.keys())
done = False
index = 0
while not done:
line = AOIfile.readline()
if line == "":
break
if "_DIS_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Negative\n")
elif "_HAP_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Positive\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Positive\n")
elif "_ANG_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Negative\n")
elif "_FEA_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Negative\n")
elif "_NEU_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Neutral\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Neutral\n")
elif "_SAD_" in line:
index += 1
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Negative\n")
if index not in mispercieved[k[i]]:
fileP.write(st+",Negative\n")
file.close()
fileP.close()
AOIfile.close()
#Makes weka dataset for all testers, but not pooled
def AllData(num_testers,type):
AOIfile=open("AOIMetrics"+type+".csv","r")
file = open("WekaData/Weka"+type+"All.arff","w")
attributes = ["AU1","AU2","AU4","AU6","AU7","AU9","AU12","AU15","AU16","AU20","AU23","AU26","Left","Lower","Right","Upper","class"]
file.write("@relation emotion\n")
file.write("\n")
#Write the attributes in the correct format
for i in range(len(attributes)-1):
file.write("@attribute "+attributes[i]+" numeric\n")
file.write("@attribute "+attributes[len(attributes)-1]+" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n")
file.write("\n@data\n")
done = False
while not done:
line = AOIfile.readline()
if line == "":
break
if "_DIS_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Disgust\n")
elif "_HAP_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Happy\n")
elif "_ANG_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Angry\n")
elif "_FEA_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Fear\n")
elif "_NEU_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Neutral\n")
elif "_SAD_" in line:
line = AOIfile.readline()
for i in range(num_testers):
temp = [0]*16
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Sad\n")
file.close()
AOIfile.close()
#Does it for all testers pooled
def testerData(num_testers,type):
AOIfile=open("AOIMetrics"+type+".csv","r")
for k in range(num_testers):
AOIfile.seek(0)
file = open("WekaData/Weka"+type+"Tester"+str(k+1)+".arff","w")
attributes = ["AU1","AU2","AU4","AU6","AU7","AU9","AU12","AU15","AU16","AU20","AU23","AU26","Left","Lower","Right","Upper","class"]
file.write("@relation emotion\n")
file.write("\n")
for i in range(len(attributes)-1):
file.write("@attribute "+attributes[i]+" numeric\n")
file.write("@attribute "+attributes[len(attributes)-1]+" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n")
file.write("\n@data\n")
done = False
while not done:
line = AOIfile.readline()
if line == "":
break
if "_DIS_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Disgust\n")
elif "_HAP_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Happy\n")
elif "_ANG_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Angry\n")
elif "_FEA_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Fear\n")
elif "_NEU_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Neutral\n")
elif "_SAD_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(k+1):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Sad\n")
file.close()
AOIfile.close()
#Writes to a file a arff file that pools all data between testers
def PooledData(num_testers,type):
AOIfile=open("AOIMetrics"+type+".csv","r")
file = open("WekaData/Weka"+type+"Pooled.arff","w")
attributes = ["AU1","AU2","AU4","AU6","AU7","AU9","AU12","AU15","AU16","AU20","AU23","AU26","Left","Lower","Right","Upper","class"]
file.write("@relation emotion\n")
file.write("\n")
#Write the attributes in the correct format
for i in range(len(attributes)-1):
file.write("@attribute "+attributes[i]+" numeric\n")
file.write("@attribute "+attributes[len(attributes)-1]+" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n")
file.write("\n@data\n")
done = False
while not done:
line = AOIfile.readline()
if line == "":
break
if "_DIS_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Disgust\n")
elif "_HAP_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Happy\n")
elif "_ANG_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Angry\n")
elif "_FEA_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Fear\n")
elif "_NEU_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Neutral\n")
elif "_SAD_" in line:
line = AOIfile.readline()
temp = [0]*16
for i in range(num_testers):
line=AOIfile.readline()
part = line.split(",")
for j in range(16):
if part[j+2] != "" and part[j+2] != "\n":
temp[j] += float(part[j+2])
st = ','.join(str(e) for e in temp)
file.write(st+",Sad\n")
file.close()
AOIfile.close()
def main():
mispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76, 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26, 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74, 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20, 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57, 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92], 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54], 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72], 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2, 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46, 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2, 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70, 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12, 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78, 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24, 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75, 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45, 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92], 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52, 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72, 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36, 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88, 89, 91, 92],'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46, 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10, 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70, 72, 74, 75, 78, 80, 81, 83, 88, 92]}
PooledData(18,"Sequential")
testerData(18,"Sequential")
AllData(18,"Sequential")
simpleData(18,"Sequential",mispercievedSeq)
mispercievedRan = { 'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72, 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64, 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21, 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59, 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93, 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117], 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29, 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76, 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65, 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106, 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19, 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63, 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103, 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14, 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54, 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100, 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116], 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86, 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116], 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89, 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117], 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65, 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, 105, 108, 109, 113, 115, 117],'Tester1': [6, 7, 8, 9, 10, 14, 15, 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50, 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92, 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26, 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57, 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105, 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14, 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54, 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101, 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117], 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76, 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32, 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95, 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66, 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26, 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86, 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19, 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71, 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}
PooledData(18,"Random")
testerData(18,"Random")
AllData(18,"Random")
simpleData(18,"Random",mispercievedRan)
NNDataSet(18,mispercievedSeq,mispercievedRan)
main() | [
"#Makes dataset for tensorflow (possibility, might not do it)\n\ndef NNDataSet(num_testers,mispercievedSeq, mispercievedRan):\n\tAOIfile=open(\"AOIMetricsSequential.csv\",\"r\")\n\t#AOIfileR=open(\"AOIMetricsRandom.csv\",\"r\")\n\tfile = open(\"NN_SVMData/EmotionDataSequentialAll.csv\",\"w\")\n\tfileP = open(\"NN_SVMData/EmotionDataSequentialPercievedAll.csv\",\"w\")\n\tfileA = open(\"NN_SVMData/EmotionDataAll.csv\",\"w\")\n\tattributes = [\"AU1\",\"AU2\",\"AU4\",\"AU6\",\"AU7\",\"AU9\",\"AU12\",\"AU15\",\"AU16\",\"AU20\",\"AU23\",\"AU26\",\"Left\",\"Lower\",\"Right\",\"Upper\",\"class\"]\n\n\tmispercieved = mispercievedSeq\n\tkeys = list(mispercieved.keys())\n\n\tfor element in attributes:\n\t\tif element != \"class\":\n\t\t\tfileA.write(element+\",\")\n\n\t\telse:\n\t\t\tfileA.write(element)\n\tfileA.write(\"\\n\")\n\n\tfor element in attributes:\n\t\t\tif element != \"class\":\n\t\t\t\tfile.write(element+\",\")\n\t\t\t\tfileP.write(element+\",\")\n\n\t\t\telse:\n\t\t\t\tfile.write(element)\n\t\t\t\tfileP.write(element)\n\tfile.write(\"\\n\")\n\tfileP.write(\"\\n\")\n\n\tfor k in range(2):\n\t\t\n\t\tindex = 0\n\t\tdone = False\n\t\twhile not done:\n\t\t\t\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tif line == \"\":\n\t\t\t\tbreak\n\t\t\tif \"_DIS_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Negative\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Negative\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\t\t\t\t\n\n\t\t\tif \"_HAP_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Positive\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Positive\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Positive\\n\")\n\n\t\t\tif \"_ANG_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Negative\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Negative\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\t\t\tif \"_FEA_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Negative\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Negative\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\t\t\tif \"_NEU_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Neutral\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Neutral\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Neutral\\n\")\n\n\t\t\tif \"_SAD_\" in line:\n\t\t\t\tindex += 1\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\tfor i in range(num_testers): \n\t\t\t\t\ttemp = [0]*16\n\t\t\t\t\tline = AOIfile.readline()\n\t\t\t\t\tpart = line.split(\",\")\n\t\t\t\t\tfor j in range(16):\n\t\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\n\t\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\t\tfile.write(st+\",Negative\\n\")\n\n\t\t\t\t\tfileA.write(st+\",Negative\\n\")\n\t\t\t\t\tif index not in mispercieved[keys[i]]:\n\t\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\t\tif k == 0:\n\t\t\tfile.close()\n\t\t\tfile = open(\"NN_SVMData/EmotionDataRandomAll.csv\",\"w\")\n\t\t\tfileP.close()\n\t\t\tfileP = open(\"NN_SVMData/EmotionDataRandomPercievedAll.csv\",\"w\")\n\t\t\tAOIfile.close()\n\t\t\tAOIfile = open(\"AOIMetricsRandom.csv\",\"r\")\n\t\t\tfor element in attributes:\n\t\t\t\tif element != \"class\":\n\t\t\t\t\tfile.write(element+\",\")\n\t\t\t\t\tfileP.write(element+\",\")\n\t\t\t\telse:\n\t\t\t\t\tfile.write(element)\n\t\t\t\t\tfileP.write(element)\n\t\t\tmispercieved = mispercievedRan\n\t\t\tkeys = list(mispercieved.keys())\n\t\t\tfile.write(\"\\n\")\n\t\t\tfileP.write(\"\\n\")\n\n\n\tfileA.close()\n\tfile.close()\n\tfileP.close()\n\tAOIfile.close()\n\t\n\n#Make Weka dataset for simple labels, positive, negative neutral emotions\ndef simpleData(num_testers,type,mispercieved):\n\tAOIfile=open(\"AOIMetrics\"+type+\".csv\",\"r\")\n\tfileP = open(\"WekaData/Weka\"+type+\"PercievedAllSimple.arff\",\"w\")\n\tfile = open(\"WekaData/Weka\"+type+\"AllSimple.arff\",\"w\")\n\tattributes = [\"AU1\",\"AU2\",\"AU4\",\"AU6\",\"AU7\",\"AU9\",\"AU12\",\"AU15\",\"AU16\",\"AU20\",\"AU23\",\"AU26\",\"Left\",\"Lower\",\"Right\",\"Upper\",\"class\"]\n\tfile.write(\"@relation emotion\\n\")\n\tfileP.write(\"@relation emotion\\n\")\n\tfileP.write(\"\\n\")\n\tfile.write(\"\\n\")\n\n\t#Write the attributes in the correct format\n\tfor i in range(len(attributes)-1):\n\t\tfile.write(\"@attribute \"+attributes[i]+\" numeric\\n\")\n\t\tfileP.write(\"@attribute \"+attributes[i]+\" numeric\\n\")\n\n\tfile.write(\"@attribute \"+attributes[len(attributes)-1]+\"{Positive,Negative,Neutral}\\n\")\n\tfileP.write(\"@attribute \"+attributes[len(attributes)-1]+\"{Positive,Negative,Neutral}\\n\")\n\n\tfile.write(\"\\n@data\\n\")\n\tfileP.write(\"\\n@data\\n\")\n\tk = list(mispercieved.keys())\n\n\tdone = False\n\tindex = 0\n\twhile not done:\n\t\t\n\t\tline = AOIfile.readline() \n\t\tif line == \"\":\n\t\t\tbreak\n\t\tif \"_DIS_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\n\t\t\tfor i in range(num_testers): \n\t\t\t\ttemp = [0]*16\n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Negative\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\t\telif \"_HAP_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Positive\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Positive\\n\")\n\n\t\telif \"_ANG_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers): \n\t\t\t\ttemp = [0]*16\n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Negative\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\t\telif \"_FEA_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Negative\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\t\telif \"_NEU_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Neutral\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Neutral\\n\")\n\n\t\telif \"_SAD_\" in line:\n\t\t\tindex += 1\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Negative\\n\")\n\t\t\t\tif index not in mispercieved[k[i]]:\n\t\t\t\t\tfileP.write(st+\",Negative\\n\")\n\n\n\tfile.close()\n\tfileP.close()\n\tAOIfile.close()\n\n#Makes weka dataset for all testers, but not pooled\ndef AllData(num_testers,type):\n\tAOIfile=open(\"AOIMetrics\"+type+\".csv\",\"r\")\n\tfile = open(\"WekaData/Weka\"+type+\"All.arff\",\"w\")\n\tattributes = [\"AU1\",\"AU2\",\"AU4\",\"AU6\",\"AU7\",\"AU9\",\"AU12\",\"AU15\",\"AU16\",\"AU20\",\"AU23\",\"AU26\",\"Left\",\"Lower\",\"Right\",\"Upper\",\"class\"]\n\tfile.write(\"@relation emotion\\n\")\n\tfile.write(\"\\n\")\n\n\t#Write the attributes in the correct format\n\tfor i in range(len(attributes)-1):\n\t\tfile.write(\"@attribute \"+attributes[i]+\" numeric\\n\")\n\n\tfile.write(\"@attribute \"+attributes[len(attributes)-1]+\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\\n\")\n\n\tfile.write(\"\\n@data\\n\")\n\n\tdone = False\n\twhile not done:\n\t\tline = AOIfile.readline() \n\t\tif line == \"\":\n\t\t\tbreak\n\t\tif \"_DIS_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\tfor i in range(num_testers): \n\t\t\t\ttemp = [0]*16\n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Disgust\\n\")\n\t\t\t\n\n\t\telif \"_HAP_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Happy\\n\")\n\n\t\telif \"_ANG_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers): \n\t\t\t\ttemp = [0]*16\n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Angry\\n\")\n\n\t\telif \"_FEA_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Fear\\n\")\n\n\t\telif \"_NEU_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Neutral\\n\")\n\n\t\telif \"_SAD_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\t\n\t\t\tfor i in range(num_testers):\n\t\t\t\ttemp = [0]*16 \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Sad\\n\")\n\n\n\tfile.close()\n\tAOIfile.close()\n\n\n#Does it for all testers pooled\ndef testerData(num_testers,type):\n\tAOIfile=open(\"AOIMetrics\"+type+\".csv\",\"r\")\n\tfor k in range(num_testers):\n\t\tAOIfile.seek(0)\n\t\tfile = open(\"WekaData/Weka\"+type+\"Tester\"+str(k+1)+\".arff\",\"w\")\n\t\tattributes = [\"AU1\",\"AU2\",\"AU4\",\"AU6\",\"AU7\",\"AU9\",\"AU12\",\"AU15\",\"AU16\",\"AU20\",\"AU23\",\"AU26\",\"Left\",\"Lower\",\"Right\",\"Upper\",\"class\"]\n\t\tfile.write(\"@relation emotion\\n\")\n\t\tfile.write(\"\\n\")\n\n\t\tfor i in range(len(attributes)-1):\n\t\t\tfile.write(\"@attribute \"+attributes[i]+\" numeric\\n\")\n\n\t\tfile.write(\"@attribute \"+attributes[len(attributes)-1]+\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\\n\")\n\n\t\tfile.write(\"\\n@data\\n\")\n\t\tdone = False\n\t\twhile not done:\n\t\t\tline = AOIfile.readline() \n\t\t\tif line == \"\":\n\t\t\t\tbreak\n\t\t\tif \"_DIS_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Disgust\\n\")\n\n\t\t\telif \"_HAP_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Happy\\n\")\n\n\t\t\telif \"_ANG_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Angry\\n\")\n\n\t\t\telif \"_FEA_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Fear\\n\")\n\n\t\t\telif \"_NEU_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Neutral\\n\")\n\n\t\t\telif \"_SAD_\" in line:\n\t\t\t\tline = AOIfile.readline()\n\t\t\t\ttemp = [0]*16\n\t\t\t\tfor i in range(k+1): \n\t\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\t\tfile.write(st+\",Sad\\n\")\n\t\tfile.close()\n\tAOIfile.close()\n\n\n#Writes to a file a arff file that pools all data between testers\ndef PooledData(num_testers,type):\n\tAOIfile=open(\"AOIMetrics\"+type+\".csv\",\"r\")\n\tfile = open(\"WekaData/Weka\"+type+\"Pooled.arff\",\"w\")\n\tattributes = [\"AU1\",\"AU2\",\"AU4\",\"AU6\",\"AU7\",\"AU9\",\"AU12\",\"AU15\",\"AU16\",\"AU20\",\"AU23\",\"AU26\",\"Left\",\"Lower\",\"Right\",\"Upper\",\"class\"]\n\tfile.write(\"@relation emotion\\n\")\n\tfile.write(\"\\n\")\n\n\t#Write the attributes in the correct format\n\tfor i in range(len(attributes)-1):\n\t\tfile.write(\"@attribute \"+attributes[i]+\" numeric\\n\")\n\n\tfile.write(\"@attribute \"+attributes[len(attributes)-1]+\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\\n\")\n\n\tfile.write(\"\\n@data\\n\")\n\n\tdone = False\n\twhile not done:\n\t\tline = AOIfile.readline() \n\t\tif line == \"\":\n\t\t\tbreak\n\t\tif \"_DIS_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Disgust\\n\")\n\n\t\telif \"_HAP_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Happy\\n\")\n\n\t\telif \"_ANG_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Angry\\n\")\n\n\t\telif \"_FEA_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Fear\\n\")\n\n\t\telif \"_NEU_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Neutral\\n\")\n\n\t\telif \"_SAD_\" in line:\n\t\t\tline = AOIfile.readline()\n\t\t\ttemp = [0]*16\n\t\t\tfor i in range(num_testers): \n\t\t\t\tline=AOIfile.readline()\n\t\t\t\tpart = line.split(\",\")\n\t\t\t\tfor j in range(16):\n\t\t\t\t\tif part[j+2] != \"\" and part[j+2] != \"\\n\":\n\t\t\t\t\t\ttemp[j] += float(part[j+2])\n\t\t\tst = ','.join(str(e) for e in temp)\n\t\t\tfile.write(st+\",Sad\\n\")\n\n\n\tfile.close()\n\tAOIfile.close()\n\n\ndef main():\n\tmispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76, 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26, 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74, 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20, 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57, 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92], 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54], 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72], 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2, 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46, 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2, 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70, 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12, 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78, 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24, 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75, 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45, 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92], 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52, 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72, 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36, 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88, 89, 91, 92],'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46, 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10, 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70, 72, 74, 75, 78, 80, 81, 83, 88, 92]}\t\n\tPooledData(18,\"Sequential\")\n\ttesterData(18,\"Sequential\")\n\tAllData(18,\"Sequential\")\n\tsimpleData(18,\"Sequential\",mispercievedSeq)\n\n\tmispercievedRan = { 'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72, 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64, 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21, 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59, 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93, 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117], 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29, 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76, 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65, 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106, 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19, 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63, 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103, 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14, 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54, 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100, 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116], 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86, 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116], 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89, 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117], 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65, 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, 105, 108, 109, 113, 115, 117],'Tester1': [6, 7, 8, 9, 10, 14, 15, 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50, 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92, 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26, 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57, 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105, 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14, 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54, 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101, 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117], 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76, 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32, 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95, 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66, 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26, 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86, 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19, 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71, 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}\n\tPooledData(18,\"Random\")\n\ttesterData(18,\"Random\")\n\tAllData(18,\"Random\")\n\tsimpleData(18,\"Random\",mispercievedRan)\n\t\n\tNNDataSet(18,mispercievedSeq,mispercievedRan)\n\nmain()",
"def NNDataSet(num_testers, mispercievedSeq, mispercievedRan):\n AOIfile = open('AOIMetricsSequential.csv', 'r')\n file = open('NN_SVMData/EmotionDataSequentialAll.csv', 'w')\n fileP = open('NN_SVMData/EmotionDataSequentialPercievedAll.csv', 'w')\n fileA = open('NN_SVMData/EmotionDataAll.csv', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n mispercieved = mispercievedSeq\n keys = list(mispercieved.keys())\n for element in attributes:\n if element != 'class':\n fileA.write(element + ',')\n else:\n fileA.write(element)\n fileA.write('\\n')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n file.write('\\n')\n fileP.write('\\n')\n for k in range(2):\n index = 0\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n fileA.write(st + ',Positive\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Positive\\n')\n if '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n fileA.write(st + ',Neutral\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Neutral\\n')\n if '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if k == 0:\n file.close()\n file = open('NN_SVMData/EmotionDataRandomAll.csv', 'w')\n fileP.close()\n fileP = open('NN_SVMData/EmotionDataRandomPercievedAll.csv', 'w')\n AOIfile.close()\n AOIfile = open('AOIMetricsRandom.csv', 'r')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n mispercieved = mispercievedRan\n keys = list(mispercieved.keys())\n file.write('\\n')\n fileP.write('\\n')\n fileA.close()\n file.close()\n fileP.close()\n AOIfile.close()\n\n\ndef simpleData(num_testers, type, mispercieved):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n fileP = open('WekaData/Weka' + type + 'PercievedAllSimple.arff', 'w')\n file = open('WekaData/Weka' + type + 'AllSimple.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n fileP.write('@relation emotion\\n')\n fileP.write('\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n fileP.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n fileP.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n file.write('\\n@data\\n')\n fileP.write('\\n@data\\n')\n k = list(mispercieved.keys())\n done = False\n index = 0\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Positive\\n')\n elif '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n file.close()\n fileP.close()\n AOIfile.close()\n\n\ndef AllData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'All.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef main():\n mispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, \n 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76,\n 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26,\n 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74,\n 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20,\n 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57,\n 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92],\n 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54],\n 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72],\n 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, \n 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2,\n 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46,\n 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2,\n 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, \n 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, \n 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70,\n 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12,\n 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78,\n 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24,\n 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75,\n 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45,\n 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92],\n 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52,\n 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, \n 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72,\n 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, \n 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, \n 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36,\n 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61,\n 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88,\n 89, 91, 92], 'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46,\n 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10,\n 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70,\n 72, 74, 75, 78, 80, 81, 83, 88, 92]}\n PooledData(18, 'Sequential')\n testerData(18, 'Sequential')\n AllData(18, 'Sequential')\n simpleData(18, 'Sequential', mispercievedSeq)\n mispercievedRan = {'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, \n 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72,\n 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, \n 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, \n 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64,\n 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, \n 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21,\n 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59,\n 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93,\n 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117],\n 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29,\n 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76,\n 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, \n 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, \n 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65,\n 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106,\n 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19,\n 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63,\n 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103,\n 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14,\n 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54,\n 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100,\n 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116],\n 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, \n 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86,\n 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116],\n 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, \n 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89,\n 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117],\n 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, \n 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65,\n 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, \n 105, 108, 109, 113, 115, 117], 'Tester1': [6, 7, 8, 9, 10, 14, 15, \n 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50,\n 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92,\n 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, \n 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26,\n 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57,\n 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105,\n 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14,\n 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54,\n 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101,\n 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117],\n 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, \n 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76,\n 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, \n 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32,\n 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95,\n 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, \n 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33,\n 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66,\n 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95,\n 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, \n 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26,\n 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86,\n 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, \n 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19,\n 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71,\n 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}\n PooledData(18, 'Random')\n testerData(18, 'Random')\n AllData(18, 'Random')\n simpleData(18, 'Random', mispercievedRan)\n NNDataSet(18, mispercievedSeq, mispercievedRan)\n\n\nmain()\n",
"def NNDataSet(num_testers, mispercievedSeq, mispercievedRan):\n AOIfile = open('AOIMetricsSequential.csv', 'r')\n file = open('NN_SVMData/EmotionDataSequentialAll.csv', 'w')\n fileP = open('NN_SVMData/EmotionDataSequentialPercievedAll.csv', 'w')\n fileA = open('NN_SVMData/EmotionDataAll.csv', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n mispercieved = mispercievedSeq\n keys = list(mispercieved.keys())\n for element in attributes:\n if element != 'class':\n fileA.write(element + ',')\n else:\n fileA.write(element)\n fileA.write('\\n')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n file.write('\\n')\n fileP.write('\\n')\n for k in range(2):\n index = 0\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n fileA.write(st + ',Positive\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Positive\\n')\n if '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n fileA.write(st + ',Neutral\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Neutral\\n')\n if '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if k == 0:\n file.close()\n file = open('NN_SVMData/EmotionDataRandomAll.csv', 'w')\n fileP.close()\n fileP = open('NN_SVMData/EmotionDataRandomPercievedAll.csv', 'w')\n AOIfile.close()\n AOIfile = open('AOIMetricsRandom.csv', 'r')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n mispercieved = mispercievedRan\n keys = list(mispercieved.keys())\n file.write('\\n')\n fileP.write('\\n')\n fileA.close()\n file.close()\n fileP.close()\n AOIfile.close()\n\n\ndef simpleData(num_testers, type, mispercieved):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n fileP = open('WekaData/Weka' + type + 'PercievedAllSimple.arff', 'w')\n file = open('WekaData/Weka' + type + 'AllSimple.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n fileP.write('@relation emotion\\n')\n fileP.write('\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n fileP.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n fileP.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n file.write('\\n@data\\n')\n fileP.write('\\n@data\\n')\n k = list(mispercieved.keys())\n done = False\n index = 0\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Positive\\n')\n elif '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n file.close()\n fileP.close()\n AOIfile.close()\n\n\ndef AllData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'All.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef main():\n mispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, \n 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76,\n 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26,\n 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74,\n 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20,\n 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57,\n 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92],\n 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54],\n 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72],\n 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, \n 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2,\n 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46,\n 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2,\n 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, \n 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, \n 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70,\n 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12,\n 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78,\n 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24,\n 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75,\n 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45,\n 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92],\n 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52,\n 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, \n 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72,\n 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, \n 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, \n 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36,\n 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61,\n 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88,\n 89, 91, 92], 'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46,\n 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10,\n 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70,\n 72, 74, 75, 78, 80, 81, 83, 88, 92]}\n PooledData(18, 'Sequential')\n testerData(18, 'Sequential')\n AllData(18, 'Sequential')\n simpleData(18, 'Sequential', mispercievedSeq)\n mispercievedRan = {'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, \n 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72,\n 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, \n 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, \n 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64,\n 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, \n 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21,\n 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59,\n 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93,\n 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117],\n 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29,\n 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76,\n 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, \n 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, \n 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65,\n 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106,\n 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19,\n 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63,\n 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103,\n 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14,\n 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54,\n 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100,\n 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116],\n 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, \n 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86,\n 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116],\n 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, \n 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89,\n 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117],\n 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, \n 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65,\n 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, \n 105, 108, 109, 113, 115, 117], 'Tester1': [6, 7, 8, 9, 10, 14, 15, \n 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50,\n 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92,\n 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, \n 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26,\n 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57,\n 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105,\n 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14,\n 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54,\n 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101,\n 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117],\n 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, \n 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76,\n 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, \n 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32,\n 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95,\n 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, \n 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33,\n 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66,\n 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95,\n 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, \n 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26,\n 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86,\n 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, \n 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19,\n 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71,\n 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}\n PooledData(18, 'Random')\n testerData(18, 'Random')\n AllData(18, 'Random')\n simpleData(18, 'Random', mispercievedRan)\n NNDataSet(18, mispercievedSeq, mispercievedRan)\n\n\n<code token>\n",
"def NNDataSet(num_testers, mispercievedSeq, mispercievedRan):\n AOIfile = open('AOIMetricsSequential.csv', 'r')\n file = open('NN_SVMData/EmotionDataSequentialAll.csv', 'w')\n fileP = open('NN_SVMData/EmotionDataSequentialPercievedAll.csv', 'w')\n fileA = open('NN_SVMData/EmotionDataAll.csv', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n mispercieved = mispercievedSeq\n keys = list(mispercieved.keys())\n for element in attributes:\n if element != 'class':\n fileA.write(element + ',')\n else:\n fileA.write(element)\n fileA.write('\\n')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n file.write('\\n')\n fileP.write('\\n')\n for k in range(2):\n index = 0\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n fileA.write(st + ',Positive\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Positive\\n')\n if '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n fileA.write(st + ',Neutral\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Neutral\\n')\n if '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n fileA.write(st + ',Negative\\n')\n if index not in mispercieved[keys[i]]:\n fileP.write(st + ',Negative\\n')\n if k == 0:\n file.close()\n file = open('NN_SVMData/EmotionDataRandomAll.csv', 'w')\n fileP.close()\n fileP = open('NN_SVMData/EmotionDataRandomPercievedAll.csv', 'w')\n AOIfile.close()\n AOIfile = open('AOIMetricsRandom.csv', 'r')\n for element in attributes:\n if element != 'class':\n file.write(element + ',')\n fileP.write(element + ',')\n else:\n file.write(element)\n fileP.write(element)\n mispercieved = mispercievedRan\n keys = list(mispercieved.keys())\n file.write('\\n')\n fileP.write('\\n')\n fileA.close()\n file.close()\n fileP.close()\n AOIfile.close()\n\n\ndef simpleData(num_testers, type, mispercieved):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n fileP = open('WekaData/Weka' + type + 'PercievedAllSimple.arff', 'w')\n file = open('WekaData/Weka' + type + 'AllSimple.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n fileP.write('@relation emotion\\n')\n fileP.write('\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n fileP.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n fileP.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n file.write('\\n@data\\n')\n fileP.write('\\n@data\\n')\n k = list(mispercieved.keys())\n done = False\n index = 0\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Positive\\n')\n elif '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n file.close()\n fileP.close()\n AOIfile.close()\n\n\n<function token>\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef main():\n mispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, \n 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76,\n 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26,\n 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74,\n 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20,\n 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57,\n 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92],\n 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54],\n 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72],\n 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, \n 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2,\n 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46,\n 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2,\n 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, \n 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, \n 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70,\n 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12,\n 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78,\n 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24,\n 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75,\n 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45,\n 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92],\n 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52,\n 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, \n 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72,\n 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, \n 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, \n 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36,\n 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61,\n 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88,\n 89, 91, 92], 'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46,\n 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10,\n 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70,\n 72, 74, 75, 78, 80, 81, 83, 88, 92]}\n PooledData(18, 'Sequential')\n testerData(18, 'Sequential')\n AllData(18, 'Sequential')\n simpleData(18, 'Sequential', mispercievedSeq)\n mispercievedRan = {'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, \n 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72,\n 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, \n 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, \n 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64,\n 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, \n 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21,\n 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59,\n 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93,\n 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117],\n 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29,\n 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76,\n 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, \n 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, \n 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65,\n 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106,\n 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19,\n 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63,\n 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103,\n 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14,\n 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54,\n 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100,\n 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116],\n 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, \n 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86,\n 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116],\n 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, \n 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89,\n 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117],\n 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, \n 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65,\n 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, \n 105, 108, 109, 113, 115, 117], 'Tester1': [6, 7, 8, 9, 10, 14, 15, \n 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50,\n 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92,\n 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, \n 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26,\n 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57,\n 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105,\n 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14,\n 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54,\n 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101,\n 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117],\n 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, \n 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76,\n 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, \n 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32,\n 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95,\n 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, \n 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33,\n 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66,\n 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95,\n 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, \n 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26,\n 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86,\n 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, \n 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19,\n 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71,\n 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}\n PooledData(18, 'Random')\n testerData(18, 'Random')\n AllData(18, 'Random')\n simpleData(18, 'Random', mispercievedRan)\n NNDataSet(18, mispercievedSeq, mispercievedRan)\n\n\n<code token>\n",
"<function token>\n\n\ndef simpleData(num_testers, type, mispercieved):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n fileP = open('WekaData/Weka' + type + 'PercievedAllSimple.arff', 'w')\n file = open('WekaData/Weka' + type + 'AllSimple.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n fileP.write('@relation emotion\\n')\n fileP.write('\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n fileP.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n fileP.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n file.write('\\n@data\\n')\n fileP.write('\\n@data\\n')\n k = list(mispercieved.keys())\n done = False\n index = 0\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Positive\\n')\n elif '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n file.close()\n fileP.close()\n AOIfile.close()\n\n\n<function token>\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef main():\n mispercievedSeq = {'Participant1': [1, 2, 3, 6, 8, 10, 12, 15, 16, 22, \n 24, 26, 30, 37, 39, 45, 46, 48, 49, 52, 55, 63, 70, 72, 74, 75, 76,\n 78, 80, 83, 87, 88, 92], 'Participant2': [5, 9, 10, 15, 20, 22, 26,\n 31, 32, 33, 39, 42, 45, 48, 49, 51, 52, 59, 63, 67, 69, 71, 72, 74,\n 75, 78, 79, 80, 81, 92], 'Participant3': [1, 6, 10, 15, 16, 17, 20,\n 21, 23, 24, 27, 29, 33, 35, 39, 41, 42, 45, 46, 49, 52, 54, 55, 57,\n 58, 60, 64, 65, 68, 69, 70, 71, 74, 78, 83, 86, 88, 92],\n 'Participant4': [9, 10, 22, 24, 26, 27, 30, 42, 48, 52, 54],\n 'Participant5': [4, 20, 22, 23, 46, 52, 53, 55, 66, 72],\n 'Participant6': [5, 9, 12, 15, 24, 27, 30, 33, 39, 48, 51, 52, 54, \n 55, 58, 60, 63, 72, 74, 75, 78, 81, 83, 88, 92], 'Participant7': [2,\n 3, 5, 6, 9, 12, 15, 16, 20, 21, 22, 24, 26, 27, 30, 32, 42, 45, 46,\n 52, 57, 62, 70, 72, 74, 75, 78, 81, 83, 91, 92], 'Participant8': [2,\n 4, 5, 20, 23, 26, 27, 33, 36, 40, 42, 45, 46, 48, 49, 51, 52, 55, \n 70, 72, 78, 92], 'Participant9': [2, 6, 9, 12, 15, 17, 22, 24, 27, \n 28, 29, 30, 33, 39, 40, 42, 45, 46, 48, 49, 51, 56, 57, 66, 69, 70,\n 72, 74, 78, 81, 83, 84, 88, 92], 'Participant10': [1, 6, 7, 10, 12,\n 15, 20, 22, 29, 30, 32, 33, 41, 42, 45, 48, 51, 63, 68, 69, 72, 78,\n 80, 83, 86, 88, 89, 91, 92], 'Tester1': [1, 2, 6, 9, 12, 15, 17, 24,\n 26, 27, 30, 33, 40, 42, 45, 46, 47, 48, 51, 52, 58, 59, 72, 74, 75,\n 78], 'Tester2': [10, 20, 22, 24, 26, 27, 30, 32, 33, 40, 42, 44, 45,\n 46, 48, 49, 52, 56, 57, 58, 70, 72, 74, 75, 78, 81, 91, 92],\n 'Tester3': [5, 6, 8, 15, 20, 24, 26, 30, 40, 42, 45, 46, 48, 49, 52,\n 70, 72, 76, 78, 80, 89], 'Tester4': [4, 5, 6, 12, 17, 21, 24, 26, \n 27, 29, 30, 33, 39, 40, 42, 45, 46, 48, 51, 52, 58, 59, 62, 70, 72,\n 78, 83, 86, 92], 'Tester5': [2, 6, 20, 22, 23, 24, 29, 41, 46, 47, \n 48, 54, 55, 58, 66, 70, 77, 78, 80], 'Tester6': [2, 3, 5, 6, 8, 9, \n 10, 11, 12, 13, 14, 15, 16, 18, 21, 23, 24, 27, 29, 30, 32, 33, 36,\n 39, 40, 42, 45, 46, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61,\n 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 81, 84, 88,\n 89, 91, 92], 'Participant11': [2, 3, 10, 11, 12, 24, 33, 40, 45, 46,\n 48, 50, 51, 52, 54, 56, 72, 76, 78, 89], 'Participant12': [3, 9, 10,\n 15, 20, 21, 22, 24, 25, 26, 29, 33, 45, 46, 47, 48, 52, 54, 58, 70,\n 72, 74, 75, 78, 80, 81, 83, 88, 92]}\n PooledData(18, 'Sequential')\n testerData(18, 'Sequential')\n AllData(18, 'Sequential')\n simpleData(18, 'Sequential', mispercievedSeq)\n mispercievedRan = {'Participant1': [5, 7, 12, 14, 16, 19, 20, 26, 27, \n 28, 29, 31, 32, 33, 35, 44, 45, 46, 47, 50, 55, 58, 64, 65, 67, 72,\n 74, 76, 81, 83, 86, 87, 90, 92, 99, 104, 105, 106, 109, 110, 111, \n 112, 113, 114, 116, 117], 'Participant2': [8, 13, 15, 17, 19, 21, \n 24, 26, 27, 28, 29, 32, 35, 39, 44, 45, 46, 47, 49, 54, 58, 59, 64,\n 65, 67, 74, 76, 77, 78, 82, 86, 88, 90, 91, 93, 99, 100, 105, 106, \n 109, 112, 113, 116], 'Participant3': [7, 9, 12, 13, 14, 15, 19, 21,\n 24, 26, 27, 28, 31, 32, 33, 39, 43, 44, 45, 47, 50, 55, 57, 58, 59,\n 63, 64, 65, 66, 67, 68, 69, 70, 71, 74, 76, 81, 85, 86, 88, 89, 93,\n 95, 96, 99, 100, 103, 105, 106, 109, 110, 111, 114, 115, 117],\n 'Participant4': [1, 12, 13, 14, 15, 17, 18, 19, 21, 26, 27, 28, 29,\n 33, 34, 35, 40, 44, 45, 46, 47, 52, 54, 58, 59, 64, 65, 66, 72, 76,\n 80, 81, 83, 87, 88, 92, 93, 95, 99, 101, 104, 105, 106, 108, 109, \n 110, 111, 113, 114], 'Participant5': [1, 4, 5, 12, 13, 16, 19, 21, \n 26, 27, 31, 32, 33, 35, 44, 45, 46, 47, 50, 54, 57, 58, 59, 64, 65,\n 66, 67, 69, 76, 81, 86, 88, 89, 90, 93, 94, 99, 101, 104, 105, 106,\n 107, 109, 110, 112, 114, 116], 'Participant6': [4, 5, 7, 8, 15, 19,\n 21, 26, 28, 29, 31, 32, 33, 35, 38, 45, 47, 49, 50, 55, 58, 61, 63,\n 64, 65, 66, 67, 68, 74, 76, 81, 82, 88, 89, 90, 93, 95, 98, 99, 103,\n 104, 105, 106, 109, 110, 112, 115, 116], 'Participant7': [7, 8, 14,\n 19, 20, 21, 22, 26, 28, 32, 33, 35, 40, 44, 45, 46, 47, 50, 52, 54,\n 56, 58, 59, 64, 65, 67, 72, 76, 79, 80, 81, 83, 90, 93, 94, 99, 100,\n 101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116],\n 'Participant8': [1, 4, 5, 13, 14, 16, 19, 25, 26, 27, 28, 32, 33, \n 39, 40, 45, 46, 47, 50, 54, 55, 57, 58, 64, 67, 76, 81, 83, 85, 86,\n 88, 89, 93, 95, 99, 102, 105, 106, 107, 109, 110, 114, 116],\n 'Participant9': [2, 6, 9, 13, 19, 21, 26, 28, 29, 31, 32, 38, 44, \n 45, 46, 47, 50, 54, 57, 58, 59, 63, 65, 66, 67, 71, 76, 79, 87, 89,\n 90, 94, 95, 98, 99, 102, 104, 105, 109, 110, 112, 113, 115, 117],\n 'Participant10': [6, 8, 9, 10, 13, 14, 16, 17, 19, 21, 25, 26, 27, \n 28, 29, 31, 32, 33, 43, 45, 46, 47, 48, 54, 57, 58, 59, 63, 64, 65,\n 67, 69, 71, 74, 78, 79, 86, 89, 90, 93, 94, 98, 99, 101, 102, 104, \n 105, 108, 109, 113, 115, 117], 'Tester1': [6, 7, 8, 9, 10, 14, 15, \n 17, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 44, 45, 47, 50,\n 57, 58, 59, 60, 63, 64, 65, 66, 67, 68, 72, 76, 79, 81, 83, 88, 92,\n 94, 98, 99, 102, 103, 104, 105, 106, 107, 110, 111, 112, 113, 114, \n 115, 116, 117], 'Tester2': [5, 8, 9, 13, 14, 15, 16, 17, 19, 21, 26,\n 27, 28, 29, 31, 32, 34, 38, 39, 44, 45, 46, 47, 50, 52, 54, 55, 57,\n 58, 59, 64, 65, 69, 71, 76, 79, 81, 93, 98, 99, 101, 103, 104, 105,\n 106, 108, 109, 110, 111, 112, 116], 'Tester3': [1, 4, 5, 6, 13, 14,\n 19, 21, 26, 27, 28, 29, 31, 32, 33, 35, 38, 45, 46, 47, 50, 52, 54,\n 55, 57, 58, 59, 64, 65, 71, 74, 76, 83, 85, 88, 89, 93, 94, 99, 101,\n 102, 103, 104, 105, 106, 107, 109, 110, 112, 114, 115, 116, 117],\n 'Tester4': [1, 2, 4, 5, 7, 8, 12, 19, 21, 25, 26, 27, 28, 31, 32, \n 33, 36, 38, 44, 45, 46, 47, 50, 54, 55, 57, 58, 59, 65, 69, 71, 76,\n 79, 86, 87, 88, 89, 90, 94, 99, 100, 102, 105, 106, 107, 109, 110, \n 112, 114, 115], 'Tester5': [1, 2, 5, 7, 14, 16, 19, 26, 28, 29, 32,\n 35, 39, 44, 45, 46, 47, 50, 55, 58, 59, 64, 65, 71, 81, 93, 94, 95,\n 99, 104, 105, 109, 111, 116, 117], 'Tester6': [6, 7, 8, 9, 11, 12, \n 13, 14, 15, 18, 19, 20, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33,\n 35, 36, 37, 38, 39, 41, 43, 45, 46, 47, 48, 50, 55, 57, 60, 65, 66,\n 67, 70, 72, 76, 78, 79, 80, 81, 83, 85, 86, 87, 89, 92, 93, 94, 95,\n 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 111, 112, \n 113, 114, 115, 116], 'Participant11': [4, 5, 6, 10, 12, 14, 22, 26,\n 32, 33, 43, 45, 46, 54, 55, 56, 58, 65, 68, 76, 78, 79, 81, 83, 86,\n 87, 88, 90, 93, 94, 95, 98, 99, 101, 102, 103, 105, 106, 107, 109, \n 110, 112, 113, 114, 115, 116], 'Participant12': [2, 13, 14, 16, 19,\n 21, 27, 28, 29, 31, 32, 43, 45, 46, 47, 52, 54, 55, 56, 58, 64, 71,\n 79, 80, 81, 83, 90, 94, 99, 101, 104, 107, 109, 112, 113, 114, 116]}\n PooledData(18, 'Random')\n testerData(18, 'Random')\n AllData(18, 'Random')\n simpleData(18, 'Random', mispercievedRan)\n NNDataSet(18, mispercievedSeq, mispercievedRan)\n\n\n<code token>\n",
"<function token>\n\n\ndef simpleData(num_testers, type, mispercieved):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n fileP = open('WekaData/Weka' + type + 'PercievedAllSimple.arff', 'w')\n file = open('WekaData/Weka' + type + 'AllSimple.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n fileP.write('@relation emotion\\n')\n fileP.write('\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n fileP.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n fileP.write('@attribute ' + attributes[len(attributes) - 1] +\n '{Positive,Negative,Neutral}\\n')\n file.write('\\n@data\\n')\n fileP.write('\\n@data\\n')\n k = list(mispercieved.keys())\n done = False\n index = 0\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_HAP_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Positive\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Positive\\n')\n elif '_ANG_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_FEA_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n elif '_NEU_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n index += 1\n line = AOIfile.readline()\n for i in range(num_testers):\n temp = [0] * 16\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Negative\\n')\n if index not in mispercieved[k[i]]:\n fileP.write(st + ',Negative\\n')\n file.close()\n fileP.close()\n AOIfile.close()\n\n\n<function token>\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\n<function token>\n<code token>\n",
"<function token>\n<function token>\n<function token>\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\ndef PooledData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n file = open('WekaData/Weka' + type + 'Pooled.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12', 'AU15',\n 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower', 'Right', 'Upper',\n 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(num_testers):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\n<function token>\n<code token>\n",
"<function token>\n<function token>\n<function token>\n\n\ndef testerData(num_testers, type):\n AOIfile = open('AOIMetrics' + type + '.csv', 'r')\n for k in range(num_testers):\n AOIfile.seek(0)\n file = open('WekaData/Weka' + type + 'Tester' + str(k + 1) +\n '.arff', 'w')\n attributes = ['AU1', 'AU2', 'AU4', 'AU6', 'AU7', 'AU9', 'AU12',\n 'AU15', 'AU16', 'AU20', 'AU23', 'AU26', 'Left', 'Lower',\n 'Right', 'Upper', 'class']\n file.write('@relation emotion\\n')\n file.write('\\n')\n for i in range(len(attributes) - 1):\n file.write('@attribute ' + attributes[i] + ' numeric\\n')\n file.write('@attribute ' + attributes[len(attributes) - 1] +\n \"\"\" {Angry,Sad,Happy,Disgust,Neutral,Fear}\n\"\"\")\n file.write('\\n@data\\n')\n done = False\n while not done:\n line = AOIfile.readline()\n if line == '':\n break\n if '_DIS_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Disgust\\n')\n elif '_HAP_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Happy\\n')\n elif '_ANG_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Angry\\n')\n elif '_FEA_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Fear\\n')\n elif '_NEU_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Neutral\\n')\n elif '_SAD_' in line:\n line = AOIfile.readline()\n temp = [0] * 16\n for i in range(k + 1):\n line = AOIfile.readline()\n part = line.split(',')\n for j in range(16):\n if part[j + 2] != '' and part[j + 2] != '\\n':\n temp[j] += float(part[j + 2])\n st = ','.join(str(e) for e in temp)\n file.write(st + ',Sad\\n')\n file.close()\n AOIfile.close()\n\n\n<function token>\n<function token>\n<code 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,941 | 2ce0664d4e0f8860873e7d894279ce767377328e | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect
from web.wxtranstypes.utils import utils_show_transtypes
mod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes')
@mod.route('/show_transtypes', methods=['POST'])
def views_show_transtypes():
req_data = request.get_data()
result = {'data': {}, 'code': 500}
if req_data:
data = json.loads(req_data.decode('utf-8'))
result['data'] = utils_show_transtypes(data)
result['code'] = 200
return json.dumps(result)
@mod.route('/add_transtypes', methods=['POST'])
def views_add_transtypes():
pass
@mod.route('/update_transtypes', methods=['POST'])
def views_update_transtypes():
pass
@mod.route('/delete_transtypes', methods=['POST'])
def views_delete_transtypes():
pass
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\nfrom flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect\nfrom web.wxtranstypes.utils import utils_show_transtypes\n\nmod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes')\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n@mod.route('/add_transtypes', methods=['POST'])\ndef views_add_transtypes():\n pass\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n@mod.route('/delete_transtypes', methods=['POST'])\ndef views_delete_transtypes():\n pass\n",
"import json\nfrom flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect\nfrom web.wxtranstypes.utils import utils_show_transtypes\nmod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes')\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n@mod.route('/add_transtypes', methods=['POST'])\ndef views_add_transtypes():\n pass\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n@mod.route('/delete_transtypes', methods=['POST'])\ndef views_delete_transtypes():\n pass\n",
"<import token>\nmod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes')\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n@mod.route('/add_transtypes', methods=['POST'])\ndef views_add_transtypes():\n pass\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n@mod.route('/delete_transtypes', methods=['POST'])\ndef views_delete_transtypes():\n pass\n",
"<import token>\n<assignment token>\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n@mod.route('/add_transtypes', methods=['POST'])\ndef views_add_transtypes():\n pass\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n@mod.route('/delete_transtypes', methods=['POST'])\ndef views_delete_transtypes():\n pass\n",
"<import token>\n<assignment token>\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n@mod.route('/add_transtypes', methods=['POST'])\ndef views_add_transtypes():\n pass\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n<function token>\n",
"<import token>\n<assignment token>\n\n\n@mod.route('/show_transtypes', methods=['POST'])\ndef views_show_transtypes():\n req_data = request.get_data()\n result = {'data': {}, 'code': 500}\n if req_data:\n data = json.loads(req_data.decode('utf-8'))\n result['data'] = utils_show_transtypes(data)\n result['code'] = 200\n return json.dumps(result)\n\n\n<function token>\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n<function token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n\n\n@mod.route('/update_transtypes', methods=['POST'])\ndef views_update_transtypes():\n pass\n\n\n<function token>\n",
"<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,942 | 38fde5ecf1bf15d737e1a886c5dca0c1893fc149 | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from __future__ import unicode_literals
from django.db import models
from django import forms
from smart_selects.db_fields import ChainedManyToManyField
class NewResult(models.Model):
index = models.BigIntegerField(blank=True,primary_key=True)
applied_school = models.TextField(db_column='Applied_School', blank=True, null=True) # Field name made lowercase.
degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.
major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.
result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.
year = models.TextField(db_column='Year', blank=True, null=True) # Field name made lowercase.
toefl = models.TextField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.
ielts = models.TextField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.
gre = models.TextField(db_column='GRE', blank=True, null=True) # Field name made lowercase.
school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.
school_major = models.TextField(db_column='School_Major', blank=True, null=True) # Field name made lowercase.
gpa = models.TextField(db_column='GPA', blank=True, null=True) # Field name made lowercase.
post_school = models.TextField(db_column='Post_School', blank=True, null=True) # Field name made lowercase.
post_major = models.TextField(db_column='Post_Major', blank=True, null=True) # Field name made lowercase.
post_gpa = models.TextField(db_column='Post_GPA', blank=True, null=True) # Field name made lowercase.
other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.
def __str__(self):
return "%d 学校:%s 申请专业:%s GPA:%.2f" %(self.index,self.applied_school,self.major,self.gpa)
class Meta:
managed = False
db_table = 'new_result'
class NewResultEqual(models.Model):
index = models.BigIntegerField(blank=True,primary_key=True)
appliedschool = models.TextField(db_column='AppliedSchool', blank=True, null=True) # Field name made lowercase.
degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.
major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.
result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.
year = models.BigIntegerField(db_column='Year', blank=True, null=True) # Field name made lowercase.
englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=True, null=True) # Field name made lowercase.
toefl = models.FloatField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.
ielts = models.FloatField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.
gre = models.BigIntegerField(db_column='GRE', blank=True, null=True) # Field name made lowercase.
school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.
schoolmajor = models.TextField(db_column='SchoolMajor', blank=True, null=True) # Field name made lowercase.
gpa = models.FloatField(db_column='GPA', blank=True, null=True) # Field name made lowercase.
postschool = models.TextField(db_column='PostSchool', blank=True, null=True) # Field name made lowercase.
postmajor = models.TextField(db_column='PostMajor', blank=True, null=True) # Field name made lowercase.
postgpa = models.TextField(db_column='PostGPA', blank=True, null=True) # Field name made lowercase.
other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.
def __str__(self):
return "%d 学校:%s 申请专业:%s GPA:%.2f" %(self.index,self.appliedschool,self.major,self.gpa)
class Meta:
managed = False
db_table = 'new_result_equal'
class NewResultMissing(models.Model):
index = models.BigIntegerField(blank=True,primary_key=True)
appliedschool = models.TextField(db_column='AppliedSchool', blank=True, null=True) # Field name made lowercase.
degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.
major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.
result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.
year = models.BigIntegerField(db_column='Year', blank=True, null=True) # Field name made lowercase.
englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=True, null=True) # Field name made lowercase.
toefl = models.FloatField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.
ielts = models.FloatField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.
gre = models.BigIntegerField(db_column='GRE', blank=True, null=True) # Field name made lowercase.
school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.
schoolmajor = models.TextField(db_column='SchoolMajor', blank=True, null=True) # Field name made lowercase.
gpa = models.FloatField(db_column='GPA', blank=True, null=True) # Field name made lowercase.
postschool = models.TextField(db_column='PostSchool', blank=True, null=True) # Field name made lowercase.
postmajor = models.TextField(db_column='PostMajor', blank=True, null=True) # Field name made lowercase.
postgpa = models.TextField(db_column='PostGPA', blank=True, null=True) # Field name made lowercase.
other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.
def __str__(self):
return "%d 学校:%s 申请专业:%s GPA:%.2f" %(self.index,self.appliedschool,self.major,self.gpa)
class Meta:
managed = False
db_table = 'new_result_missing'
# class ApplicationForm(forms.ModelForm):
# class Meta:
# model=NewResultEqual
# field=('appliedschool','major')
# class AppliedSchool(models.Model):
# name=models.CharField(max_length=255)
# class Major(models.Model):
# name=models.CharField(max_length=255)
# appliedschool=models.ForeignKey(AppliedSchool)
| [
"# This is an auto-generated Django model module.\n# You'll have to do the following manually to clean this up:\n# * Rearrange models' order\n# * Make sure each model has one field with primary_key=True\n# * Make sure each ForeignKey has `on_delete` set to the desired behavior.\n# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table\n# Feel free to rename the models, but don't rename db_table values or field names.\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django import forms\nfrom smart_selects.db_fields import ChainedManyToManyField\n\n\nclass NewResult(models.Model):\n index = models.BigIntegerField(blank=True,primary_key=True)\n applied_school = models.TextField(db_column='Applied_School', blank=True, null=True) # Field name made lowercase.\n degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.\n major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.\n result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.\n year = models.TextField(db_column='Year', blank=True, null=True) # Field name made lowercase.\n toefl = models.TextField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.\n ielts = models.TextField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.\n gre = models.TextField(db_column='GRE', blank=True, null=True) # Field name made lowercase.\n school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.\n school_major = models.TextField(db_column='School_Major', blank=True, null=True) # Field name made lowercase.\n gpa = models.TextField(db_column='GPA', blank=True, null=True) # Field name made lowercase.\n post_school = models.TextField(db_column='Post_School', blank=True, null=True) # Field name made lowercase.\n post_major = models.TextField(db_column='Post_Major', blank=True, null=True) # Field name made lowercase.\n post_gpa = models.TextField(db_column='Post_GPA', blank=True, null=True) # Field name made lowercase.\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.\n def __str__(self):\n return \"%d 学校:%s 申请专业:%s GPA:%.2f\" %(self.index,self.applied_school,self.major,self.gpa)\n\n class Meta:\n managed = False\n db_table = 'new_result'\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True,primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True, null=True) # Field name made lowercase.\n degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.\n major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.\n result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.\n year = models.BigIntegerField(db_column='Year', blank=True, null=True) # Field name made lowercase.\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=True, null=True) # Field name made lowercase.\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True) # Field name made lowercase.\n school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True, null=True) # Field name made lowercase.\n gpa = models.FloatField(db_column='GPA', blank=True, null=True) # Field name made lowercase.\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True) # Field name made lowercase.\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True) # Field name made lowercase.\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True) # Field name made lowercase.\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.\n def __str__(self):\n return \"%d 学校:%s 申请专业:%s GPA:%.2f\" %(self.index,self.appliedschool,self.major,self.gpa)\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True,primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True, null=True) # Field name made lowercase.\n degree = models.TextField(db_column='Degree', blank=True, null=True) # Field name made lowercase.\n major = models.TextField(db_column='Major', blank=True, null=True) # Field name made lowercase.\n result = models.TextField(db_column='Result', blank=True, null=True) # Field name made lowercase.\n year = models.BigIntegerField(db_column='Year', blank=True, null=True) # Field name made lowercase.\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=True, null=True) # Field name made lowercase.\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True) # Field name made lowercase.\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True) # Field name made lowercase.\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True) # Field name made lowercase.\n school = models.TextField(db_column='School', blank=True, null=True) # Field name made lowercase.\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True, null=True) # Field name made lowercase.\n gpa = models.FloatField(db_column='GPA', blank=True, null=True) # Field name made lowercase.\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True) # Field name made lowercase.\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True) # Field name made lowercase.\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True) # Field name made lowercase.\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True) # Field name made lowercase.\n def __str__(self):\n return \"%d 学校:%s 申请专业:%s GPA:%.2f\" %(self.index,self.appliedschool,self.major,self.gpa)\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n\n# class ApplicationForm(forms.ModelForm):\n# class Meta:\n# model=NewResultEqual\n# field=('appliedschool','major')\n\n# class AppliedSchool(models.Model):\n# name=models.CharField(max_length=255)\n\n# class Major(models.Model):\n# name=models.CharField(max_length=255)\n# appliedschool=models.ForeignKey(AppliedSchool)\n \n\n\n",
"from __future__ import unicode_literals\nfrom django.db import models\nfrom django import forms\nfrom smart_selects.db_fields import ChainedManyToManyField\n\n\nclass NewResult(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n applied_school = models.TextField(db_column='Applied_School', blank=\n True, null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.TextField(db_column='Year', blank=True, null=True)\n toefl = models.TextField(db_column='TOEFL', blank=True, null=True)\n ielts = models.TextField(db_column='IELTS', blank=True, null=True)\n gre = models.TextField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n school_major = models.TextField(db_column='School_Major', blank=True,\n null=True)\n gpa = models.TextField(db_column='GPA', blank=True, null=True)\n post_school = models.TextField(db_column='Post_School', blank=True,\n null=True)\n post_major = models.TextField(db_column='Post_Major', blank=True, null=True\n )\n post_gpa = models.TextField(db_column='Post_GPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n applied_school, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result'\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n\n\nclass NewResult(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n applied_school = models.TextField(db_column='Applied_School', blank=\n True, null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.TextField(db_column='Year', blank=True, null=True)\n toefl = models.TextField(db_column='TOEFL', blank=True, null=True)\n ielts = models.TextField(db_column='IELTS', blank=True, null=True)\n gre = models.TextField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n school_major = models.TextField(db_column='School_Major', blank=True,\n null=True)\n gpa = models.TextField(db_column='GPA', blank=True, null=True)\n post_school = models.TextField(db_column='Post_School', blank=True,\n null=True)\n post_major = models.TextField(db_column='Post_Major', blank=True, null=True\n )\n post_gpa = models.TextField(db_column='Post_GPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n applied_school, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result'\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n\n\nclass NewResult(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n applied_school, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result'\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n\n\nclass NewResult(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n class Meta:\n managed = False\n db_table = 'new_result'\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n\n\nclass NewResultEqual(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n\n\nclass NewResultEqual(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n\n\nclass NewResultEqual(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n class Meta:\n managed = False\n db_table = 'new_result_equal'\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n<class token>\n\n\nclass NewResultMissing(models.Model):\n index = models.BigIntegerField(blank=True, primary_key=True)\n appliedschool = models.TextField(db_column='AppliedSchool', blank=True,\n null=True)\n degree = models.TextField(db_column='Degree', blank=True, null=True)\n major = models.TextField(db_column='Major', blank=True, null=True)\n result = models.TextField(db_column='Result', blank=True, null=True)\n year = models.BigIntegerField(db_column='Year', blank=True, null=True)\n englishlevel = models.BigIntegerField(db_column='EnglishLevel', blank=\n True, null=True)\n toefl = models.FloatField(db_column='TOEFL', blank=True, null=True)\n ielts = models.FloatField(db_column='IELTS', blank=True, null=True)\n gre = models.BigIntegerField(db_column='GRE', blank=True, null=True)\n school = models.TextField(db_column='School', blank=True, null=True)\n schoolmajor = models.TextField(db_column='SchoolMajor', blank=True,\n null=True)\n gpa = models.FloatField(db_column='GPA', blank=True, null=True)\n postschool = models.TextField(db_column='PostSchool', blank=True, null=True\n )\n postmajor = models.TextField(db_column='PostMajor', blank=True, null=True)\n postgpa = models.TextField(db_column='PostGPA', blank=True, null=True)\n other_info = models.TextField(db_column='Other_Info', blank=True, null=True\n )\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n<class token>\n\n\nclass NewResultMissing(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return '%d 学校:%s 申请专业:%s GPA:%.2f' % (self.index, self.\n appliedschool, self.major, self.gpa)\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n<class token>\n\n\nclass NewResultMissing(models.Model):\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 <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n class Meta:\n managed = False\n db_table = 'new_result_missing'\n",
"<import token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,943 | 1fd18338067e28ab48a9a83f5ced26e69a1d58b1 | # -*-coding: utf-8-*- ; -*-Python-*-
# Copyright © 2022-2023 Tom Fontaine
# Title: colors.py
# Date: 25-Apr-2022
colors = {'CSI': chr(27) + '[',
'CSI24': chr(27) + '[38;5;',
'NORMAL': '0',
'BOLD': '1',
'BLACK': '30',
'RED': '31',
'GREEN': '32',
'YELLOW': '33',
'BLUE': '34',
'MAGENTA': '35',
'CYAN': '36',
'WHITE': '37'}
| [
"# -*-coding: utf-8-*- ; -*-Python-*-\n\n# Copyright © 2022-2023 Tom Fontaine\n\n# Title: colors.py\n# Date: 25-Apr-2022\n\n\ncolors = {'CSI': chr(27) + '[',\n 'CSI24': chr(27) + '[38;5;',\n\n 'NORMAL': '0',\n 'BOLD': '1',\n\n 'BLACK': '30',\n 'RED': '31',\n 'GREEN': '32',\n 'YELLOW': '33',\n 'BLUE': '34',\n 'MAGENTA': '35',\n 'CYAN': '36',\n 'WHITE': '37'}\n",
"colors = {'CSI': chr(27) + '[', 'CSI24': chr(27) + '[38;5;', 'NORMAL': '0',\n 'BOLD': '1', 'BLACK': '30', 'RED': '31', 'GREEN': '32', 'YELLOW': '33',\n 'BLUE': '34', 'MAGENTA': '35', 'CYAN': '36', 'WHITE': '37'}\n",
"<assignment token>\n"
] | false |
99,944 | b36f307d81187eb662470628aa84f86295a91297 | __copyright__ = """
This file is part of stellar-py, Stellar Python Client.
Copyright 2018 CSIRO Data61
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.
"""
__license__ = "Apache 2.0"
from setuptools import setup
from setuptools import find_packages
setup(name='stellar-py',
version='0.2.2',
description='Python client for the Stellar project',
url='https://github.com/data61/stellar-py',
author='Kevin Jung',
author_email='kevin.jung@data61.csiro.au',
license='Apache 2.0',
install_requires=['requests', 'redis', 'polling', 'networkx'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
extras_require={
'testing': ['httpretty', 'coveralls'],
},
packages=find_packages())
| [
"__copyright__ = \"\"\"\n\n This file is part of stellar-py, Stellar Python Client.\n\n Copyright 2018 CSIRO Data61\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n__license__ = \"Apache 2.0\"\n\nfrom setuptools import setup\nfrom setuptools import find_packages\n\nsetup(name='stellar-py',\n version='0.2.2',\n description='Python client for the Stellar project',\n url='https://github.com/data61/stellar-py',\n author='Kevin Jung',\n author_email='kevin.jung@data61.csiro.au',\n license='Apache 2.0',\n install_requires=['requests', 'redis', 'polling', 'networkx'],\n setup_requires=['pytest-runner'],\n tests_require=['pytest'],\n extras_require={\n 'testing': ['httpretty', 'coveralls'],\n },\n packages=find_packages())\n",
"__copyright__ = \"\"\"\n\n This file is part of stellar-py, Stellar Python Client.\n\n Copyright 2018 CSIRO Data61\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n__license__ = 'Apache 2.0'\nfrom setuptools import setup\nfrom setuptools import find_packages\nsetup(name='stellar-py', version='0.2.2', description=\n 'Python client for the Stellar project', url=\n 'https://github.com/data61/stellar-py', author='Kevin Jung',\n author_email='kevin.jung@data61.csiro.au', license='Apache 2.0',\n install_requires=['requests', 'redis', 'polling', 'networkx'],\n setup_requires=['pytest-runner'], tests_require=['pytest'],\n extras_require={'testing': ['httpretty', 'coveralls']}, packages=\n find_packages())\n",
"__copyright__ = \"\"\"\n\n This file is part of stellar-py, Stellar Python Client.\n\n Copyright 2018 CSIRO Data61\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n__license__ = 'Apache 2.0'\n<import token>\nsetup(name='stellar-py', version='0.2.2', description=\n 'Python client for the Stellar project', url=\n 'https://github.com/data61/stellar-py', author='Kevin Jung',\n author_email='kevin.jung@data61.csiro.au', license='Apache 2.0',\n install_requires=['requests', 'redis', 'polling', 'networkx'],\n setup_requires=['pytest-runner'], tests_require=['pytest'],\n extras_require={'testing': ['httpretty', 'coveralls']}, packages=\n find_packages())\n",
"<assignment token>\n<import token>\nsetup(name='stellar-py', version='0.2.2', description=\n 'Python client for the Stellar project', url=\n 'https://github.com/data61/stellar-py', author='Kevin Jung',\n author_email='kevin.jung@data61.csiro.au', license='Apache 2.0',\n install_requires=['requests', 'redis', 'polling', 'networkx'],\n setup_requires=['pytest-runner'], tests_require=['pytest'],\n extras_require={'testing': ['httpretty', 'coveralls']}, packages=\n find_packages())\n",
"<assignment token>\n<import token>\n<code token>\n"
] | false |
99,945 | 5058f568f278e7e87e07d0523d58293fdc1e1ddc | def add(x, y):
return x + y
def minus(x, y):
return x - y
def multiple(x, y):
return x * y
def divide(x, y):
if y == 0:
print("error!")
return
else:
return x / y | [
"def add(x, y):\n\treturn x + y\n\ndef minus(x, y):\n\treturn x - y\n\ndef multiple(x, y):\n\treturn x * y\n\ndef divide(x, y):\n\tif y == 0:\n\t\tprint(\"error!\")\n\t\treturn\n\telse:\n\t\treturn x / y",
"def add(x, y):\n return x + y\n\n\ndef minus(x, y):\n return x - y\n\n\ndef multiple(x, y):\n return x * y\n\n\ndef divide(x, y):\n if y == 0:\n print('error!')\n return\n else:\n return x / y\n",
"def add(x, y):\n return x + y\n\n\ndef minus(x, y):\n return x - y\n\n\n<function token>\n\n\ndef divide(x, y):\n if y == 0:\n print('error!')\n return\n else:\n return x / y\n",
"<function token>\n\n\ndef minus(x, y):\n return x - y\n\n\n<function token>\n\n\ndef divide(x, y):\n if y == 0:\n print('error!')\n return\n else:\n return x / y\n",
"<function token>\n<function token>\n<function token>\n\n\ndef divide(x, y):\n if y == 0:\n print('error!')\n return\n else:\n return x / y\n",
"<function token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,946 | 926f55a6fc19dcf95339aae1e16f5d10cbd977ac | import math
from abc import ABCMeta, abstractmethod
from collections import Iterable
# from __future__ import annotations
'''
This whole thing is a bit much...
To make the assignment interesting I decided to practice object hierarchies and inheritance,
and potentially generate some code I could reuse later with Katis.
The intent was to cut most of it out of the final submission, but I suddenly found myself quite busy.
Nothing magical happens here, and other than maybe StateNode, none of these classes are particularly important
for understanding the assignment submission.
'''
from typing import TypeVar, Callable, Generic, Any
N = TypeVar('N', int, float) # Number
A = TypeVar('A') # Action
E = TypeVar('E') # Edge
D = TypeVar('D') # Node
S = TypeVar('S') # State
C = TypeVar('C') # Configuration
# T = TypeVar('T', Callable[[A], D], Callable[[A, D], D]) #...
def _order(i: int, j: int) -> tuple:
if i < j: return i, j
else: return j, i
class AState(Generic[S, C, A], metaclass=ABCMeta):
debug: bool = False
_actions: list = None
_examined: bool = False
_results: dict = None
def __init__(self, results: dict = None):
self._results = results
@abstractmethod
def __lt__(self, other) -> bool:
pass
@abstractmethod
def __le__(self, other) -> bool:
pass
@abstractmethod
def __eq__(self, other) -> bool:
pass
@abstractmethod
def __ne__(self, other) -> bool:
pass
@abstractmethod
def __gt__(self, other) -> bool:
pass
@abstractmethod
def __ge__(self, other) -> bool:
pass
@abstractmethod
def __getitem__(self, key):
pass
@abstractmethod
def __str__(self) -> str:
pass
@abstractmethod
def __hash__(self):
pass
@abstractmethod
def describe(self) -> str:
pass
@abstractmethod
def is_goal(self) -> bool:
pass
def actions(self) -> list:
"""
Returns the list of valid actions that can be performed on this node.
:return: The list of valid actions
"""
if self.debug: print(f"AState.actions()")
if not self._examined:
if self.debug: print(f"\tExamining...")
self._actions = self._generate_actions()
self._examined = True
return self._actions
def result(self, action: A) -> S:
"""
A complicated method that links an action to a result by whichever means used by the subclass
:param action: The action being performed
:return: The resulting state
"""
if self.debug: print(f"AState.transition({action.name})")
if self._results:
if self._results[action]:
if callable(self._results[action]):
output = self._results[action](argument=self, action=action)
if action and not action.output: action.output = output
return output
else:
output = self._results[action]
if action and not action.output: action.output = output
return output
elif action and action.result:
return action.result
elif action and action.transform:
return action.transform(argument=self, action=action)
else:
raise KeyError(action)
# Must override
@abstractmethod
def _generate_actions(self) -> list:
"""
This method must be overridden by any subclasses.
It must return a list of all valid actions that can be performed.
"""
pass
class AAction(Generic[A, S], metaclass=ABCMeta):
debug: bool = False
name: str
argument: S = None
output: S = None
transform: Callable = None
reversible: bool
reverse: str
@abstractmethod
def __str__(self) -> str:
pass
class AEdge(Generic[E, D], metaclass=ABCMeta):
debug: bool = False
cost: N
source: D
result: D
reversible: bool
@abstractmethod
def __str__(self) -> str:
pass
@abstractmethod
def __int__(self) -> int:
pass
@abstractmethod
def __float__(self) -> float:
pass
@abstractmethod
def __lt__(self, other) -> bool:
pass
@abstractmethod
def __le__(self, other) -> bool:
pass
@abstractmethod
def __eq__(self, other) -> bool:
pass
@abstractmethod
def __ne__(self, other) -> bool:
pass
@abstractmethod
def __gt__(self, other) -> bool:
pass
@abstractmethod
def __ge__(self, other) -> bool:
pass
@abstractmethod
def __hash__(self):
pass
class ANode(Generic[E, D], metaclass=ABCMeta):
debug: bool = False
parent: D
_edges: list = None
def __init__(self, parent: D = None):
self.parent = parent
@abstractmethod
def __int__(self) -> int:
pass
@abstractmethod
def __float__(self) -> float:
pass
@abstractmethod
def __lt__(self, other) -> bool:
pass
@abstractmethod
def __le__(self, other) -> bool:
pass
@abstractmethod
def __eq__(self, other) -> bool:
pass
@abstractmethod
def __ne__(self, other) -> bool:
pass
@abstractmethod
def __gt__(self, other) -> bool:
pass
@abstractmethod
def __ge__(self, other) -> bool:
pass
@abstractmethod
def __str__(self) -> str:
pass
@abstractmethod
def __hash__(self):
pass
@abstractmethod
def expand(self, ignore) -> list:
pass
@abstractmethod
def actions(self) -> list:
pass
@abstractmethod
def describe(self) -> str:
pass
@abstractmethod
def transition(self, action):
pass
class DelegatingState(AState[S, C, A], metaclass=ABCMeta):
configuration: C
def __init__(self, configuration: C, results: dict = None, *args, **kwargs):
super().__init__(results)
self.configuration = configuration
def __str__(self) -> str:
return self.configuration.__str__()
def __lt__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__lt__(other.configuration)
return self.configuration.__lt__(other)
def __le__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__le__(other.configuration)
return self.configuration.__le__(other)
def __eq__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__eq__(other.configuration)
return self.configuration.__eq__(other)
def __ne__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__ne__(other.configuration)
return self.configuration.__ne__(other)
def __gt__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__gt__(other.configuration)
return self.configuration.__gt__(other)
def __ge__(self, other) -> bool:
if isinstance(other, DelegatingState):
return self.configuration.__ge__(other.configuration)
return self.configuration.__ge__(other)
def __getitem__(self, key):
if hasattr(self.configuration, "__getitem__") and callable(getattr(self.configuration, "__getitem__")):
return self.configuration.__getitem__(key)
if hasattr(self.configuration, key):
return getattr(self.configuration, key)
return None
def __hash__(self):
return hash(self.configuration)
class StringState(DelegatingState[S, str, A], metaclass=ABCMeta):
marked: int
def __init__(self, configuration: str, marked: int = None, results: dict = None, *args, **kwargs):
super().__init__(configuration, results)
self.marked = marked
def __str__(self) -> str:
return self.configuration
def __len__(self) -> int:
return self.configuration.__len__()
def __getitem__(self, key):
return self.configuration.__getitem__(key)
def swap(self, i: int, j: int = None) -> str:
if self.debug: print(f"StringState.swap({i}, {j})")
if j is None:
if self.marked is not None:
j = self.marked
else:
j = 0
if i == j: return self.configuration
min_i, max_i = _order(i, j)
return self.configuration[:min_i] + self.configuration[max_i] + self.configuration[min_i + 1:max_i] \
+ self.configuration[min_i] + self.configuration[max_i + 1:]
@staticmethod
def shuffle_string(tiles: str) -> str:
import random
l = list(tiles)
random.shuffle(l)
return ''.join(l)
IntPair = TypeVar('IntPair', int, tuple)
class CharGrid(StringState[S, A], metaclass=ABCMeta):
_rows: int
_cols: int
gap: tuple
def __init__(self, configuration: str, rows: int = 0, cols: int = 0, marked: int = None, results: dict = None,
*args, **kwargs):
super().__init__(configuration, marked, results)
if rows > 0 and cols > 0 and len(configuration) == rows * cols:
self._rows = rows
self._cols = cols
elif rows > 0 and len(configuration) % rows == 0:
self._rows = rows
self._cols = len(configuration) // rows
elif cols > 0 and len(configuration) % cols == 0:
self._rows = len(configuration) // cols
self._cols = cols
elif int(math.sqrt(len(configuration)))**2 == len(configuration):
self._rows = rows
self._cols = cols
else:
raise AttributeError(configuration, rows, cols)
self.gap = self.coord(self.marked)
def __getitem__(self, key):
if isinstance(key, tuple) and len(key) == 2:
key: tuple
return self.get(*key)
return super().__getitem__(key)
def __str__(self) -> str:
string: str = ""
for i in range(self._rows):
string += self.get_row(i) + '\n'
return string
def coord(self, i: int) -> tuple:
if i > self._rows * self._cols: raise IndexError(i)
return i // self._cols, i % self._cols
def _flat(self, i: int, j: int) -> int:
if i == self._rows + 1 and j == 0: return self._rows * self._cols
if i > self._rows or j > self._cols: raise IndexError(i, j)
return i * self._cols + j
def get(self, i: IntPair, j: int = None) -> str:
if isinstance(i, tuple):
return self.configuration[self._flat(*i)]
if j is None:
return self.configuration[i]
return self.configuration[self._flat(i, j)]
def get_row(self, i: int) -> str:
return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]
def get_col(self, j: int) -> str:
string: str = ""
for i in range(self._rows):
string += self.configuration[self._flat(i, j)]
return string
def swap(self, i: IntPair, j: IntPair = None) -> str:
if self.debug: print(f"CharGrid.swap({i}, {j})")
if j is not None and isinstance(j, tuple):
j: tuple
j: int = self._flat(*j)
if self.debug: print(f"\tj -> {j}")
if isinstance(i, tuple):
i: tuple
if j is None:
j: int = self.marked
# if self.debug: print(f"\ti, j -> {i}")
# return super().swap(*i)
if self.debug: print(f"\ti, j -> {self._flat(*i)}, {j}")
return super().swap(self._flat(*i), j)
return super().swap(i, j)
class Edge(AEdge[E, D], metaclass=ABCMeta):
def __init__(self, cost: N = 1, source: D = None, result: D = None, reversible: bool = False, *args, **kwargs):
self.cost = cost
self.source = source
self.result = result
self.reversible = reversible
def __str__(self) -> str:
string: str = ""
if self.source: string += " " + self.source.describe() ## Clean this name stuff up
if self.reversible: string += f" <-{self.cost}->"
else: string += f" -{self.cost}->"
if self.result: string += " " + self.result.describe()
return string
def __int__(self) -> int:
if isinstance(self.cost, int): return self.cost
return int(self.cost)
def __float__(self) -> float:
if isinstance(self.cost, float): return self.cost
return float(self.cost)
def __lt__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost < int(other)
return self.cost < float(other)
def __le__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost <= int(other)
return self.cost <= float(other)
def __eq__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost == int(other)
return self.cost == float(other)
def __ne__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost != int(other)
return self.cost != float(other)
def __gt__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost > int(other)
return self.cost > float(other)
def __ge__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost >= int(other)
return self.cost >= float(other)
def __hash__(self):
return hash((self.cost, self.source, self.result, self.reversible))
class Action(Edge['Action', D], AAction['Action', S]):
def __init__(self, name: str, cost: N = 1, transform: Callable = None, argument: S = None, output: S = None,
source: D = None, result: D = None,
reversible: bool = False, reverse: str = None, *args, **kwargs):
super().__init__(cost=cost, source=source, result=result)
self.name = name
self.argument = argument
self.output = output
self.reversible = reversible
self.reverse = reverse
# if result and transform: raise AttributeError(transform, result)
self.transform = transform
# Helper method for debug information
@staticmethod
def _parse_transform(trans):
tokens = str(trans).split(" ")
i = 0
while tokens[i] in ["<bound", "method"]:
i += 1
class_name, method_name = tokens[i].split(".")
context_name, _ = tokens[i + 2][1:].split(".")
return context_name, class_name, method_name
def __str__(self) -> str:
string: str = self.name
if self.source or self.cost != 1 or self.result: string += ":"
if self.debug and self.transform:
context_name, class_name, method_name = self._parse_transform(self.transform)
string += " " + class_name + "." + method_name + "()"
if self.source: string += " on " + self.source.describe() ## Clean this name stuff up
if self.cost != 1:
if self.reversible: string += f" <-{self.cost}->"
else: string += f" -{self.cost}->"
else:
if self.reversible: string += f" <--->"
else: string += f" --->"
if self.result: string += " " + self.result.describe()
else: string += " ?"
return string
def __hash__(self):
return hash(self.name)
class CostNode(ANode[E, D], metaclass=ABCMeta):
cost: N
_edges: list
_children: list
_expanded: bool
_examined: bool
def __init__(self, parent: D = None, edge: Action[S, D] = None, cost: N = 0):
super().__init__(parent)
self.action = edge
self.cost = cost
self._edges = []
self._children = []
self._expanded = False
self._examined = False
def __int__(self) -> int:
if isinstance(self.cost, int): return self.cost
return int(self.cost)
def __float__(self) -> float:
if isinstance(self.cost, float): return self.cost
return float(self.cost)
def __lt__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost < int(other)
return self.cost < float(other)
def __le__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost <= int(other)
return self.cost <= float(other)
def __eq__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost == int(other)
return self.cost == float(other)
def __ne__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost != int(other)
return self.cost != float(other)
def __gt__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost > int(other)
return self.cost > float(other)
def __ge__(self, other) -> bool:
if isinstance(self.cost, int):
return self.cost >= int(other)
return self.cost >= float(other)
def __getitem__(self, key: Action[S, D]):
return None
def __hash__(self):
return hash((self.parent, self.action, self.cost))
class StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):
action: Action[D, S]
state: S
_transitions: dict
def __init__(self, state: S, parent: D = None, edge: Action[S, D] = None, cost: N = 0,
transitions: dict = None, *args, **kwargs):
super().__init__(parent, edge, cost)
self.state = state
self._transitions = transitions
def expand(self, ignore: Iterable = None) -> list:
"""
Expands the current node.
:param ignore: An iterable collection of states to ignore.
:return: The list of expanded nodes
"""
if self.debug: print(f"StateNode.expand({ignore})")
if not self._expanded:
if ignore is not None:
if self.debug: print(f"\tExpanding without {ignore}")
x: D
self._children = [x for x in self._generate_children() if x.state not in ignore]
else:
if self.debug: print(f"\tExpanding...")
self._children = self._generate_children()
self._expanded = True
return self._children
def actions(self) -> list:
"""
Returns the list of valid actions that can be performed on this node.
:return: The list of valid actions
"""
if self.debug: print(f"StateNode.actions()")
if not self._examined:
if self.debug: print(f"\tExamining...")
self._edges = self.state.actions()
for e in self._edges:
e: Action
e.source = self
e.cost = self.get_cost(e)
self._examined = True
return self._edges
def __hash__(self):
return hash(hash(self.state))
# May need to override
def __getitem__(self, key: Any):
# if isinstance(key, Action): return super().__getitem__(key)
if isinstance(key, Action): return self.transition(key)
return self.state.__getitem__(key)
def __str__(self) -> str:
return self.state.__str__()
def _generate_children(self) -> list:
"""
Internal method that generates the children of this node.
The default implementation delegates to _generate_actions
:return: The list of children
"""
if self.debug: print(f"StateNode._generate_children()")
return [self.transition(x) for x in self.actions()]
def describe(self) -> str:
"""
:return: A string description of the node
"""
return self.state.describe()
def transition(self, action: Action) -> D:
"""
A complicated method that links an action to a result by whichever means used by the subclass
:param action: The action being performed
:return: The resulting node
"""
if self.debug: print(f"StateNode.transition({action.name})")
if self._transitions:
if self._transitions[action]:
if callable(self._transitions[action]):
result = self._transitions[action](source=self, action=action)
if action and not action.result: action.result = result
return result
else:
result = self._transitions[action]
if action and not action.result: action.result = result
return result
elif action and action.result:
return action.result
elif action and action.transform:
return self._successor(action.transform(source=self, action=action), action)
else:
raise KeyError(action)
# Must override
@abstractmethod
def get_cost(self, action: Action) -> N:
"""
This method must be overridden by any subclasses.
It must return a list of all valid actions that can be performed.
"""
pass
@abstractmethod
def _successor(self, state: S, action: Action, *args, **kwargs) -> D:
"""
This method must be overridden by any subclasses.
It must return a successor based on the new state provided
"""
pass
'''
if self.debug: print(f"StateNode.transition({action.name})")
if self._transitions:
if self._transitions[action]:
if callable(self._transitions[action]):
result = self._transitions[action](source=self, action=action)
if action and not action.result: action.result = result
return result
else:
result = self._transitions[action]
if action and not action.result: action.result = result
return result
elif action and action.result:
return action.result
elif action and action.transform:
return action.transform(source=self, action=action)
else:
raise KeyError(action)
'''
| [
"import math\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Iterable\n\n# from __future__ import annotations\n\n'''\nThis whole thing is a bit much...\nTo make the assignment interesting I decided to practice object hierarchies and inheritance,\nand potentially generate some code I could reuse later with Katis.\nThe intent was to cut most of it out of the final submission, but I suddenly found myself quite busy.\nNothing magical happens here, and other than maybe StateNode, none of these classes are particularly important\nfor understanding the assignment submission.\n'''\n\nfrom typing import TypeVar, Callable, Generic, Any\n\nN = TypeVar('N', int, float) # Number\n\nA = TypeVar('A') # Action\n\nE = TypeVar('E') # Edge\n\nD = TypeVar('D') # Node\n\nS = TypeVar('S') # State\n\nC = TypeVar('C') # Configuration\n\n\n# T = TypeVar('T', Callable[[A], D], Callable[[A, D], D]) #...\n\ndef _order(i: int, j: int) -> tuple:\n if i < j: return i, j\n else: return j, i\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict = None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __le__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) -> str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) -> str:\n pass\n\n @abstractmethod\n def is_goal(self) -> bool:\n pass\n\n def actions(self) -> list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug: print(f\"AState.actions()\")\n if not self._examined:\n if self.debug: print(f\"\\tExamining...\")\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n\n def result(self, action: A) -> S:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting state\n \"\"\"\n if self.debug: print(f\"AState.transition({action.name})\")\n if self._results:\n if self._results[action]:\n if callable(self._results[action]):\n output = self._results[action](argument=self, action=action)\n if action and not action.output: action.output = output\n return output\n else:\n output = self._results[action]\n if action and not action.output: action.output = output\n return output\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(argument=self, action=action)\n else:\n raise KeyError(action)\n\n # Must override\n\n @abstractmethod\n def _generate_actions(self) -> list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) -> str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) -> str:\n pass\n\n @abstractmethod\n def __int__(self) -> int:\n pass\n\n @abstractmethod\n def __float__(self) -> float:\n pass\n\n @abstractmethod\n def __lt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __le__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D = None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) -> int:\n pass\n\n @abstractmethod\n def __float__(self) -> float:\n pass\n\n @abstractmethod\n def __lt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __le__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) -> bool:\n pass\n\n @abstractmethod\n def __str__(self) -> str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) -> list:\n pass\n\n @abstractmethod\n def actions(self) -> list:\n pass\n\n @abstractmethod\n def describe(self) -> str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict = None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) -> str:\n return self.configuration.__str__()\n\n def __lt__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) -> bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, \"__getitem__\") and callable(getattr(self.configuration, \"__getitem__\")):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int = None, results: dict = None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) -> str:\n return self.configuration\n\n def __len__(self) -> int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int = None) -> str:\n if self.debug: print(f\"StringState.swap({i}, {j})\")\n\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n\n if i == j: return self.configuration\n\n min_i, max_i = _order(i, j)\n\n return self.configuration[:min_i] + self.configuration[max_i] + self.configuration[min_i + 1:max_i] \\\n + self.configuration[min_i] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) -> str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\nIntPair = TypeVar('IntPair', int, tuple)\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n\n gap: tuple\n\n def __init__(self, configuration: str, rows: int = 0, cols: int = 0, marked: int = None, results: dict = None,\n *args, **kwargs):\n super().__init__(configuration, marked, results)\n\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n\n elif int(math.sqrt(len(configuration)))**2 == len(configuration):\n self._rows = rows\n self._cols = cols\n\n else:\n raise AttributeError(configuration, rows, cols)\n\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) -> str:\n string: str = \"\"\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) -> tuple:\n if i > self._rows * self._cols: raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) -> int:\n if i == self._rows + 1 and j == 0: return self._rows * self._cols\n if i > self._rows or j > self._cols: raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int = None) -> str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) -> str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) -> str:\n string: str = \"\"\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair = None) -> str:\n if self.debug: print(f\"CharGrid.swap({i}, {j})\")\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug: print(f\"\\tj -> {j}\")\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n # if self.debug: print(f\"\\ti, j -> {i}\")\n # return super().swap(*i)\n if self.debug: print(f\"\\ti, j -> {self._flat(*i)}, {j}\")\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N = 1, source: D = None, result: D = None, reversible: bool = False, *args, **kwargs):\n self.cost = cost\n\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) -> str:\n string: str = \"\"\n if self.source: string += \" \" + self.source.describe() ## Clean this name stuff up\n if self.reversible: string += f\" <-{self.cost}->\"\n else: string += f\" -{self.cost}->\"\n if self.result: string += \" \" + self.result.describe()\n\n return string\n\n def __int__(self) -> int:\n if isinstance(self.cost, int): return self.cost\n return int(self.cost)\n\n def __float__(self) -> float:\n if isinstance(self.cost, float): return self.cost\n return float(self.cost)\n\n def __lt__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N = 1, transform: Callable = None, argument: S = None, output: S = None,\n source: D = None, result: D = None,\n reversible: bool = False, reverse: str = None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n\n # if result and transform: raise AttributeError(transform, result)\n\n self.transform = transform\n\n # Helper method for debug information\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(\" \")\n\n i = 0\n\n while tokens[i] in [\"<bound\", \"method\"]:\n i += 1\n class_name, method_name = tokens[i].split(\".\")\n context_name, _ = tokens[i + 2][1:].split(\".\")\n\n return context_name, class_name, method_name\n\n def __str__(self) -> str:\n string: str = self.name\n\n if self.source or self.cost != 1 or self.result: string += \":\"\n\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self.transform)\n string += \" \" + class_name + \".\" + method_name + \"()\"\n if self.source: string += \" on \" + self.source.describe() ## Clean this name stuff up\n if self.cost != 1:\n if self.reversible: string += f\" <-{self.cost}->\"\n else: string += f\" -{self.cost}->\"\n else:\n if self.reversible: string += f\" <--->\"\n else: string += f\" --->\"\n if self.result: string += \" \" + self.result.describe()\n else: string += \" ?\"\n\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D = None, edge: Action[S, D] = None, cost: N = 0):\n super().__init__(parent)\n\n self.action = edge\n self.cost = cost\n\n self._edges = []\n self._children = []\n\n self._expanded = False\n self._examined = False\n\n def __int__(self) -> int:\n if isinstance(self.cost, int): return self.cost\n return int(self.cost)\n\n def __float__(self) -> float:\n if isinstance(self.cost, float): return self.cost\n return float(self.cost)\n\n def __lt__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) -> bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D = None, edge: Action[S, D] = None, cost: N = 0,\n transitions: dict = None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n\n self.state = state\n\n self._transitions = transitions\n\n def expand(self, ignore: Iterable = None) -> list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug: print(f\"StateNode.expand({ignore})\")\n if not self._expanded:\n if ignore is not None:\n if self.debug: print(f\"\\tExpanding without {ignore}\")\n x: D\n self._children = [x for x in self._generate_children() if x.state not in ignore]\n else:\n if self.debug: print(f\"\\tExpanding...\")\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) -> list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug: print(f\"StateNode.actions()\")\n if not self._examined:\n if self.debug: print(f\"\\tExamining...\")\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n # May need to override\n\n def __getitem__(self, key: Any):\n # if isinstance(key, Action): return super().__getitem__(key)\n if isinstance(key, Action): return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) -> str:\n return self.state.__str__()\n\n def _generate_children(self) -> list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug: print(f\"StateNode._generate_children()\")\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) -> str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) -> D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug: print(f\"StateNode.transition({action.name})\")\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=action)\n if action and not action.result: action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result: action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=action), action)\n else:\n raise KeyError(action)\n\n # Must override\n\n @abstractmethod\n def get_cost(self, action: Action) -> N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) -> D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n'''\n if self.debug: print(f\"StateNode.transition({action.name})\")\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=action)\n if action and not action.result: action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result: action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(source=self, action=action)\n else:\n raise KeyError(action)\n'''\n",
"import math\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Iterable\n<docstring token>\nfrom typing import TypeVar, Callable, Generic, Any\nN = TypeVar('N', int, float)\nA = TypeVar('A')\nE = TypeVar('E')\nD = TypeVar('D')\nS = TypeVar('S')\nC = TypeVar('C')\n\n\ndef _order(i: int, j: int) ->tuple:\n if i < j:\n return i, j\n else:\n return j, i\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict=None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n\n def result(self, action: A) ->S:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting state\n \"\"\"\n if self.debug:\n print(f'AState.transition({action.name})')\n if self._results:\n if self._results[action]:\n if callable(self._results[action]):\n output = self._results[action](argument=self, action=action\n )\n if action and not action.output:\n action.output = output\n return output\n else:\n output = self._results[action]\n if action and not action.output:\n action.output = output\n return output\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(argument=self, action=action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\nIntPair = TypeVar('IntPair', int, tuple)\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\nN = TypeVar('N', int, float)\nA = TypeVar('A')\nE = TypeVar('E')\nD = TypeVar('D')\nS = TypeVar('S')\nC = TypeVar('C')\n\n\ndef _order(i: int, j: int) ->tuple:\n if i < j:\n return i, j\n else:\n return j, i\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict=None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n\n def result(self, action: A) ->S:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting state\n \"\"\"\n if self.debug:\n print(f'AState.transition({action.name})')\n if self._results:\n if self._results[action]:\n if callable(self._results[action]):\n output = self._results[action](argument=self, action=action\n )\n if action and not action.output:\n action.output = output\n return output\n else:\n output = self._results[action]\n if action and not action.output:\n action.output = output\n return output\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(argument=self, action=action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\nIntPair = TypeVar('IntPair', int, tuple)\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n\n\ndef _order(i: int, j: int) ->tuple:\n if i < j:\n return i, j\n else:\n return j, i\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict=None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n\n def result(self, action: A) ->S:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting state\n \"\"\"\n if self.debug:\n print(f'AState.transition({action.name})')\n if self._results:\n if self._results[action]:\n if callable(self._results[action]):\n output = self._results[action](argument=self, action=action\n )\n if action and not action.output:\n action.output = output\n return output\n else:\n output = self._results[action]\n if action and not action.output:\n action.output = output\n return output\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(argument=self, action=action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict=None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n\n def result(self, action: A) ->S:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting state\n \"\"\"\n if self.debug:\n print(f'AState.transition({action.name})')\n if self._results:\n if self._results[action]:\n if callable(self._results[action]):\n output = self._results[action](argument=self, action=action\n )\n if action and not action.output:\n action.output = output\n return output\n else:\n output = self._results[action]\n if action and not action.output:\n action.output = output\n return output\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return action.transform(argument=self, action=action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n\n def __init__(self, results: dict=None):\n self._results = results\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n <function token>\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'AState.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._actions = self._generate_actions()\n self._examined = True\n return self._actions\n <function token>\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def _generate_actions(self) ->list:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __getitem__(self, key):\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n <function token>\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def is_goal(self) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\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 AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\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 AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass AState(Generic[S, C, A], metaclass=ABCMeta):\n debug: bool = False\n _actions: list = None\n _examined: bool = False\n _results: dict = None\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 AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass AAction(Generic[A, S], metaclass=ABCMeta):\n debug: bool = False\n name: str\n argument: S = None\n output: S = None\n transform: Callable = None\n reversible: bool\n reverse: str\n <function token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n <function token>\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n <function token>\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\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 @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass AEdge(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n cost: N\n source: D\n result: D\n reversible: bool\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 ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n\n @abstractmethod\n def actions(self) ->list:\n pass\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __str__(self) ->str:\n pass\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __le__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n\n @abstractmethod\n def transition(self, action):\n pass\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __gt__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __ge__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n <function token>\n\n @abstractmethod\n def __eq__(self, other) ->bool:\n pass\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n\n @abstractmethod\n def __lt__(self, other) ->bool:\n pass\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n\n @abstractmethod\n def __int__(self) ->int:\n pass\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n <function token>\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __hash__(self):\n pass\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n <function token>\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def expand(self, ignore) ->list:\n pass\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n <function token>\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def describe(self) ->str:\n pass\n <function token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n <function token>\n\n @abstractmethod\n def __float__(self) ->float:\n pass\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\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 DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def __ne__(self, other) ->bool:\n pass\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 DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\n\n def __init__(self, parent: D=None):\n self.parent = parent\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 DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass ANode(Generic[E, D], metaclass=ABCMeta):\n debug: bool = False\n parent: D\n _edges: list = None\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 DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n\n def __str__(self) ->str:\n return self.configuration.__str__()\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__lt__(other.configuration)\n return self.configuration.__lt__(other)\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n <function token>\n <function token>\n\n def __le__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__le__(other.configuration)\n return self.configuration.__le__(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n\n def __hash__(self):\n return hash(self.configuration)\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n\n def __init__(self, configuration: C, results: dict=None, *args, **kwargs):\n super().__init__(results)\n self.configuration = configuration\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ne__(other.configuration)\n return self.configuration.__ne__(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n <function token>\n\n def __gt__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__gt__(other.configuration)\n return self.configuration.__gt__(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n <function token>\n <function token>\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n\n def __getitem__(self, key):\n if hasattr(self.configuration, '__getitem__') and callable(getattr(\n self.configuration, '__getitem__')):\n return self.configuration.__getitem__(key)\n if hasattr(self.configuration, key):\n return getattr(self.configuration, key)\n return None\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__eq__(other.configuration)\n return self.configuration.__eq__(other)\n <function token>\n <function token>\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n <function token>\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ge__(self, other) ->bool:\n if isinstance(other, DelegatingState):\n return self.configuration.__ge__(other.configuration)\n return self.configuration.__ge__(other)\n <function token>\n <function token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass DelegatingState(AState[S, C, A], metaclass=ABCMeta):\n configuration: C\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 StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n\n def __init__(self, configuration: str, marked: int=None, results: dict=\n None, *args, **kwargs):\n super().__init__(configuration, results)\n self.marked = marked\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n\n def __str__(self) ->str:\n return self.configuration\n\n def __len__(self) ->int:\n return self.configuration.__len__()\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n\n def __str__(self) ->str:\n return self.configuration\n <function token>\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n <function token>\n <function token>\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n\n @staticmethod\n def shuffle_string(tiles: str) ->str:\n import random\n l = list(tiles)\n random.shuffle(l)\n return ''.join(l)\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n <function token>\n <function token>\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n\n def swap(self, i: int, j: int=None) ->str:\n if self.debug:\n print(f'StringState.swap({i}, {j})')\n if j is None:\n if self.marked is not None:\n j = self.marked\n else:\n j = 0\n if i == j:\n return self.configuration\n min_i, max_i = _order(i, j)\n return self.configuration[:min_i] + self.configuration[max_i\n ] + self.configuration[min_i + 1:max_i] + self.configuration[min_i\n ] + self.configuration[max_i + 1:]\n <function token>\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n <function token>\n <function token>\n\n def __getitem__(self, key):\n return self.configuration.__getitem__(key)\n <function token>\n <function token>\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StringState(DelegatingState[S, str, A], metaclass=ABCMeta):\n marked: int\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n\n def get_row(self, i: int) ->str:\n return self.configuration[self._flat(i, 0):self._flat(i + 1, 0)]\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n\n def swap(self, i: IntPair, j: IntPair=None) ->str:\n if self.debug:\n print(f'CharGrid.swap({i}, {j})')\n if j is not None and isinstance(j, tuple):\n j: tuple\n j: int = self._flat(*j)\n if self.debug:\n print(f'\\tj -> {j}')\n if isinstance(i, tuple):\n i: tuple\n if j is None:\n j: int = self.marked\n if self.debug:\n print(f'\\ti, j -> {self._flat(*i)}, {j}')\n return super().swap(self._flat(*i), j)\n return super().swap(i, j)\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n\n def __getitem__(self, key):\n if isinstance(key, tuple) and len(key) == 2:\n key: tuple\n return self.get(*key)\n return super().__getitem__(key)\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n\n def _flat(self, i: int, j: int) ->int:\n if i == self._rows + 1 and j == 0:\n return self._rows * self._cols\n if i > self._rows or j > self._cols:\n raise IndexError(i, j)\n return i * self._cols + j\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n\n def __init__(self, configuration: str, rows: int=0, cols: int=0, marked:\n int=None, results: dict=None, *args, **kwargs):\n super().__init__(configuration, marked, results)\n if rows > 0 and cols > 0 and len(configuration) == rows * cols:\n self._rows = rows\n self._cols = cols\n elif rows > 0 and len(configuration) % rows == 0:\n self._rows = rows\n self._cols = len(configuration) // rows\n elif cols > 0 and len(configuration) % cols == 0:\n self._rows = len(configuration) // cols\n self._cols = cols\n elif int(math.sqrt(len(configuration))) ** 2 == len(configuration):\n self._rows = rows\n self._cols = cols\n else:\n raise AttributeError(configuration, rows, cols)\n self.gap = self.coord(self.marked)\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n <function token>\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n <function token>\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n\n def coord(self, i: int) ->tuple:\n if i > self._rows * self._cols:\n raise IndexError(i)\n return i // self._cols, i % self._cols\n <function token>\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n <function token>\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n <function token>\n <function token>\n\n def get(self, i: IntPair, j: int=None) ->str:\n if isinstance(i, tuple):\n return self.configuration[self._flat(*i)]\n if j is None:\n return self.configuration[i]\n return self.configuration[self._flat(i, j)]\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\n <function token>\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.get_row(i) + '\\n'\n return string\n <function token>\n <function token>\n <function token>\n <function token>\n\n def get_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\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_col(self, j: int) ->str:\n string: str = ''\n for i in range(self._rows):\n string += self.configuration[self._flat(i, j)]\n return string\n <function token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass CharGrid(StringState[S, A], metaclass=ABCMeta):\n _rows: int\n _cols: int\n gap: tuple\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 Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n\n def __init__(self, cost: N=1, source: D=None, result: D=None,\n reversible: bool=False, *args, **kwargs):\n self.cost = cost\n self.source = source\n self.result = result\n self.reversible = reversible\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n\n def __str__(self) ->str:\n string: str = ''\n if self.source:\n string += ' ' + self.source.describe()\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n if self.result:\n string += ' ' + self.result.describe()\n return string\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n <function token>\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\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 __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\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 __hash__(self):\n return hash((self.cost, self.source, self.result, self.reversible))\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n\n\nclass Edge(AEdge[E, D], metaclass=ABCMeta):\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 Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n\n @staticmethod\n def _parse_transform(trans):\n tokens = str(trans).split(' ')\n i = 0\n while tokens[i] in ['<bound', 'method']:\n i += 1\n class_name, method_name = tokens[i].split('.')\n context_name, _ = tokens[i + 2][1:].split('.')\n return context_name, class_name, method_name\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n <function token>\n\n def __str__(self) ->str:\n string: str = self.name\n if self.source or self.cost != 1 or self.result:\n string += ':'\n if self.debug and self.transform:\n context_name, class_name, method_name = self._parse_transform(self\n .transform)\n string += ' ' + class_name + '.' + method_name + '()'\n if self.source:\n string += ' on ' + self.source.describe()\n if self.cost != 1:\n if self.reversible:\n string += f' <-{self.cost}->'\n else:\n string += f' -{self.cost}->'\n elif self.reversible:\n string += f' <--->'\n else:\n string += f' --->'\n if self.result:\n string += ' ' + self.result.describe()\n else:\n string += ' ?'\n return string\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n\n def __init__(self, name: str, cost: N=1, transform: Callable=None,\n argument: S=None, output: S=None, source: D=None, result: D=None,\n reversible: bool=False, reverse: str=None, *args, **kwargs):\n super().__init__(cost=cost, source=source, result=result)\n self.name = name\n self.argument = argument\n self.output = output\n self.reversible = reversible\n self.reverse = reverse\n self.transform = transform\n <function token>\n <function token>\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n <function token>\n <function token>\n <function token>\n\n def __hash__(self):\n return hash(self.name)\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n\n\nclass Action(Edge['Action', D], AAction['Action', S]):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n\n def __float__(self) ->float:\n if isinstance(self.cost, float):\n return self.cost\n return float(self.cost)\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n\n def __ge__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost >= int(other)\n return self.cost >= float(other)\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n\n def __init__(self, parent: D=None, edge: Action[S, D]=None, cost: N=0):\n super().__init__(parent)\n self.action = edge\n self.cost = cost\n self._edges = []\n self._children = []\n self._expanded = False\n self._examined = False\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n\n def __int__(self) ->int:\n if isinstance(self.cost, int):\n return self.cost\n return int(self.cost)\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n\n def __le__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost <= int(other)\n return self.cost <= float(other)\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n <function token>\n\n def __eq__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost == int(other)\n return self.cost == float(other)\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n\n def __lt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost < int(other)\n return self.cost < float(other)\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n\n def __gt__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost > int(other)\n return self.cost > float(other)\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n <function token>\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n\n def __hash__(self):\n return hash((self.parent, self.action, self.cost))\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __ne__(self, other) ->bool:\n if isinstance(self.cost, int):\n return self.cost != int(other)\n return self.cost != float(other)\n <function token>\n <function token>\n\n def __getitem__(self, key: Action[S, D]):\n return None\n <function token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\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 __getitem__(self, key: Action[S, D]):\n return None\n <function token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n\n\nclass CostNode(ANode[E, D], metaclass=ABCMeta):\n cost: N\n _edges: list\n _children: list\n _expanded: bool\n _examined: bool\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 StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n\n def __getitem__(self, key: Any):\n if isinstance(key, Action):\n return self.transition(key)\n return self.state.__getitem__(key)\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n\n def __hash__(self):\n return hash(hash(self.state))\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n\n @abstractmethod\n def get_cost(self, action: Action) ->N:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a list of all valid actions that can be performed.\n \"\"\"\n pass\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n\n def describe(self) ->str:\n \"\"\"\n :return: A string description of the node\n \"\"\"\n return self.state.describe()\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n <function token>\n\n def transition(self, action: Action) ->D:\n \"\"\"\n A complicated method that links an action to a result by whichever means used by the subclass\n :param action: The action being performed\n :return: The resulting node\n \"\"\"\n if self.debug:\n print(f'StateNode.transition({action.name})')\n if self._transitions:\n if self._transitions[action]:\n if callable(self._transitions[action]):\n result = self._transitions[action](source=self, action=\n action)\n if action and not action.result:\n action.result = result\n return result\n else:\n result = self._transitions[action]\n if action and not action.result:\n action.result = result\n return result\n elif action and action.result:\n return action.result\n elif action and action.transform:\n return self._successor(action.transform(source=self, action=\n action), action)\n else:\n raise KeyError(action)\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n\n def actions(self) ->list:\n \"\"\"\n Returns the list of valid actions that can be performed on this node.\n :return: The list of valid actions\n \"\"\"\n if self.debug:\n print(f'StateNode.actions()')\n if not self._examined:\n if self.debug:\n print(f'\\tExamining...')\n self._edges = self.state.actions()\n for e in self._edges:\n e: Action\n e.source = self\n e.cost = self.get_cost(e)\n self._examined = True\n return self._edges\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n\n def __init__(self, state: S, parent: D=None, edge: Action[S, D]=None,\n cost: N=0, transitions: dict=None, *args, **kwargs):\n super().__init__(parent, edge, cost)\n self.state = state\n self._transitions = transitions\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n <function token>\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n <function token>\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n <function token>\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n\n def _generate_children(self) ->list:\n \"\"\"\n Internal method that generates the children of this node.\n The default implementation delegates to _generate_actions\n :return: The list of children\n \"\"\"\n if self.debug:\n print(f'StateNode._generate_children()')\n return [self.transition(x) for x in self.actions()]\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n <function token>\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n <function token>\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n <function token>\n <function token>\n <function token>\n <function token>\n\n @abstractmethod\n def _successor(self, state: S, action: Action, *args, **kwargs) ->D:\n \"\"\"\n This method must be overridden by any subclasses.\n It must return a successor based on the new state provided\n \"\"\"\n pass\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n <function token>\n\n def expand(self, ignore: Iterable=None) ->list:\n \"\"\"\n Expands the current node.\n :param ignore: An iterable collection of states to ignore.\n :return: The list of expanded nodes\n \"\"\"\n if self.debug:\n print(f'StateNode.expand({ignore})')\n if not self._expanded:\n if ignore is not None:\n if self.debug:\n print(f'\\tExpanding without {ignore}')\n x: D\n self._children = [x for x in self._generate_children() if x\n .state not in ignore]\n else:\n if self.debug:\n print(f'\\tExpanding...')\n self._children = self._generate_children()\n self._expanded = True\n return self._children\n <function token>\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __str__(self) ->str:\n return self.state.__str__()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass StateNode(CostNode['Action', D], Generic[S, D], metaclass=ABCMeta):\n action: Action[D, S]\n state: S\n _transitions: dict\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<docstring token>\n",
"<import token>\n<docstring token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<docstring token>\n"
] | false |
99,947 | ded367d0159f7c1a72f7adea7494f61ae658b1cf | import json
def load_information(key):
f = open('doc\print_info.json',)
data = json.load(f)
if key:
data = [x for x in data if x['modelo'] == key or x['ip'] == key or x['nombre'] == key or x['sise'] == key ]
f.close()
return data | [
"import json\n\ndef load_information(key):\n f = open('doc\\print_info.json',)\n data = json.load(f)\n \n if key:\n data = [x for x in data if x['modelo'] == key or x['ip'] == key or x['nombre'] == key or x['sise'] == key ]\n f.close()\n return data",
"import json\n\n\ndef load_information(key):\n f = open('doc\\\\print_info.json')\n data = json.load(f)\n if key:\n data = [x for x in data if x['modelo'] == key or x['ip'] == key or \n x['nombre'] == key or x['sise'] == key]\n f.close()\n return data\n",
"<import token>\n\n\ndef load_information(key):\n f = open('doc\\\\print_info.json')\n data = json.load(f)\n if key:\n data = [x for x in data if x['modelo'] == key or x['ip'] == key or \n x['nombre'] == key or x['sise'] == key]\n f.close()\n return data\n",
"<import token>\n<function token>\n"
] | false |
99,948 | 1210c4d499c02cf9861b97261033b2d12f2c78d7 | #!/usr/bin/env python3
import csv, json
from sys import argv
try:
filename = argv[1]
except IndexError:
print("No input given")
exit()
try:
f = open(filename, 'r')
blockdata = csv.reader(f, delimiter=',')
timestamp = []
height = []
nonce = []
diff = []
for row in blockdata:
#print (row)
timestamp.append(row[3])
height.append(row[1])
nonce.append(row[2])
diff.append(row[0])
print ("{")
print ("\"timestamp\": ")
print (json.dumps(timestamp))
print (",")
print ("\"height\": ")
print (json.dumps(height))
print (",")
print ("\"nonce\": ")
print (json.dumps(nonce))
print (",")
print ("\"diff\": ")
print (json.dumps(diff))
print ("}")
except (IOError, OSError) as e:
print("Could not open file %s -> %s" % (filename,e))
| [
"#!/usr/bin/env python3\n\nimport csv, json\nfrom sys import argv\n\ntry:\n filename = argv[1]\nexcept IndexError:\n print(\"No input given\")\n exit()\n\ntry:\n f = open(filename, 'r')\n blockdata = csv.reader(f, delimiter=',')\n\n timestamp = []\n height = []\n nonce = []\n diff = []\n\n for row in blockdata:\n #print (row)\n timestamp.append(row[3])\n height.append(row[1])\n nonce.append(row[2])\n diff.append(row[0])\n\n print (\"{\")\n print (\"\\\"timestamp\\\": \")\n print (json.dumps(timestamp))\n print (\",\")\n print (\"\\\"height\\\": \")\n print (json.dumps(height))\n print (\",\")\n print (\"\\\"nonce\\\": \")\n print (json.dumps(nonce))\n print (\",\")\n print (\"\\\"diff\\\": \")\n print (json.dumps(diff))\n print (\"}\")\n\nexcept (IOError, OSError) as e:\n print(\"Could not open file %s -> %s\" % (filename,e))\n",
"import csv, json\nfrom sys import argv\ntry:\n filename = argv[1]\nexcept IndexError:\n print('No input given')\n exit()\ntry:\n f = open(filename, 'r')\n blockdata = csv.reader(f, delimiter=',')\n timestamp = []\n height = []\n nonce = []\n diff = []\n for row in blockdata:\n timestamp.append(row[3])\n height.append(row[1])\n nonce.append(row[2])\n diff.append(row[0])\n print('{')\n print('\"timestamp\": ')\n print(json.dumps(timestamp))\n print(',')\n print('\"height\": ')\n print(json.dumps(height))\n print(',')\n print('\"nonce\": ')\n print(json.dumps(nonce))\n print(',')\n print('\"diff\": ')\n print(json.dumps(diff))\n print('}')\nexcept (IOError, OSError) as e:\n print('Could not open file %s -> %s' % (filename, e))\n",
"<import token>\ntry:\n filename = argv[1]\nexcept IndexError:\n print('No input given')\n exit()\ntry:\n f = open(filename, 'r')\n blockdata = csv.reader(f, delimiter=',')\n timestamp = []\n height = []\n nonce = []\n diff = []\n for row in blockdata:\n timestamp.append(row[3])\n height.append(row[1])\n nonce.append(row[2])\n diff.append(row[0])\n print('{')\n print('\"timestamp\": ')\n print(json.dumps(timestamp))\n print(',')\n print('\"height\": ')\n print(json.dumps(height))\n print(',')\n print('\"nonce\": ')\n print(json.dumps(nonce))\n print(',')\n print('\"diff\": ')\n print(json.dumps(diff))\n print('}')\nexcept (IOError, OSError) as e:\n print('Could not open file %s -> %s' % (filename, e))\n",
"<import token>\n<code token>\n"
] | false |
99,949 | 840acc471ea55a84186b25ca07ddcf7c006a60a9 | #!/usr/bin/python
from __future__ import print_function
import dbus
import sys
import time
import gobject
from dbus.mainloop.glib import DBusGMainLoop
WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1"
WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1"
WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1"
WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface"
def usage():
print("Usage: %s <ifname>" % sys.argv[0])
print("Press Ctrl-C to stop")
def ProbeRequest(args):
if 'addr' in args:
print('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['addr']),
end=' ')
if 'dst' in args:
print('-> %.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['dst']),
end=' ')
if 'bssid' in args:
print('(bssid %.2x:%.2x:%.2x:%.2x:%.2x:%.2x)' % tuple(args['dst']),
end=' ')
if 'signal' in args:
print('signal:%d' % args['signal'], end=' ')
if 'ies' in args:
print('have IEs (%d bytes)' % len(args['ies']), end=' ')
print('')
if __name__ == "__main__":
global bus
global wpas_obj
global if_obj
global p2p_iface
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH)
# Print list of i/f if no one is specified
if (len(sys.argv) < 2) :
usage()
sys.exit(0)
wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE)
ifname = sys.argv[1]
path = wpas.GetInterface(ifname)
if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
iface = dbus.Interface(if_obj, WPAS_DBUS_INTERFACES_INTERFACE)
bus.add_signal_receiver(ProbeRequest,
dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,
signal_name="ProbeRequest")
iface.SubscribeProbeReq()
gobject.MainLoop().run()
| [
"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport dbus\nimport sys\nimport time\nimport gobject\nfrom dbus.mainloop.glib import DBusGMainLoop\n\nWPAS_DBUS_SERVICE = \"fi.w1.wpa_supplicant1\"\nWPAS_DBUS_INTERFACE = \"fi.w1.wpa_supplicant1\"\nWPAS_DBUS_OPATH = \"/fi/w1/wpa_supplicant1\"\nWPAS_DBUS_INTERFACES_INTERFACE = \"fi.w1.wpa_supplicant1.Interface\"\n\ndef usage():\n\tprint(\"Usage: %s <ifname>\" % sys.argv[0])\n\tprint(\"Press Ctrl-C to stop\")\n\ndef ProbeRequest(args):\n\tif 'addr' in args:\n\t\tprint('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['addr']),\n end=' ')\n\tif 'dst' in args:\n\t\tprint('-> %.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['dst']),\n end=' ')\n\tif 'bssid' in args:\n\t\tprint('(bssid %.2x:%.2x:%.2x:%.2x:%.2x:%.2x)' % tuple(args['dst']),\n end=' ')\n\tif 'signal' in args:\n\t\tprint('signal:%d' % args['signal'], end=' ')\n\tif 'ies' in args:\n\t\tprint('have IEs (%d bytes)' % len(args['ies']), end=' ')\n print('')\n\nif __name__ == \"__main__\":\n\tglobal bus\n\tglobal wpas_obj\n\tglobal if_obj\n\tglobal p2p_iface\n\n\tdbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\n\tbus = dbus.SystemBus()\n\twpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH)\n\n\t# Print list of i/f if no one is specified\n\tif (len(sys.argv) < 2) :\n\t\tusage()\n\t\tsys.exit(0)\n\n\twpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE)\n\n\tifname = sys.argv[1]\n\n\tpath = wpas.GetInterface(ifname)\n\n\tif_obj = bus.get_object(WPAS_DBUS_SERVICE, path)\n\tiface = dbus.Interface(if_obj, WPAS_DBUS_INTERFACES_INTERFACE)\n\n\tbus.add_signal_receiver(ProbeRequest,\n\t\t\t\tdbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,\n\t\t\t\tsignal_name=\"ProbeRequest\")\n\n\tiface.SubscribeProbeReq()\n\n\tgobject.MainLoop().run()\n"
] | true |
99,950 | d1434f8fdd0b75ff8a13226f18b60b5281a4ebca | n,m= map(int,input().split())
from collections import Counter
arr = list(map(int,input().split()))
d = Counter(arr)
flag = 0
for i in range(n):
temp = m - arr[i]
if d[temp]:
if arr[i]==temp and d[temp]==1:
continue
print("YES")
flag = 1
break
if flag==0:
print("NO")
| [
"n,m= map(int,input().split())\nfrom collections import Counter\narr = list(map(int,input().split()))\nd = Counter(arr)\n\n\nflag = 0\nfor i in range(n):\n temp = m - arr[i]\n if d[temp]:\n if arr[i]==temp and d[temp]==1:\n continue\n print(\"YES\")\n flag = 1\n break\nif flag==0:\n \n print(\"NO\")\n",
"n, m = map(int, input().split())\nfrom collections import Counter\narr = list(map(int, input().split()))\nd = Counter(arr)\nflag = 0\nfor i in range(n):\n temp = m - arr[i]\n if d[temp]:\n if arr[i] == temp and d[temp] == 1:\n continue\n print('YES')\n flag = 1\n break\nif flag == 0:\n print('NO')\n",
"n, m = map(int, input().split())\n<import token>\narr = list(map(int, input().split()))\nd = Counter(arr)\nflag = 0\nfor i in range(n):\n temp = m - arr[i]\n if d[temp]:\n if arr[i] == temp and d[temp] == 1:\n continue\n print('YES')\n flag = 1\n break\nif flag == 0:\n print('NO')\n",
"<assignment token>\n<import token>\n<assignment token>\nfor i in range(n):\n temp = m - arr[i]\n if d[temp]:\n if arr[i] == temp and d[temp] == 1:\n continue\n print('YES')\n flag = 1\n break\nif flag == 0:\n print('NO')\n",
"<assignment token>\n<import token>\n<assignment token>\n<code token>\n"
] | false |
99,951 | 9921f7fe70280babd2fd29783676d605356081ba | from socket import AF_INET, socket, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
s.connect(('localhost', 8888))
msg = 'Привет, сервер!'
s.send(msg.encode('utf-8'))
data = s.recv(4096)
print(data.decode('utf-8'))
s.close()
# print(tame_data.decode('utf-8')) | [
"from socket import AF_INET, socket, SOCK_STREAM\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 8888))\n\nmsg = 'Привет, сервер!'\ns.send(msg.encode('utf-8'))\ndata = s.recv(4096)\nprint(data.decode('utf-8'))\ns.close()\n\n# print(tame_data.decode('utf-8'))",
"from socket import AF_INET, socket, SOCK_STREAM\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 8888))\nmsg = 'Привет, сервер!'\ns.send(msg.encode('utf-8'))\ndata = s.recv(4096)\nprint(data.decode('utf-8'))\ns.close()\n",
"<import token>\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 8888))\nmsg = 'Привет, сервер!'\ns.send(msg.encode('utf-8'))\ndata = s.recv(4096)\nprint(data.decode('utf-8'))\ns.close()\n",
"<import token>\n<assignment token>\ns.connect(('localhost', 8888))\n<assignment token>\ns.send(msg.encode('utf-8'))\n<assignment token>\nprint(data.decode('utf-8'))\ns.close()\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,952 | 31ac9e6651e11458654adebc13e85b45bde2c54a | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 12:16:58 2019
@author: vladgriguta
Downloads the spectra of the objects in a multi-threading manner, allowing
for fast download of data.
"""
import os
NUM_CPUS = 2 # defaults to all available
def get_address_lists(n_lists,file='../download_url.txt'):
addresses = []
for i in range(n_lists):
addresses.append([])
with open(file,'r') as txt_file:
content = txt_file.readlines()
# round to higher integer
n_elem = int(len(content)/n_lists) + (len(content) % n_lists > 0)
for i in range(len(content)):
addresses[int(i/n_elem)].append(content[i])
return addresses
def worker(address_list,directory):
os.system("wget "+address_list+" "+directory)
def test_run(pool,addresses,directory):
for add in addresses:
for i in range(len(add)):
pool.apply_async(worker, args=(add[i],directory))
#pool.apply_async(worker, args=(add[0],directory))
if __name__ == "__main__":
import multiprocessing as mp
pool = mp.Pool(NUM_CPUS)
directory = 'spectraFull/'
addresses = get_address_lists(4)
test_run(pool,addresses,directory)
pool.close()
pool.join()
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 12 12:16:58 2019\n\n@author: vladgriguta\n\nDownloads the spectra of the objects in a multi-threading manner, allowing\nfor fast download of data.\n\n\"\"\"\nimport os\nNUM_CPUS = 2 # defaults to all available\n\ndef get_address_lists(n_lists,file='../download_url.txt'):\n addresses = []\n for i in range(n_lists):\n addresses.append([])\n with open(file,'r') as txt_file:\n content = txt_file.readlines()\n # round to higher integer\n n_elem = int(len(content)/n_lists) + (len(content) % n_lists > 0)\n for i in range(len(content)):\n addresses[int(i/n_elem)].append(content[i])\n return addresses\n\ndef worker(address_list,directory):\n os.system(\"wget \"+address_list+\" \"+directory)\n\ndef test_run(pool,addresses,directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i],directory))\n \n #pool.apply_async(worker, args=(add[0],directory))\n\nif __name__ == \"__main__\":\n import multiprocessing as mp\n pool = mp.Pool(NUM_CPUS)\n \n directory = 'spectraFull/'\n \n addresses = get_address_lists(4)\n \n test_run(pool,addresses,directory)\n pool.close()\n pool.join()\n\n\n\n",
"<docstring token>\nimport os\nNUM_CPUS = 2\n\n\ndef get_address_lists(n_lists, file='../download_url.txt'):\n addresses = []\n for i in range(n_lists):\n addresses.append([])\n with open(file, 'r') as txt_file:\n content = txt_file.readlines()\n n_elem = int(len(content) / n_lists) + (len(content) % n_lists > 0)\n for i in range(len(content)):\n addresses[int(i / n_elem)].append(content[i])\n return addresses\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\ndef test_run(pool, addresses, directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i], directory))\n\n\nif __name__ == '__main__':\n import multiprocessing as mp\n pool = mp.Pool(NUM_CPUS)\n directory = 'spectraFull/'\n addresses = get_address_lists(4)\n test_run(pool, addresses, directory)\n pool.close()\n pool.join()\n",
"<docstring token>\n<import token>\nNUM_CPUS = 2\n\n\ndef get_address_lists(n_lists, file='../download_url.txt'):\n addresses = []\n for i in range(n_lists):\n addresses.append([])\n with open(file, 'r') as txt_file:\n content = txt_file.readlines()\n n_elem = int(len(content) / n_lists) + (len(content) % n_lists > 0)\n for i in range(len(content)):\n addresses[int(i / n_elem)].append(content[i])\n return addresses\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\ndef test_run(pool, addresses, directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i], directory))\n\n\nif __name__ == '__main__':\n import multiprocessing as mp\n pool = mp.Pool(NUM_CPUS)\n directory = 'spectraFull/'\n addresses = get_address_lists(4)\n test_run(pool, addresses, directory)\n pool.close()\n pool.join()\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef get_address_lists(n_lists, file='../download_url.txt'):\n addresses = []\n for i in range(n_lists):\n addresses.append([])\n with open(file, 'r') as txt_file:\n content = txt_file.readlines()\n n_elem = int(len(content) / n_lists) + (len(content) % n_lists > 0)\n for i in range(len(content)):\n addresses[int(i / n_elem)].append(content[i])\n return addresses\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\ndef test_run(pool, addresses, directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i], directory))\n\n\nif __name__ == '__main__':\n import multiprocessing as mp\n pool = mp.Pool(NUM_CPUS)\n directory = 'spectraFull/'\n addresses = get_address_lists(4)\n test_run(pool, addresses, directory)\n pool.close()\n pool.join()\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef get_address_lists(n_lists, file='../download_url.txt'):\n addresses = []\n for i in range(n_lists):\n addresses.append([])\n with open(file, 'r') as txt_file:\n content = txt_file.readlines()\n n_elem = int(len(content) / n_lists) + (len(content) % n_lists > 0)\n for i in range(len(content)):\n addresses[int(i / n_elem)].append(content[i])\n return addresses\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\ndef test_run(pool, addresses, directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i], directory))\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\ndef test_run(pool, addresses, directory):\n for add in addresses:\n for i in range(len(add)):\n pool.apply_async(worker, args=(add[i], directory))\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n\n\ndef worker(address_list, directory):\n os.system('wget ' + address_list + ' ' + directory)\n\n\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<code token>\n"
] | false |
99,953 | a2455fb96660a919f5b4987e501c3064e431222a | #! python3
#bullet adder -adds bullets before lines
import pyperclip
pyperclip.copy('hello dear\n what\n')
text = pyperclip.paste()
#seperate lines
lines = text.split('\n')
for i in range(len(lines)):
lines[i] = '*'+lines[i]
text = '\n'.join(lines)
pyperclip.copy(text)
| [
"#! python3\r\n#bullet adder -adds bullets before lines\r\n\r\nimport pyperclip\r\npyperclip.copy('hello dear\\n what\\n')\r\n\t\r\ntext = pyperclip.paste()\r\n\r\n#seperate lines \r\nlines = text.split('\\n')\r\nfor i in range(len(lines)):\r\n\tlines[i] = '*'+lines[i]\r\ntext = '\\n'.join(lines)\r\npyperclip.copy(text)\r\n",
"import pyperclip\npyperclip.copy(\"\"\"hello dear\n what\n\"\"\")\ntext = pyperclip.paste()\nlines = text.split('\\n')\nfor i in range(len(lines)):\n lines[i] = '*' + lines[i]\ntext = '\\n'.join(lines)\npyperclip.copy(text)\n",
"<import token>\npyperclip.copy(\"\"\"hello dear\n what\n\"\"\")\ntext = pyperclip.paste()\nlines = text.split('\\n')\nfor i in range(len(lines)):\n lines[i] = '*' + lines[i]\ntext = '\\n'.join(lines)\npyperclip.copy(text)\n",
"<import token>\npyperclip.copy(\"\"\"hello dear\n what\n\"\"\")\n<assignment token>\nfor i in range(len(lines)):\n lines[i] = '*' + lines[i]\n<assignment token>\npyperclip.copy(text)\n",
"<import token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,954 | 9e73be09c9861d7ba881c2fbcca7f25da2f55c32 | import tensorflow.keras
from PIL import Image
import numpy as np
np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
image = Image.open(r'15.jpeg')
image = image.resize((224, 224))
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
data[0] = normalized_image_array
# run the inference
prediction = model.predict(data)
print(prediction)
| [
"import tensorflow.keras\nfrom PIL import Image\nimport numpy as np\n\nnp.set_printoptions(suppress=True)\n\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\n\n\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nimage = Image.open(r'15.jpeg')\nimage = image.resize((224, 224))\nimage_array = np.asarray(image)\nnormalized_image_array = (image_array.astype(np.float32) / 127.0) - 1\ndata[0] = normalized_image_array\n\n# run the inference\nprediction = model.predict(data)\nprint(prediction)\n",
"import tensorflow.keras\nfrom PIL import Image\nimport numpy as np\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nimage = Image.open('15.jpeg')\nimage = image.resize((224, 224))\nimage_array = np.asarray(image)\nnormalized_image_array = image_array.astype(np.float32) / 127.0 - 1\ndata[0] = normalized_image_array\nprediction = model.predict(data)\nprint(prediction)\n",
"<import token>\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nimage = Image.open('15.jpeg')\nimage = image.resize((224, 224))\nimage_array = np.asarray(image)\nnormalized_image_array = image_array.astype(np.float32) / 127.0 - 1\ndata[0] = normalized_image_array\nprediction = model.predict(data)\nprint(prediction)\n",
"<import token>\nnp.set_printoptions(suppress=True)\n<assignment token>\nprint(prediction)\n",
"<import token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,955 | 4fcbdf96cfe5016835eb3c2443211a5070821279 | # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
class HrExpenseAdvanceLine(models.Model):
_name = "hr.expense.advance.line"
_description = "Expense Advance Line"
name = fields.Char(string="Description",
required=True)
advance_id = fields.Many2one(string="Advance Reference",
comodel_name="hr.expense.advance",
required=True,
ondelete="cascade")
currency_id = fields.Many2one(string="Currency",
comodel_name="res.currency",
related="advance_id.currency_id",
store=True)
estimated_amount = fields.Monetary(string="Estimated Amount") | [
"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\n\nclass HrExpenseAdvanceLine(models.Model):\n _name = \"hr.expense.advance.line\"\n _description = \"Expense Advance Line\"\n\n name = fields.Char(string=\"Description\",\n required=True)\n advance_id = fields.Many2one(string=\"Advance Reference\",\n comodel_name=\"hr.expense.advance\",\n required=True,\n ondelete=\"cascade\")\n currency_id = fields.Many2one(string=\"Currency\",\n comodel_name=\"res.currency\",\n related=\"advance_id.currency_id\",\n store=True)\n estimated_amount = fields.Monetary(string=\"Estimated Amount\")",
"from odoo import models, fields, api, _\n\n\nclass HrExpenseAdvanceLine(models.Model):\n _name = 'hr.expense.advance.line'\n _description = 'Expense Advance Line'\n name = fields.Char(string='Description', required=True)\n advance_id = fields.Many2one(string='Advance Reference', comodel_name=\n 'hr.expense.advance', required=True, ondelete='cascade')\n currency_id = fields.Many2one(string='Currency', comodel_name=\n 'res.currency', related='advance_id.currency_id', store=True)\n estimated_amount = fields.Monetary(string='Estimated Amount')\n",
"<import token>\n\n\nclass HrExpenseAdvanceLine(models.Model):\n _name = 'hr.expense.advance.line'\n _description = 'Expense Advance Line'\n name = fields.Char(string='Description', required=True)\n advance_id = fields.Many2one(string='Advance Reference', comodel_name=\n 'hr.expense.advance', required=True, ondelete='cascade')\n currency_id = fields.Many2one(string='Currency', comodel_name=\n 'res.currency', related='advance_id.currency_id', store=True)\n estimated_amount = fields.Monetary(string='Estimated Amount')\n",
"<import token>\n\n\nclass HrExpenseAdvanceLine(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n",
"<import token>\n<class token>\n"
] | false |
99,956 | 39f02872715e2a7cfd7779b83e80a0ffdbd6b3c8 | # Copyright 2020 Red Hat, Inc.
# 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.
class DistroNotSupported(Exception):
"""Distribution is not supported"""
def __init__(
self,
distro_id: str,
message: str = "Distribution {} is not currently supported",
):
super().__init__(message.format(distro_id))
class SubscriptionManagerConfigError(Exception):
"""Subscription manager not configured correctly"""
def __init__( # pylint: disable=useless-super-delegation
self,
message: str = "Red Hat Subscription Manager is not currently configured correctly",
):
super().__init__(message)
class SubscriptionManagerFailure(Exception):
"""Subscription manager failed"""
def __init__(
self, cmd_line: str, message: str = "Failed running subscription-manager {}"
):
super().__init__(message.format(cmd_line))
class VersionNotSupported(Exception):
"""Version is not supported"""
def __init__(
self, version: str, message: str = "Version {} is not currently supported"
):
super().__init__(message.format(version))
class RepositoryNotSupported(Exception):
"""Unknown repository"""
def __init__(self, repo: str, message: str = "Repository {} is unknown"):
super().__init__(message.format(repo))
| [
"# Copyright 2020 Red Hat, Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nclass DistroNotSupported(Exception):\n \"\"\"Distribution is not supported\"\"\"\n\n def __init__(\n self,\n distro_id: str,\n message: str = \"Distribution {} is not currently supported\",\n ):\n super().__init__(message.format(distro_id))\n\n\nclass SubscriptionManagerConfigError(Exception):\n \"\"\"Subscription manager not configured correctly\"\"\"\n\n def __init__( # pylint: disable=useless-super-delegation\n self,\n message: str = \"Red Hat Subscription Manager is not currently configured correctly\",\n ):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(\n self, cmd_line: str, message: str = \"Failed running subscription-manager {}\"\n ):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(\n self, version: str, message: str = \"Version {} is not currently supported\"\n ):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str = \"Repository {} is unknown\"):\n super().__init__(message.format(repo))\n",
"class DistroNotSupported(Exception):\n \"\"\"Distribution is not supported\"\"\"\n\n def __init__(self, distro_id: str, message: str=\n 'Distribution {} is not currently supported'):\n super().__init__(message.format(distro_id))\n\n\nclass SubscriptionManagerConfigError(Exception):\n \"\"\"Subscription manager not configured correctly\"\"\"\n\n def __init__(self, message: str=\n 'Red Hat Subscription Manager is not currently configured correctly'):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"class DistroNotSupported(Exception):\n <docstring token>\n\n def __init__(self, distro_id: str, message: str=\n 'Distribution {} is not currently supported'):\n super().__init__(message.format(distro_id))\n\n\nclass SubscriptionManagerConfigError(Exception):\n \"\"\"Subscription manager not configured correctly\"\"\"\n\n def __init__(self, message: str=\n 'Red Hat Subscription Manager is not currently configured correctly'):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"class DistroNotSupported(Exception):\n <docstring token>\n <function token>\n\n\nclass SubscriptionManagerConfigError(Exception):\n \"\"\"Subscription manager not configured correctly\"\"\"\n\n def __init__(self, message: str=\n 'Red Hat Subscription Manager is not currently configured correctly'):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n\n\nclass SubscriptionManagerConfigError(Exception):\n \"\"\"Subscription manager not configured correctly\"\"\"\n\n def __init__(self, message: str=\n 'Red Hat Subscription Manager is not currently configured correctly'):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n\n\nclass SubscriptionManagerConfigError(Exception):\n <docstring token>\n\n def __init__(self, message: str=\n 'Red Hat Subscription Manager is not currently configured correctly'):\n super().__init__(message)\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n\n\nclass SubscriptionManagerConfigError(Exception):\n <docstring token>\n <function token>\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n\n\nclass SubscriptionManagerFailure(Exception):\n \"\"\"Subscription manager failed\"\"\"\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n\n\nclass SubscriptionManagerFailure(Exception):\n <docstring token>\n\n def __init__(self, cmd_line: str, message: str=\n 'Failed running subscription-manager {}'):\n super().__init__(message.format(cmd_line))\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n\n\nclass SubscriptionManagerFailure(Exception):\n <docstring token>\n <function token>\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n\n\nclass VersionNotSupported(Exception):\n \"\"\"Version is not supported\"\"\"\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n\n\nclass VersionNotSupported(Exception):\n <docstring token>\n\n def __init__(self, version: str, message: str=\n 'Version {} is not currently supported'):\n super().__init__(message.format(version))\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n\n\nclass VersionNotSupported(Exception):\n <docstring token>\n <function token>\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RepositoryNotSupported(Exception):\n \"\"\"Unknown repository\"\"\"\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RepositoryNotSupported(Exception):\n <docstring token>\n\n def __init__(self, repo: str, message: str='Repository {} is unknown'):\n super().__init__(message.format(repo))\n",
"<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RepositoryNotSupported(Exception):\n <docstring token>\n <function token>\n",
"<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n"
] | false |
99,957 | dff58769b0084bf6f2da86ec47ed0ac6c336bf15 | import numpy as np
def find_rank(arr):
a = np.array(arr)
r = np.array(a.argsort().argsort(), dtype=float)
f = a==a
for i in xrange(len(a)):
if not f[i]:
continue
s = a == a[i]
ls = np.sum(s)
if ls > 1:
tr = np.sum(r[s])
r[s] = float(tr)/ls
f[s] = False
return r
if __name__ == '__main__':
print find_rank([1, 2, 3])
print find_rank([1, 3, 2])
print find_rank([1, 3, 1])
print find_rank([1, 1, 1])
| [
"import numpy as np\n\ndef find_rank(arr):\n a = np.array(arr)\n r = np.array(a.argsort().argsort(), dtype=float)\n f = a==a\n for i in xrange(len(a)):\n if not f[i]: \n continue\n s = a == a[i]\n ls = np.sum(s)\n if ls > 1:\n tr = np.sum(r[s])\n r[s] = float(tr)/ls\n f[s] = False\n return r\n\nif __name__ == '__main__':\n print find_rank([1, 2, 3])\n print find_rank([1, 3, 2])\n print find_rank([1, 3, 1])\n print find_rank([1, 1, 1])\n"
] | true |
99,958 | cdb44b7ac0fb0d4e24786741de3ccb3440aff67e | from django.db import models
from djongo import models as djongo_models
class CourseScore(models.Model):
course_name = models.CharField(max_length=4)
student_name = models.CharField(max_length=16)
score = models.IntegerField()
# the manager for postgres
objects = models.Manager()
# the djongo manager for mongodb
mobjects = djongo_models.DjongoManager()
| [
"from django.db import models\nfrom djongo import models as djongo_models\n\n\nclass CourseScore(models.Model):\n\n course_name = models.CharField(max_length=4)\n student_name = models.CharField(max_length=16)\n score = models.IntegerField()\n\n # the manager for postgres\n objects = models.Manager()\n # the djongo manager for mongodb\n mobjects = djongo_models.DjongoManager()\n",
"from django.db import models\nfrom djongo import models as djongo_models\n\n\nclass CourseScore(models.Model):\n course_name = models.CharField(max_length=4)\n student_name = models.CharField(max_length=16)\n score = models.IntegerField()\n objects = models.Manager()\n mobjects = djongo_models.DjongoManager()\n",
"<import token>\n\n\nclass CourseScore(models.Model):\n course_name = models.CharField(max_length=4)\n student_name = models.CharField(max_length=16)\n score = models.IntegerField()\n objects = models.Manager()\n mobjects = djongo_models.DjongoManager()\n",
"<import token>\n\n\nclass CourseScore(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n",
"<import token>\n<class token>\n"
] | false |
99,959 | 679181c622282ca8b33b2217fd94336431b9d23a | def left_child(root):
return root * 2 + 1
def right_child(root):
return root * 2 + 2
def parent(child):
return (child - 1)// 2
def shift_down(a, start, end):
root = start
while True:
child = left_child(root)
if child > end:
return
swap = root
if a[swap] < a[child]:
swap = child
if child + 1 <= end and a[swap] < a[child+1]:
swap = child + 1
if swap == root:
return
else:
a[root], a[swap] = a[swap], a[root]
root = swap
def shift_up(a, start, end):
child = end
while child > start:
p = parent(child)
if a[child] > a[p]:
a[child], a[p] = a[p], a[child]
child = p
else:
return
def heapify(a):
end = len(a) - 1
start = parent(end)
while start >= 0:
shift_down(a, start, end)
start -= 1
def heap_sort(a):
sz = len(a)
if sz < 1:
return a
heapify(a)
end = sz - 1
while end > 0:
a[end], a[0] = a[0], a[end]
end -= 1
shift_down(a, 0, end)
return a
if __name__ == "__main__":
a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]
heapify(a)
print(f"After {a}")
a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]
print(f"Before sorting {a}")
a = heap_sort(a)
print(f"After sorting {a}") | [
"def left_child(root):\n return root * 2 + 1\n\n\ndef right_child(root):\n return root * 2 + 2\n\n\ndef parent(child):\n return (child - 1)// 2\n\n\ndef shift_down(a, start, end):\n root = start\n\n while True:\n child = left_child(root)\n if child > end:\n return\n swap = root\n if a[swap] < a[child]:\n swap = child\n\n if child + 1 <= end and a[swap] < a[child+1]:\n swap = child + 1\n\n if swap == root:\n return\n else:\n a[root], a[swap] = a[swap], a[root]\n root = swap\n\n\ndef shift_up(a, start, end):\n child = end\n while child > start:\n p = parent(child)\n if a[child] > a[p]:\n a[child], a[p] = a[p], a[child]\n child = p\n else:\n return\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\nif __name__ == \"__main__\":\n a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]\n heapify(a)\n print(f\"After {a}\")\n a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]\n print(f\"Before sorting {a}\")\n a = heap_sort(a)\n print(f\"After sorting {a}\")",
"def left_child(root):\n return root * 2 + 1\n\n\ndef right_child(root):\n return root * 2 + 2\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\ndef shift_down(a, start, end):\n root = start\n while True:\n child = left_child(root)\n if child > end:\n return\n swap = root\n if a[swap] < a[child]:\n swap = child\n if child + 1 <= end and a[swap] < a[child + 1]:\n swap = child + 1\n if swap == root:\n return\n else:\n a[root], a[swap] = a[swap], a[root]\n root = swap\n\n\ndef shift_up(a, start, end):\n child = end\n while child > start:\n p = parent(child)\n if a[child] > a[p]:\n a[child], a[p] = a[p], a[child]\n child = p\n else:\n return\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\nif __name__ == '__main__':\n a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]\n heapify(a)\n print(f'After {a}')\n a = [8650, 8657, 8460, 3277, 6223, 6864, 5264, 6042, 9821, 204]\n print(f'Before sorting {a}')\n a = heap_sort(a)\n print(f'After sorting {a}')\n",
"def left_child(root):\n return root * 2 + 1\n\n\ndef right_child(root):\n return root * 2 + 2\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\ndef shift_down(a, start, end):\n root = start\n while True:\n child = left_child(root)\n if child > end:\n return\n swap = root\n if a[swap] < a[child]:\n swap = child\n if child + 1 <= end and a[swap] < a[child + 1]:\n swap = child + 1\n if swap == root:\n return\n else:\n a[root], a[swap] = a[swap], a[root]\n root = swap\n\n\ndef shift_up(a, start, end):\n child = end\n while child > start:\n p = parent(child)\n if a[child] > a[p]:\n a[child], a[p] = a[p], a[child]\n child = p\n else:\n return\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\n<code token>\n",
"def left_child(root):\n return root * 2 + 1\n\n\ndef right_child(root):\n return root * 2 + 2\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\ndef shift_down(a, start, end):\n root = start\n while True:\n child = left_child(root)\n if child > end:\n return\n swap = root\n if a[swap] < a[child]:\n swap = child\n if child + 1 <= end and a[swap] < a[child + 1]:\n swap = child + 1\n if swap == root:\n return\n else:\n a[root], a[swap] = a[swap], a[root]\n root = swap\n\n\n<function token>\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\n<code token>\n",
"def left_child(root):\n return root * 2 + 1\n\n\n<function token>\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\ndef shift_down(a, start, end):\n root = start\n while True:\n child = left_child(root)\n if child > end:\n return\n swap = root\n if a[swap] < a[child]:\n swap = child\n if child + 1 <= end and a[swap] < a[child + 1]:\n swap = child + 1\n if swap == root:\n return\n else:\n a[root], a[swap] = a[swap], a[root]\n root = swap\n\n\n<function token>\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\n<code token>\n",
"def left_child(root):\n return root * 2 + 1\n\n\n<function token>\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\n<function token>\n<function token>\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\n<code token>\n",
"<function token>\n<function token>\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\n<function token>\n<function token>\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\ndef heap_sort(a):\n sz = len(a)\n if sz < 1:\n return a\n heapify(a)\n end = sz - 1\n while end > 0:\n a[end], a[0] = a[0], a[end]\n end -= 1\n shift_down(a, 0, end)\n return a\n\n\n<code token>\n",
"<function token>\n<function token>\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\n<function token>\n<function token>\n\n\ndef heapify(a):\n end = len(a) - 1\n start = parent(end)\n while start >= 0:\n shift_down(a, start, end)\n start -= 1\n\n\n<function token>\n<code token>\n",
"<function token>\n<function token>\n\n\ndef parent(child):\n return (child - 1) // 2\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<code 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,960 | 9a24790d67d5a53c540fafa734240354fb7a684e | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from efficient_apriori import apriori
# header=None,不将第一行作为head
dataset = pd.read_csv('./Market_Basket_Optimisation.csv', header = None)
# shape为(7501,20)
print(dataset.shape)
# 将数据存放到transactions中
transactions = []
for i in range(0, dataset.shape[0]): # 按照行进行遍历
temp = []
for j in range(0, dataset.shape[1]): # 按照列进行遍历 for j in range(0, 20):
if str(dataset.values[i, j]) != 'nan':
temp.append(str(dataset.values[i, j]))
transactions.append(temp)
#print(transactions)
# 挖掘频繁项集和频繁规则
itemsets, rules = apriori(transactions, min_support=0.03, min_confidence=0.4)
print("频繁项集:", itemsets)
print("关联规则:", rules)
# 陈博士,
# 请问从关联规则得出以下结论是否正确:
# 1 买牛肉的人,有大于40%的概率会去买矿泉水。
# 2 买牛肉与买矿泉水组合出现的概率大于3%
#
# 关于天池的那道题:
# 是否可以把训练集切片30%,作为测试集。那么就知道预测效果好不好了(因为天池最多只能递交5次)
| [
"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom efficient_apriori import apriori\r\n\r\n# header=None,不将第一行作为head\r\ndataset = pd.read_csv('./Market_Basket_Optimisation.csv', header = None) \r\n# shape为(7501,20)\r\nprint(dataset.shape)\r\n\r\n# 将数据存放到transactions中\r\ntransactions = []\r\nfor i in range(0, dataset.shape[0]): # 按照行进行遍历\r\n temp = []\r\n for j in range(0, dataset.shape[1]): # 按照列进行遍历 for j in range(0, 20):\r\n if str(dataset.values[i, j]) != 'nan':\r\n temp.append(str(dataset.values[i, j]))\r\n transactions.append(temp)\r\n#print(transactions)\r\n# 挖掘频繁项集和频繁规则\r\nitemsets, rules = apriori(transactions, min_support=0.03, min_confidence=0.4)\r\nprint(\"频繁项集:\", itemsets)\r\nprint(\"关联规则:\", rules)\r\n\r\n# 陈博士,\r\n# 请问从关联规则得出以下结论是否正确:\r\n# 1 买牛肉的人,有大于40%的概率会去买矿泉水。\r\n# 2 买牛肉与买矿泉水组合出现的概率大于3%\r\n#\r\n# 关于天池的那道题:\r\n# 是否可以把训练集切片30%,作为测试集。那么就知道预测效果好不好了(因为天池最多只能递交5次)\r\n",
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom efficient_apriori import apriori\ndataset = pd.read_csv('./Market_Basket_Optimisation.csv', header=None)\nprint(dataset.shape)\ntransactions = []\nfor i in range(0, dataset.shape[0]):\n temp = []\n for j in range(0, dataset.shape[1]):\n if str(dataset.values[i, j]) != 'nan':\n temp.append(str(dataset.values[i, j]))\n transactions.append(temp)\nitemsets, rules = apriori(transactions, min_support=0.03, min_confidence=0.4)\nprint('频繁项集:', itemsets)\nprint('关联规则:', rules)\n",
"<import token>\ndataset = pd.read_csv('./Market_Basket_Optimisation.csv', header=None)\nprint(dataset.shape)\ntransactions = []\nfor i in range(0, dataset.shape[0]):\n temp = []\n for j in range(0, dataset.shape[1]):\n if str(dataset.values[i, j]) != 'nan':\n temp.append(str(dataset.values[i, j]))\n transactions.append(temp)\nitemsets, rules = apriori(transactions, min_support=0.03, min_confidence=0.4)\nprint('频繁项集:', itemsets)\nprint('关联规则:', rules)\n",
"<import token>\n<assignment token>\nprint(dataset.shape)\n<assignment token>\nfor i in range(0, dataset.shape[0]):\n temp = []\n for j in range(0, dataset.shape[1]):\n if str(dataset.values[i, j]) != 'nan':\n temp.append(str(dataset.values[i, j]))\n transactions.append(temp)\n<assignment token>\nprint('频繁项集:', itemsets)\nprint('关联规则:', rules)\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,961 | 13f7e99aedb4b5a049a53f68738d5447f9ca63c2 | import pprint
import os
import sqlite3
from td.client import TDClient
from datetime import datetime
pp = pprint.PrettyPrinter()
conn = sqlite3.connect(os.environ.get('DB_NAME'))
# Create a new session, credentials path is required.
TDSession = TDClient(
client_id=os.environ.get('CLIENT_ID'),
redirect_uri='https://localhost/callback',
credentials_path='td_credentials.json'
)
# Login to the session
TDSession.login()
# `get_transactions` Endpoint. Should not return an error
accounts = TDSession.get_accounts(account=os.environ.get('ACCOUNT_ID'))
a = accounts['securitiesAccount']
b = accounts['securitiesAccount']['currentBalances']
conn.execute('insert into accounts values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [datetime.today(),a['type'], a['accountId'], b['accruedInterest'], b['cashBalance'], b['longOptionMarketValue'], b['liquidationValue'], b['longMarketValue'], b['availableFunds'], b['buyingPower'], b['dayTradingBuyingPower'], b['equity'], b['equityPercentage'], b['longMarginValue'], b['maintenanceRequirement'], b['marginBalance']])
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
| [
"import pprint\nimport os\nimport sqlite3\nfrom td.client import TDClient\nfrom datetime import datetime\n\npp = pprint.PrettyPrinter()\nconn = sqlite3.connect(os.environ.get('DB_NAME'))\n\n# Create a new session, credentials path is required.\nTDSession = TDClient(\n client_id=os.environ.get('CLIENT_ID'),\n redirect_uri='https://localhost/callback',\n credentials_path='td_credentials.json'\n)\n\n# Login to the session\nTDSession.login()\n\n# `get_transactions` Endpoint. Should not return an error\naccounts = TDSession.get_accounts(account=os.environ.get('ACCOUNT_ID'))\na = accounts['securitiesAccount']\nb = accounts['securitiesAccount']['currentBalances']\nconn.execute('insert into accounts values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [datetime.today(),a['type'], a['accountId'], b['accruedInterest'], b['cashBalance'], b['longOptionMarketValue'], b['liquidationValue'], b['longMarketValue'], b['availableFunds'], b['buyingPower'], b['dayTradingBuyingPower'], b['equity'], b['equityPercentage'], b['longMarginValue'], b['maintenanceRequirement'], b['marginBalance']])\n\n# Save (commit) the changes\nconn.commit()\n\n# We can also close the connection if we are done with it.\n# Just be sure any changes have been committed or they will be lost.\nconn.close()\n",
"import pprint\nimport os\nimport sqlite3\nfrom td.client import TDClient\nfrom datetime import datetime\npp = pprint.PrettyPrinter()\nconn = sqlite3.connect(os.environ.get('DB_NAME'))\nTDSession = TDClient(client_id=os.environ.get('CLIENT_ID'), redirect_uri=\n 'https://localhost/callback', credentials_path='td_credentials.json')\nTDSession.login()\naccounts = TDSession.get_accounts(account=os.environ.get('ACCOUNT_ID'))\na = accounts['securitiesAccount']\nb = accounts['securitiesAccount']['currentBalances']\nconn.execute('insert into accounts values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n [datetime.today(), a['type'], a['accountId'], b['accruedInterest'], b[\n 'cashBalance'], b['longOptionMarketValue'], b['liquidationValue'], b[\n 'longMarketValue'], b['availableFunds'], b['buyingPower'], b[\n 'dayTradingBuyingPower'], b['equity'], b['equityPercentage'], b[\n 'longMarginValue'], b['maintenanceRequirement'], b['marginBalance']])\nconn.commit()\nconn.close()\n",
"<import token>\npp = pprint.PrettyPrinter()\nconn = sqlite3.connect(os.environ.get('DB_NAME'))\nTDSession = TDClient(client_id=os.environ.get('CLIENT_ID'), redirect_uri=\n 'https://localhost/callback', credentials_path='td_credentials.json')\nTDSession.login()\naccounts = TDSession.get_accounts(account=os.environ.get('ACCOUNT_ID'))\na = accounts['securitiesAccount']\nb = accounts['securitiesAccount']['currentBalances']\nconn.execute('insert into accounts values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n [datetime.today(), a['type'], a['accountId'], b['accruedInterest'], b[\n 'cashBalance'], b['longOptionMarketValue'], b['liquidationValue'], b[\n 'longMarketValue'], b['availableFunds'], b['buyingPower'], b[\n 'dayTradingBuyingPower'], b['equity'], b['equityPercentage'], b[\n 'longMarginValue'], b['maintenanceRequirement'], b['marginBalance']])\nconn.commit()\nconn.close()\n",
"<import token>\n<assignment token>\nTDSession.login()\n<assignment token>\nconn.execute('insert into accounts values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',\n [datetime.today(), a['type'], a['accountId'], b['accruedInterest'], b[\n 'cashBalance'], b['longOptionMarketValue'], b['liquidationValue'], b[\n 'longMarketValue'], b['availableFunds'], b['buyingPower'], b[\n 'dayTradingBuyingPower'], b['equity'], b['equityPercentage'], b[\n 'longMarginValue'], b['maintenanceRequirement'], b['marginBalance']])\nconn.commit()\nconn.close()\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,962 | 940f3a3a5c7936bf4e7e429e3c3088d09a64f6dd | # coding=utf-8
import requests
from bs4 import BeautifulSoup
url = "http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0"
page = requests.get(url).text
soup = BeautifulSoup(page,"lxml")
tayara_listing = soup.find("div", class_="moment")
tayara_item = tayara_listing.find_all("div", class_="moment-content")
for tayara_title in tayara_item:
tayara_info = tayara_title.find("div", class_="moment-image")
print(tayara_info.img)
tayara_msg = tayara_title.find("div", class_="moment-theme")
print(tayara_msg.p)
tayara_cap = tayara_title.find("div", class_="moment-caption")
print(tayara_cap.p)
tayara_audio = tayara_title.find("div", class_="moment-audio")
print(tayara_audio.source)
| [
"# coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0\"\npage = requests.get(url).text\nsoup = BeautifulSoup(page,\"lxml\")\n\ntayara_listing = soup.find(\"div\", class_=\"moment\")\ntayara_item = tayara_listing.find_all(\"div\", class_=\"moment-content\")\n\nfor tayara_title in tayara_item:\n tayara_info = tayara_title.find(\"div\", class_=\"moment-image\")\n print(tayara_info.img)\n tayara_msg = tayara_title.find(\"div\", class_=\"moment-theme\")\n print(tayara_msg.p)\n tayara_cap = tayara_title.find(\"div\", class_=\"moment-caption\")\n print(tayara_cap.p)\n tayara_audio = tayara_title.find(\"div\", class_=\"moment-audio\")\n print(tayara_audio.source)\n",
"import requests\nfrom bs4 import BeautifulSoup\nurl = (\n 'http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0'\n )\npage = requests.get(url).text\nsoup = BeautifulSoup(page, 'lxml')\ntayara_listing = soup.find('div', class_='moment')\ntayara_item = tayara_listing.find_all('div', class_='moment-content')\nfor tayara_title in tayara_item:\n tayara_info = tayara_title.find('div', class_='moment-image')\n print(tayara_info.img)\n tayara_msg = tayara_title.find('div', class_='moment-theme')\n print(tayara_msg.p)\n tayara_cap = tayara_title.find('div', class_='moment-caption')\n print(tayara_cap.p)\n tayara_audio = tayara_title.find('div', class_='moment-audio')\n print(tayara_audio.source)\n",
"<import token>\nurl = (\n 'http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0'\n )\npage = requests.get(url).text\nsoup = BeautifulSoup(page, 'lxml')\ntayara_listing = soup.find('div', class_='moment')\ntayara_item = tayara_listing.find_all('div', class_='moment-content')\nfor tayara_title in tayara_item:\n tayara_info = tayara_title.find('div', class_='moment-image')\n print(tayara_info.img)\n tayara_msg = tayara_title.find('div', class_='moment-theme')\n print(tayara_msg.p)\n tayara_cap = tayara_title.find('div', class_='moment-caption')\n print(tayara_cap.p)\n tayara_audio = tayara_title.find('div', class_='moment-audio')\n print(tayara_audio.source)\n",
"<import token>\n<assignment token>\nfor tayara_title in tayara_item:\n tayara_info = tayara_title.find('div', class_='moment-image')\n print(tayara_info.img)\n tayara_msg = tayara_title.find('div', class_='moment-theme')\n print(tayara_msg.p)\n tayara_cap = tayara_title.find('div', class_='moment-caption')\n print(tayara_cap.p)\n tayara_audio = tayara_title.find('div', class_='moment-audio')\n print(tayara_audio.source)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,963 | 4df299857e9abc20bc162ef283ae3679251ed32d | reddit_categories = ['hot', 'new', 'controversial', 'rising', 'top']
async def get_subreddit_json(session, subreddit, category):
return await get_json(session, 'https://www.reddit.com/r/' + subreddit + '/' + category + '/.json')
async def get_json(session, url):
async with session.get(url) as resp:
return await resp.json()
async def get_reddit_post_from_json(post_data: dict):
post = post_data['data']
score = post['score']
author = post['author']
is_nsfw = post['over_18']
link = post['url']
title = post['title']
return '**Title:** {0}\n**Link:** <{1}>\n**Author:** {2}\n**Score:** {3}\n**NSFW:** {4}'.format(
title, link, author, score, is_nsfw)
async def get_reddit_posts(sr_posts, num):
posts = []
i = 0
for post in sr_posts:
if i >= num:
break
posts.append(await get_reddit_post_from_json(post))
i += 1
return posts
async def get_subreddit_top(session, subreddit, num, category):
try:
sr_data = await get_subreddit_json(session, subreddit, category)
sr_posts = sr_data['data']['children']
except KeyError:
return ['Posts could not be loaded, are you sure thats a subreddit?']
return await get_reddit_posts(sr_posts, num)
| [
"reddit_categories = ['hot', 'new', 'controversial', 'rising', 'top']\n\nasync def get_subreddit_json(session, subreddit, category):\n return await get_json(session, 'https://www.reddit.com/r/' + subreddit + '/' + category + '/.json')\n\nasync def get_json(session, url):\n async with session.get(url) as resp:\n return await resp.json()\n\nasync def get_reddit_post_from_json(post_data: dict):\n post = post_data['data']\n score = post['score']\n author = post['author']\n is_nsfw = post['over_18']\n link = post['url']\n title = post['title']\n return '**Title:** {0}\\n**Link:** <{1}>\\n**Author:** {2}\\n**Score:** {3}\\n**NSFW:** {4}'.format(\n title, link, author, score, is_nsfw)\n\nasync def get_reddit_posts(sr_posts, num):\n posts = []\n i = 0\n for post in sr_posts:\n if i >= num:\n break\n posts.append(await get_reddit_post_from_json(post))\n i += 1\n return posts\n\nasync def get_subreddit_top(session, subreddit, num, category):\n try:\n sr_data = await get_subreddit_json(session, subreddit, category)\n sr_posts = sr_data['data']['children']\n except KeyError:\n return ['Posts could not be loaded, are you sure thats a subreddit?']\n return await get_reddit_posts(sr_posts, num)\n",
"reddit_categories = ['hot', 'new', 'controversial', 'rising', 'top']\n\n\nasync def get_subreddit_json(session, subreddit, category):\n return await get_json(session, 'https://www.reddit.com/r/' + subreddit +\n '/' + category + '/.json')\n\n\nasync def get_json(session, url):\n async with session.get(url) as resp:\n return await resp.json()\n\n\nasync def get_reddit_post_from_json(post_data: dict):\n post = post_data['data']\n score = post['score']\n author = post['author']\n is_nsfw = post['over_18']\n link = post['url']\n title = post['title']\n return (\n '**Title:** {0}\\n**Link:** <{1}>\\n**Author:** {2}\\n**Score:** {3}\\n**NSFW:** {4}'\n .format(title, link, author, score, is_nsfw))\n\n\nasync def get_reddit_posts(sr_posts, num):\n posts = []\n i = 0\n for post in sr_posts:\n if i >= num:\n break\n posts.append(await get_reddit_post_from_json(post))\n i += 1\n return posts\n\n\nasync def get_subreddit_top(session, subreddit, num, category):\n try:\n sr_data = await get_subreddit_json(session, subreddit, category)\n sr_posts = sr_data['data']['children']\n except KeyError:\n return ['Posts could not be loaded, are you sure thats a subreddit?']\n return await get_reddit_posts(sr_posts, num)\n",
"<assignment token>\n\n\nasync def get_subreddit_json(session, subreddit, category):\n return await get_json(session, 'https://www.reddit.com/r/' + subreddit +\n '/' + category + '/.json')\n\n\nasync def get_json(session, url):\n async with session.get(url) as resp:\n return await resp.json()\n\n\nasync def get_reddit_post_from_json(post_data: dict):\n post = post_data['data']\n score = post['score']\n author = post['author']\n is_nsfw = post['over_18']\n link = post['url']\n title = post['title']\n return (\n '**Title:** {0}\\n**Link:** <{1}>\\n**Author:** {2}\\n**Score:** {3}\\n**NSFW:** {4}'\n .format(title, link, author, score, is_nsfw))\n\n\nasync def get_reddit_posts(sr_posts, num):\n posts = []\n i = 0\n for post in sr_posts:\n if i >= num:\n break\n posts.append(await get_reddit_post_from_json(post))\n i += 1\n return posts\n\n\nasync def get_subreddit_top(session, subreddit, num, category):\n try:\n sr_data = await get_subreddit_json(session, subreddit, category)\n sr_posts = sr_data['data']['children']\n except KeyError:\n return ['Posts could not be loaded, are you sure thats a subreddit?']\n return await get_reddit_posts(sr_posts, num)\n",
"<assignment token>\n<code token>\n"
] | false |
99,964 | b015a5d7a956c836722b262426b7a89bcce907e2 | import sys
import requests
import json
from requests import Request, Session
from requests.auth import HTTPBasicAuth
import argparse
from SwarmClient import Swarm
from JiraClient import Jira
import Config
if __name__ == '__main__':
swarm = Swarm()
jira = Jira()
parser = argparse.ArgumentParser( epilog="WARRNING: -a, --all will update all Jiras in the search range specified in the config!!!")
parser.add_argument("-u", "--user", help="Update user Jiras",
action="store_true")
parser.add_argument("-a", "--all", help="Update all Jiras",
action="store_true")
args = parser.parse_args()
if args.user or not len(sys.argv) > 1:
changes = swarm.LoadUserChanges()
elif args.all:
changes = swarm.LoadAllChanges()
for item in changes:
print jira.HasLinkedItem(item.description, item.change)
if not jira.HasLinkedItem(item.description, item.change):
print str(item.change) + " " + str(item.description) + " " + Config.settings['swarm_server'] + str(
item.url) + " Added the link to the Jira."
jira.AddLinkedItem(str(item.change), Config.settings['swarm_server'] + str(item.url), str(item.description))
else:
print str(item.change) + " " + str(item.description) + " " + Config.settings['swarm_server'] + str(
item.url) + " The remote link already exists."
| [
"import sys\nimport requests\nimport json\nfrom requests import Request, Session\nfrom requests.auth import HTTPBasicAuth\nimport argparse\nfrom SwarmClient import Swarm\nfrom JiraClient import Jira\nimport Config\n\n\nif __name__ == '__main__':\n swarm = Swarm()\n jira = Jira()\n parser = argparse.ArgumentParser( epilog=\"WARRNING: -a, --all will update all Jiras in the search range specified in the config!!!\")\n parser.add_argument(\"-u\", \"--user\", help=\"Update user Jiras\",\n action=\"store_true\")\n parser.add_argument(\"-a\", \"--all\", help=\"Update all Jiras\",\n action=\"store_true\")\n args = parser.parse_args()\n if args.user or not len(sys.argv) > 1:\n changes = swarm.LoadUserChanges()\n\n elif args.all:\n changes = swarm.LoadAllChanges()\n\n for item in changes:\n\n print jira.HasLinkedItem(item.description, item.change)\n\n if not jira.HasLinkedItem(item.description, item.change):\n print str(item.change) + \" \" + str(item.description) + \" \" + Config.settings['swarm_server'] + str(\n item.url) + \" Added the link to the Jira.\"\n jira.AddLinkedItem(str(item.change), Config.settings['swarm_server'] + str(item.url), str(item.description))\n else:\n print str(item.change) + \" \" + str(item.description) + \" \" + Config.settings['swarm_server'] + str(\n item.url) + \" The remote link already exists.\"\n"
] | true |
99,965 | b6051496357dabc0ede873ceebb4054ff46e4d3d | from django.conf.urls import url
from user.views import login, login_validate, join_page, about
urlpatterns = [
url(r'^login/$', login),
url(r'^login/validate/$', login_validate),
url(r'^join/$', join_page),
url(r'^about/$', about),
] | [
"from django.conf.urls import url\r\n\r\nfrom user.views import login, login_validate, join_page, about\r\n\r\nurlpatterns = [\r\n url(r'^login/$', login),\r\n url(r'^login/validate/$', login_validate),\r\n url(r'^join/$', join_page),\r\n url(r'^about/$', about),\r\n]",
"from django.conf.urls import url\nfrom user.views import login, login_validate, join_page, about\nurlpatterns = [url('^login/$', login), url('^login/validate/$',\n login_validate), url('^join/$', join_page), url('^about/$', about)]\n",
"<import token>\nurlpatterns = [url('^login/$', login), url('^login/validate/$',\n login_validate), url('^join/$', join_page), url('^about/$', about)]\n",
"<import token>\n<assignment token>\n"
] | false |
99,966 | 19110b2767433c84dfab6ba28892923b00e99776 | import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional ,Dropout
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import numpy as np
def lesson4_1() :
# https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/Course%203%20-%20Week%204%20-%20Lesson%201%20-%20Notebook.ipynb#scrollTo=PRnDnCW-Z7qv
tokenizer = Tokenizer()
data="In the town of Athy one Jeremy Lanigan \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \nJudy ODaly, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young Terrance McCarthy \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, Ned Morgan, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big Phelim McHugh. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \nOld Casey, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball."
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
print(tokenizer.word_index)
print(total_words) ## 단어 총 수
input_sequences = []
## 한 문장당 단어씩 잘라서
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i + 1]
input_sequences.append(n_gram_sequence)
# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
xs, labels = input_sequences[:, :-1], input_sequences[:, -1]
# one hot encoding => 263개 중에 맞는거에 1
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
print(tokenizer.word_index['in'])
print(tokenizer.word_index['the'])
print(tokenizer.word_index['town'])
print(tokenizer.word_index['of'])
print(tokenizer.word_index['athy'])
print(tokenizer.word_index['one'])
print(tokenizer.word_index['jeremy'])
print(tokenizer.word_index['lanigan']) ## Label
print(xs[6])
# [0 0 0 4 2 66 8 67 68 69]
print(ys[6])
'''
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
'''
print(xs[5])
print(ys[5])
'''
[ 0 0 0 0 4 2 66 8 67 68]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
'''
print(tokenizer.word_index)
model = Sequential()
model.add(Embedding(total_words, 64, input_length=max_sequence_len - 1)) ## max_sequence_len - 1 => 라벨을 얻기 위해 뒤에서 하나 뺏기 때문
model.add(Bidirectional(LSTM(20))) ## 양방향을 하면 보다 더 자연스러운 추측이 가능하다 .
model.add(Dense(total_words, activation='softmax')) ## total_words => 원핫 인코딩과 같은 크기 , 단어 하나당 하나의 뉴런이 존재
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ## 범주 예측
history = model.fit(xs, ys, epochs=500, verbose=1)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.show()
plot_graphs(history, 'accuracy')
## 예측
'''
Laurence 는 없는 단어이기 때문에 패스 하고 있는 단어들을 이용하여 찾는다
'''
seed_text = "Laurence went to dublin"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
def Poetry() :
# https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/Course%203%20-%20Week%204%20-%20Lesson%202%20-%20Notebook.ipynb
# wget --no-check-certificate https://storage.googleapis.com/laurencemoroney-blog.appspot.com/irish-lyrics-eof.txt -O ./tmp/irish-lyrics-eof.txt
tokenizer = Tokenizer()
data = open('./tmp/irish-lyrics-eof.txt').read()
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
print(tokenizer.word_index)
print(total_words)
input_sequences = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
print("len token_list : " , len(token_list))
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
xs, labels = input_sequences[:,:-1],input_sequences[:,-1]
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
print(tokenizer.word_index['in'])
print(tokenizer.word_index['the'])
print(tokenizer.word_index['town'])
print(tokenizer.word_index['of'])
print(tokenizer.word_index['athy'])
print(tokenizer.word_index['one'])
print(tokenizer.word_index['jeremy'])
print(tokenizer.word_index['lanigan'])
print(xs[6])
print(ys[6])
print(tokenizer.word_index)
model = Sequential()
model.add(Embedding(total_words, 100, input_length=max_sequence_len-1))
model.add(Bidirectional(LSTM(150)))
model.add(Dense(total_words, activation='softmax'))
adam = Adam(lr=0.01)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
#earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
model.summary()
history = model.fit(xs, ys, epochs=100, verbose=1)
print(model)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.show()
plot_graphs(history, 'accuracy')
seed_text = "I've got a bad feeling about this"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
def HaveToTest () :
#https://www.tensorflow.org/tutorials/text/text_generation
print("https://www.tensorflow.org/tutorials/text/text_generation")
'''
In this course you’ve done a lot of NLP and text processing.
This week you trained with a dataset of Irish songs to create traditional-sounding poetry.
For this week’s exercise, you’ll take a corpus of Shakespeare sonnets, and use them to train a model.
Then, see if that model can create poetry!
'''
def Exercise() :
#https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/NLP_Week4_Exercise_Shakespeare_Question.ipynb
#https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/NLP_Week4_Exercise_Shakespeare_Answer.ipynb
## !wget --no-check-certificate https://storage.googleapis.com/laurencemoroney-blog.appspot.com/sonnets.txt -O ./tmp/sonnets.txt
import tensorflow.keras.utils as ku
tokenizer = Tokenizer()
data = open('./tmp/sonnets.txt').read()
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
# create input sequences using list of tokens
input_sequences = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i + 1]
input_sequences.append(n_gram_sequence)
# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
predictors, label = input_sequences[:, :-1], input_sequences[:, -1]
label = ku.to_categorical(label, num_classes=total_words)
model = Sequential()
model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))
model.add(Bidirectional(LSTM(150, return_sequences=True)))
model.add(Dropout(0.2))
model.add(LSTM(100))
model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=regularizers.l2(0.01)))
model.add(Dense(total_words, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
'''
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding (Embedding) (None, 10, 100) 321100
_________________________________________________________________
bidirectional (Bidirectional (None, 10, 300) 301200
_________________________________________________________________
dropout (Dropout) (None, 10, 300) 0
_________________________________________________________________
lstm_1 (LSTM) (None, 100) 160400
_________________________________________________________________
dense (Dense) (None, 1605) 162105
_________________________________________________________________
dense_1 (Dense) (None, 3211) 5156866
=================================================================
Total params: 6,101,671
Trainable params: 6,101,671
Non-trainable params: 0
_________________________________________________________________
None
'''
history = model.fit(predictors, label, epochs=100, verbose=1)
import matplotlib.pyplot as plt
acc = history.history['accuracy']
loss = history.history['loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'b', label='Training accuracy')
plt.title('Training accuracy')
plt.figure()
plt.plot(epochs, loss, 'b', label='Training Loss')
plt.title('Training loss')
plt.legend()
plt.show()
seed_text = "Help me Obi Wan Kenobi, you're my only hope"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
if __name__ == '__main__' :
HaveToTest()
# Poetry()
Exercise() | [
"import tensorflow as tf\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional ,Dropout\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nimport numpy as np\n\ndef lesson4_1() :\n # https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/Course%203%20-%20Week%204%20-%20Lesson%201%20-%20Notebook.ipynb#scrollTo=PRnDnCW-Z7qv\n tokenizer = Tokenizer()\n data=\"In the town of Athy one Jeremy Lanigan \\n Battered away til he hadnt a pound. \\nHis father died and made him a man again \\n Left him a farm and ten acres of ground. \\nHe gave a grand party for friends and relations \\nWho didnt forget him when come to the wall, \\nAnd if youll but listen Ill make your eyes glisten \\nOf the rows and the ructions of Lanigans Ball. \\nMyself to be sure got free invitation, \\nFor all the nice girls and boys I might ask, \\nAnd just in a minute both friends and relations \\nWere dancing round merry as bees round a cask. \\nJudy ODaly, that nice little milliner, \\nShe tipped me a wink for to give her a call, \\nAnd I soon arrived with Peggy McGilligan \\nJust in time for Lanigans Ball. \\nThere were lashings of punch and wine for the ladies, \\nPotatoes and cakes; there was bacon and tea, \\nThere were the Nolans, Dolans, OGradys \\nCourting the girls and dancing away. \\nSongs they went round as plenty as water, \\nThe harp that once sounded in Taras old hall,\\nSweet Nelly Gray and The Rat Catchers Daughter,\\nAll singing together at Lanigans Ball. \\nThey were doing all kinds of nonsensical polkas \\nAll round the room in a whirligig. \\nJulia and I, we banished their nonsense \\nAnd tipped them the twist of a reel and a jig. \\nAch mavrone, how the girls got all mad at me \\nDanced til youd think the ceiling would fall. \\nFor I spent three weeks at Brooks Academy \\nLearning new steps for Lanigans Ball. \\nThree long weeks I spent up in Dublin, \\nThree long weeks to learn nothing at all,\\n Three long weeks I spent up in Dublin, \\nLearning new steps for Lanigans Ball. \\nShe stepped out and I stepped in again, \\nI stepped out and she stepped in again, \\nShe stepped out and I stepped in again, \\nLearning new steps for Lanigans Ball. \\nBoys were all merry and the girls they were hearty \\nAnd danced all around in couples and groups, \\nTil an accident happened, young Terrance McCarthy \\nPut his right leg through miss Finnertys hoops. \\nPoor creature fainted and cried Meelia murther, \\nCalled for her brothers and gathered them all. \\nCarmody swore that hed go no further \\nTil he had satisfaction at Lanigans Ball. \\nIn the midst of the row miss Kerrigan fainted, \\nHer cheeks at the same time as red as a rose. \\nSome of the lads declared she was painted, \\nShe took a small drop too much, I suppose. \\nHer sweetheart, Ned Morgan, so powerful and able, \\nWhen he saw his fair colleen stretched out by the wall, \\nTore the left leg from under the table \\nAnd smashed all the Chaneys at Lanigans Ball. \\nBoys, oh boys, twas then there were runctions. \\nMyself got a lick from big Phelim McHugh. \\nI soon replied to his introduction \\nAnd kicked up a terrible hullabaloo. \\nOld Casey, the piper, was near being strangled. \\nThey squeezed up his pipes, bellows, chanters and all. \\nThe girls, in their ribbons, they got all entangled \\nAnd that put an end to Lanigans Ball.\"\n\n corpus = data.lower().split(\"\\n\")\n\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n\n print(tokenizer.word_index)\n print(total_words) ## 단어 총 수\n\n input_sequences = []\n ## 한 문장당 단어씩 잘라서\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n\n # pad sequences\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))\n\n # create predictors and label\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n\n # one hot encoding => 263개 중에 맞는거에 1\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan']) ## Label\n\n print(xs[6])\n # [0 0 0 4 2 66 8 67 68 69]\n print(ys[6])\n '''\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n '''\n\n print(xs[5])\n print(ys[5])\n '''\n [ 0 0 0 0 4 2 66 8 67 68]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n '''\n\n print(tokenizer.word_index)\n\n model = Sequential()\n model.add(Embedding(total_words, 64, input_length=max_sequence_len - 1)) ## max_sequence_len - 1 => 라벨을 얻기 위해 뒤에서 하나 뺏기 때문\n\n model.add(Bidirectional(LSTM(20))) ## 양방향을 하면 보다 더 자연스러운 추측이 가능하다 .\n model.add(Dense(total_words, activation='softmax')) ## total_words => 원핫 인코딩과 같은 크기 , 단어 하나당 하나의 뉴런이 존재\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ## 범주 예측\n\n history = model.fit(xs, ys, epochs=500, verbose=1)\n\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.show()\n\n plot_graphs(history, 'accuracy')\n\n ## 예측\n ''' \n Laurence 는 없는 단어이기 때문에 패스 하고 있는 단어들을 이용하여 찾는다 \n '''\n seed_text = \"Laurence went to dublin\"\n next_words = 100\n\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = \"\"\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += \" \" + output_word\n print(seed_text)\n\ndef Poetry() :\n# https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/Course%203%20-%20Week%204%20-%20Lesson%202%20-%20Notebook.ipynb\n# wget --no-check-certificate https://storage.googleapis.com/laurencemoroney-blog.appspot.com/irish-lyrics-eof.txt -O ./tmp/irish-lyrics-eof.txt\n tokenizer = Tokenizer()\n\n data = open('./tmp/irish-lyrics-eof.txt').read()\n\n corpus = data.lower().split(\"\\n\")\n\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n\n print(tokenizer.word_index)\n print(total_words)\n\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print(\"len token_list : \" , len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i+1]\n input_sequences.append(n_gram_sequence)\n\n # pad sequences\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))\n\n # create predictors and label\n xs, labels = input_sequences[:,:-1],input_sequences[:,-1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n\n print(xs[6])\n print(ys[6])\n\n print(tokenizer.word_index)\n\n\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len-1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\n #earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n\n print(model)\n\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.show()\n\n\n plot_graphs(history, 'accuracy')\n\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = \"\"\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += \" \" + output_word\n print(seed_text)\n\ndef HaveToTest () :\n #https://www.tensorflow.org/tutorials/text/text_generation\n print(\"https://www.tensorflow.org/tutorials/text/text_generation\")\n\n'''\n In this course you’ve done a lot of NLP and text processing. \n This week you trained with a dataset of Irish songs to create traditional-sounding poetry. \n For this week’s exercise, you’ll take a corpus of Shakespeare sonnets, and use them to train a model. \n Then, see if that model can create poetry!\n'''\ndef Exercise() :\n #https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/NLP_Week4_Exercise_Shakespeare_Question.ipynb\n #https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%203%20-%20NLP/NLP_Week4_Exercise_Shakespeare_Answer.ipynb\n ## !wget --no-check-certificate https://storage.googleapis.com/laurencemoroney-blog.appspot.com/sonnets.txt -O ./tmp/sonnets.txt\n import tensorflow.keras.utils as ku\n tokenizer = Tokenizer()\n data = open('./tmp/sonnets.txt').read()\n\n corpus = data.lower().split(\"\\n\")\n\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n\n # create input sequences using list of tokens\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n\n # pad sequences\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))\n\n # create predictors and label\n predictors, label = input_sequences[:, :-1], input_sequences[:, -1]\n\n label = ku.to_categorical(label, num_classes=total_words)\n\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150, return_sequences=True)))\n model.add(Dropout(0.2))\n model.add(LSTM(100))\n model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=regularizers.l2(0.01)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n print(model.summary())\n ''' \n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n embedding (Embedding) (None, 10, 100) 321100 \n _________________________________________________________________\n bidirectional (Bidirectional (None, 10, 300) 301200 \n _________________________________________________________________\n dropout (Dropout) (None, 10, 300) 0 \n _________________________________________________________________\n lstm_1 (LSTM) (None, 100) 160400 \n _________________________________________________________________\n dense (Dense) (None, 1605) 162105 \n _________________________________________________________________\n dense_1 (Dense) (None, 3211) 5156866 \n =================================================================\n Total params: 6,101,671\n Trainable params: 6,101,671\n Non-trainable params: 0\n _________________________________________________________________\n None\n '''\n history = model.fit(predictors, label, epochs=100, verbose=1)\n\n import matplotlib.pyplot as plt\n acc = history.history['accuracy']\n loss = history.history['loss']\n\n epochs = range(len(acc))\n\n plt.plot(epochs, acc, 'b', label='Training accuracy')\n plt.title('Training accuracy')\n\n plt.figure()\n\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.title('Training loss')\n plt.legend()\n\n plt.show()\n\n seed_text = \"Help me Obi Wan Kenobi, you're my only hope\"\n next_words = 100\n\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = \"\"\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += \" \" + output_word\n print(seed_text)\nif __name__ == '__main__' :\n HaveToTest()\n\n # Poetry()\n Exercise()",
"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional, Dropout\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nimport numpy as np\n\n\ndef lesson4_1():\n tokenizer = Tokenizer()\n data = \"\"\"In the town of Athy one Jeremy Lanigan \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \nJudy ODaly, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young Terrance McCarthy \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, Ned Morgan, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big Phelim McHugh. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \nOld Casey, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball.\"\"\"\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n \"\"\"\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(xs[5])\n print(ys[5])\n \"\"\"\n [ 0 0 0 0 4 2 66 8 67 68]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 64, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(20)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n history = model.fit(xs, ys, epochs=500, verbose=1)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n \"\"\" \n Laurence 는 없는 단어이기 때문에 패스 하고 있는 단어들을 이용하여 찾는다 \n \"\"\"\n seed_text = 'Laurence went to dublin'\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef Poetry():\n tokenizer = Tokenizer()\n data = open('./tmp/irish-lyrics-eof.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print('len token_list : ', len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=\n ['accuracy'])\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n print(model)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n\n\ndef Exercise():\n import tensorflow.keras.utils as ku\n tokenizer = Tokenizer()\n data = open('./tmp/sonnets.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n predictors, label = input_sequences[:, :-1], input_sequences[:, -1]\n label = ku.to_categorical(label, num_classes=total_words)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150, return_sequences=True)))\n model.add(Dropout(0.2))\n model.add(LSTM(100))\n model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=\n regularizers.l2(0.01)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n print(model.summary())\n \"\"\" \n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n embedding (Embedding) (None, 10, 100) 321100 \n _________________________________________________________________\n bidirectional (Bidirectional (None, 10, 300) 301200 \n _________________________________________________________________\n dropout (Dropout) (None, 10, 300) 0 \n _________________________________________________________________\n lstm_1 (LSTM) (None, 100) 160400 \n _________________________________________________________________\n dense (Dense) (None, 1605) 162105 \n _________________________________________________________________\n dense_1 (Dense) (None, 3211) 5156866 \n =================================================================\n Total params: 6,101,671\n Trainable params: 6,101,671\n Non-trainable params: 0\n _________________________________________________________________\n None\n \"\"\"\n history = model.fit(predictors, label, epochs=100, verbose=1)\n import matplotlib.pyplot as plt\n acc = history.history['accuracy']\n loss = history.history['loss']\n epochs = range(len(acc))\n plt.plot(epochs, acc, 'b', label='Training accuracy')\n plt.title('Training accuracy')\n plt.figure()\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.title('Training loss')\n plt.legend()\n plt.show()\n seed_text = \"Help me Obi Wan Kenobi, you're my only hope\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\nif __name__ == '__main__':\n HaveToTest()\n Exercise()\n",
"<import token>\n\n\ndef lesson4_1():\n tokenizer = Tokenizer()\n data = \"\"\"In the town of Athy one Jeremy Lanigan \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \nJudy ODaly, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young Terrance McCarthy \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, Ned Morgan, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big Phelim McHugh. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \nOld Casey, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball.\"\"\"\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n \"\"\"\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(xs[5])\n print(ys[5])\n \"\"\"\n [ 0 0 0 0 4 2 66 8 67 68]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 64, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(20)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n history = model.fit(xs, ys, epochs=500, verbose=1)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n \"\"\" \n Laurence 는 없는 단어이기 때문에 패스 하고 있는 단어들을 이용하여 찾는다 \n \"\"\"\n seed_text = 'Laurence went to dublin'\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef Poetry():\n tokenizer = Tokenizer()\n data = open('./tmp/irish-lyrics-eof.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print('len token_list : ', len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=\n ['accuracy'])\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n print(model)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n\n\ndef Exercise():\n import tensorflow.keras.utils as ku\n tokenizer = Tokenizer()\n data = open('./tmp/sonnets.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n predictors, label = input_sequences[:, :-1], input_sequences[:, -1]\n label = ku.to_categorical(label, num_classes=total_words)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150, return_sequences=True)))\n model.add(Dropout(0.2))\n model.add(LSTM(100))\n model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=\n regularizers.l2(0.01)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n print(model.summary())\n \"\"\" \n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n embedding (Embedding) (None, 10, 100) 321100 \n _________________________________________________________________\n bidirectional (Bidirectional (None, 10, 300) 301200 \n _________________________________________________________________\n dropout (Dropout) (None, 10, 300) 0 \n _________________________________________________________________\n lstm_1 (LSTM) (None, 100) 160400 \n _________________________________________________________________\n dense (Dense) (None, 1605) 162105 \n _________________________________________________________________\n dense_1 (Dense) (None, 3211) 5156866 \n =================================================================\n Total params: 6,101,671\n Trainable params: 6,101,671\n Non-trainable params: 0\n _________________________________________________________________\n None\n \"\"\"\n history = model.fit(predictors, label, epochs=100, verbose=1)\n import matplotlib.pyplot as plt\n acc = history.history['accuracy']\n loss = history.history['loss']\n epochs = range(len(acc))\n plt.plot(epochs, acc, 'b', label='Training accuracy')\n plt.title('Training accuracy')\n plt.figure()\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.title('Training loss')\n plt.legend()\n plt.show()\n seed_text = \"Help me Obi Wan Kenobi, you're my only hope\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\nif __name__ == '__main__':\n HaveToTest()\n Exercise()\n",
"<import token>\n\n\ndef lesson4_1():\n tokenizer = Tokenizer()\n data = \"\"\"In the town of Athy one Jeremy Lanigan \n Battered away til he hadnt a pound. \nHis father died and made him a man again \n Left him a farm and ten acres of ground. \nHe gave a grand party for friends and relations \nWho didnt forget him when come to the wall, \nAnd if youll but listen Ill make your eyes glisten \nOf the rows and the ructions of Lanigans Ball. \nMyself to be sure got free invitation, \nFor all the nice girls and boys I might ask, \nAnd just in a minute both friends and relations \nWere dancing round merry as bees round a cask. \nJudy ODaly, that nice little milliner, \nShe tipped me a wink for to give her a call, \nAnd I soon arrived with Peggy McGilligan \nJust in time for Lanigans Ball. \nThere were lashings of punch and wine for the ladies, \nPotatoes and cakes; there was bacon and tea, \nThere were the Nolans, Dolans, OGradys \nCourting the girls and dancing away. \nSongs they went round as plenty as water, \nThe harp that once sounded in Taras old hall,\nSweet Nelly Gray and The Rat Catchers Daughter,\nAll singing together at Lanigans Ball. \nThey were doing all kinds of nonsensical polkas \nAll round the room in a whirligig. \nJulia and I, we banished their nonsense \nAnd tipped them the twist of a reel and a jig. \nAch mavrone, how the girls got all mad at me \nDanced til youd think the ceiling would fall. \nFor I spent three weeks at Brooks Academy \nLearning new steps for Lanigans Ball. \nThree long weeks I spent up in Dublin, \nThree long weeks to learn nothing at all,\n Three long weeks I spent up in Dublin, \nLearning new steps for Lanigans Ball. \nShe stepped out and I stepped in again, \nI stepped out and she stepped in again, \nShe stepped out and I stepped in again, \nLearning new steps for Lanigans Ball. \nBoys were all merry and the girls they were hearty \nAnd danced all around in couples and groups, \nTil an accident happened, young Terrance McCarthy \nPut his right leg through miss Finnertys hoops. \nPoor creature fainted and cried Meelia murther, \nCalled for her brothers and gathered them all. \nCarmody swore that hed go no further \nTil he had satisfaction at Lanigans Ball. \nIn the midst of the row miss Kerrigan fainted, \nHer cheeks at the same time as red as a rose. \nSome of the lads declared she was painted, \nShe took a small drop too much, I suppose. \nHer sweetheart, Ned Morgan, so powerful and able, \nWhen he saw his fair colleen stretched out by the wall, \nTore the left leg from under the table \nAnd smashed all the Chaneys at Lanigans Ball. \nBoys, oh boys, twas then there were runctions. \nMyself got a lick from big Phelim McHugh. \nI soon replied to his introduction \nAnd kicked up a terrible hullabaloo. \nOld Casey, the piper, was near being strangled. \nThey squeezed up his pipes, bellows, chanters and all. \nThe girls, in their ribbons, they got all entangled \nAnd that put an end to Lanigans Ball.\"\"\"\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n \"\"\"\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(xs[5])\n print(ys[5])\n \"\"\"\n [ 0 0 0 0 4 2 66 8 67 68]\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n \"\"\"\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 64, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(20)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n history = model.fit(xs, ys, epochs=500, verbose=1)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n \"\"\" \n Laurence 는 없는 단어이기 때문에 패스 하고 있는 단어들을 이용하여 찾는다 \n \"\"\"\n seed_text = 'Laurence went to dublin'\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef Poetry():\n tokenizer = Tokenizer()\n data = open('./tmp/irish-lyrics-eof.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print('len token_list : ', len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=\n ['accuracy'])\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n print(model)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n\n\ndef Exercise():\n import tensorflow.keras.utils as ku\n tokenizer = Tokenizer()\n data = open('./tmp/sonnets.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n predictors, label = input_sequences[:, :-1], input_sequences[:, -1]\n label = ku.to_categorical(label, num_classes=total_words)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150, return_sequences=True)))\n model.add(Dropout(0.2))\n model.add(LSTM(100))\n model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=\n regularizers.l2(0.01)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n print(model.summary())\n \"\"\" \n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n embedding (Embedding) (None, 10, 100) 321100 \n _________________________________________________________________\n bidirectional (Bidirectional (None, 10, 300) 301200 \n _________________________________________________________________\n dropout (Dropout) (None, 10, 300) 0 \n _________________________________________________________________\n lstm_1 (LSTM) (None, 100) 160400 \n _________________________________________________________________\n dense (Dense) (None, 1605) 162105 \n _________________________________________________________________\n dense_1 (Dense) (None, 3211) 5156866 \n =================================================================\n Total params: 6,101,671\n Trainable params: 6,101,671\n Non-trainable params: 0\n _________________________________________________________________\n None\n \"\"\"\n history = model.fit(predictors, label, epochs=100, verbose=1)\n import matplotlib.pyplot as plt\n acc = history.history['accuracy']\n loss = history.history['loss']\n epochs = range(len(acc))\n plt.plot(epochs, acc, 'b', label='Training accuracy')\n plt.title('Training accuracy')\n plt.figure()\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.title('Training loss')\n plt.legend()\n plt.show()\n seed_text = \"Help me Obi Wan Kenobi, you're my only hope\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\ndef Poetry():\n tokenizer = Tokenizer()\n data = open('./tmp/irish-lyrics-eof.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print('len token_list : ', len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=\n ['accuracy'])\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n print(model)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n\n\ndef Exercise():\n import tensorflow.keras.utils as ku\n tokenizer = Tokenizer()\n data = open('./tmp/sonnets.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n predictors, label = input_sequences[:, :-1], input_sequences[:, -1]\n label = ku.to_categorical(label, num_classes=total_words)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150, return_sequences=True)))\n model.add(Dropout(0.2))\n model.add(LSTM(100))\n model.add(Dense(total_words / 2, activation='relu', kernel_regularizer=\n regularizers.l2(0.01)))\n model.add(Dense(total_words, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n print(model.summary())\n \"\"\" \n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n embedding (Embedding) (None, 10, 100) 321100 \n _________________________________________________________________\n bidirectional (Bidirectional (None, 10, 300) 301200 \n _________________________________________________________________\n dropout (Dropout) (None, 10, 300) 0 \n _________________________________________________________________\n lstm_1 (LSTM) (None, 100) 160400 \n _________________________________________________________________\n dense (Dense) (None, 1605) 162105 \n _________________________________________________________________\n dense_1 (Dense) (None, 3211) 5156866 \n =================================================================\n Total params: 6,101,671\n Trainable params: 6,101,671\n Non-trainable params: 0\n _________________________________________________________________\n None\n \"\"\"\n history = model.fit(predictors, label, epochs=100, verbose=1)\n import matplotlib.pyplot as plt\n acc = history.history['accuracy']\n loss = history.history['loss']\n epochs = range(len(acc))\n plt.plot(epochs, acc, 'b', label='Training accuracy')\n plt.title('Training accuracy')\n plt.figure()\n plt.plot(epochs, loss, 'b', label='Training Loss')\n plt.title('Training loss')\n plt.legend()\n plt.show()\n seed_text = \"Help me Obi Wan Kenobi, you're my only hope\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\n<code token>\n",
"<import token>\n<function token>\n\n\ndef Poetry():\n tokenizer = Tokenizer()\n data = open('./tmp/irish-lyrics-eof.txt').read()\n corpus = data.lower().split('\\n')\n tokenizer.fit_on_texts(corpus)\n total_words = len(tokenizer.word_index) + 1\n print(tokenizer.word_index)\n print(total_words)\n input_sequences = []\n for line in corpus:\n token_list = tokenizer.texts_to_sequences([line])[0]\n print('len token_list : ', len(token_list))\n for i in range(1, len(token_list)):\n n_gram_sequence = token_list[:i + 1]\n input_sequences.append(n_gram_sequence)\n max_sequence_len = max([len(x) for x in input_sequences])\n input_sequences = np.array(pad_sequences(input_sequences, maxlen=\n max_sequence_len, padding='pre'))\n xs, labels = input_sequences[:, :-1], input_sequences[:, -1]\n ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)\n print(tokenizer.word_index['in'])\n print(tokenizer.word_index['the'])\n print(tokenizer.word_index['town'])\n print(tokenizer.word_index['of'])\n print(tokenizer.word_index['athy'])\n print(tokenizer.word_index['one'])\n print(tokenizer.word_index['jeremy'])\n print(tokenizer.word_index['lanigan'])\n print(xs[6])\n print(ys[6])\n print(tokenizer.word_index)\n model = Sequential()\n model.add(Embedding(total_words, 100, input_length=max_sequence_len - 1))\n model.add(Bidirectional(LSTM(150)))\n model.add(Dense(total_words, activation='softmax'))\n adam = Adam(lr=0.01)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=\n ['accuracy'])\n model.summary()\n history = model.fit(xs, ys, epochs=100, verbose=1)\n print(model)\n import matplotlib.pyplot as plt\n\n def plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.xlabel('Epochs')\n plt.ylabel(string)\n plt.show()\n plot_graphs(history, 'accuracy')\n seed_text = \"I've got a bad feeling about this\"\n next_words = 100\n for _ in range(next_words):\n token_list = tokenizer.texts_to_sequences([seed_text])[0]\n token_list = pad_sequences([token_list], maxlen=max_sequence_len - \n 1, padding='pre')\n predicted = model.predict_classes(token_list, verbose=0)\n output_word = ''\n for word, index in tokenizer.word_index.items():\n if index == predicted:\n output_word = word\n break\n seed_text += ' ' + output_word\n print(seed_text)\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n<function token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n\n\ndef HaveToTest():\n print('https://www.tensorflow.org/tutorials/text/text_generation')\n\n\n<docstring token>\n<function token>\n<code token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n<docstring token>\n<function token>\n<code token>\n"
] | false |
99,967 | 810fc5480d25b8f00fd47a7215f87e017848077e | # the square root function using Newton’s method. In this case, Newton’s method is to approximate sqrt(x) by picking a starting point z and then repeating:
# z_next = z - ((z*z - x) / (2 * z))
# Author: Adrian Sypos
# Date: 23/09/2017
import math
x = 20.0
z_next = lambda z: (z - ((z*z - x) / (2 * z)))
current = 1.0
while current != z_next(current):
current = z_next(current)
print('Square root evaluated using Newtons method: ', current)
print('Square root evaluated using math library: ', math.sqrt(x)) | [
"# the square root function using Newton’s method. In this case, Newton’s method is to approximate sqrt(x) by picking a starting point z and then repeating:\n# z_next = z - ((z*z - x) / (2 * z))\n# Author: Adrian Sypos\n# Date: 23/09/2017\n\nimport math\n\nx = 20.0\n\nz_next = lambda z: (z - ((z*z - x) / (2 * z)))\n\ncurrent = 1.0\n\nwhile current != z_next(current):\n\tcurrent = z_next(current)\n\t\nprint('Square root evaluated using Newtons method: ', current)\nprint('Square root evaluated using math library: ', math.sqrt(x))",
"import math\nx = 20.0\nz_next = lambda z: z - (z * z - x) / (2 * z)\ncurrent = 1.0\nwhile current != z_next(current):\n current = z_next(current)\nprint('Square root evaluated using Newtons method: ', current)\nprint('Square root evaluated using math library: ', math.sqrt(x))\n",
"<import token>\nx = 20.0\nz_next = lambda z: z - (z * z - x) / (2 * z)\ncurrent = 1.0\nwhile current != z_next(current):\n current = z_next(current)\nprint('Square root evaluated using Newtons method: ', current)\nprint('Square root evaluated using math library: ', math.sqrt(x))\n",
"<import token>\n<assignment token>\nwhile current != z_next(current):\n current = z_next(current)\nprint('Square root evaluated using Newtons method: ', current)\nprint('Square root evaluated using math library: ', math.sqrt(x))\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,968 | a270c3749a4fda58bd1f8624fdd2f75d8e4cbdd0 | from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import copy
# os.environ["CUDA_VISIBLE_DEVICES"] = "3"
# Data augmentation and normalization for training
# Just normalization for validation
DATA_MEAN = 0.20558404267255
DATA_STD = 0.17694948680626902473216631207703
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD, DATA_STD, DATA_STD])
]),
'valid': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD, DATA_STD, DATA_STD])
]),
}
data_dir = 'MURA_Torch_Format'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
data_transforms[x])
for x in ['train', 'valid']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=100,
shuffle=True, num_workers=20)
for x in ['train', 'valid']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}
class_names = image_datasets['train'].classes
use_gpu = torch.cuda.is_available()
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'valid']:
if phase == 'train':
scheduler.step()
model.train(True) # Set model to training mode
else:
model.train(False) # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for data in dataloaders[phase]:
# get the inputs
inputs, labels = data
# wrap them in Variable
if use_gpu:
inputs = Variable(inputs.cuda())
labels = Variable(labels.cuda())
else:
inputs, labels = Variable(inputs), Variable(labels)
# zero the parameter gradients
optimizer.zero_grad()
# forward
outputs = model(inputs)
_, preds = torch.max(outputs.data, 1)
loss = criterion(outputs, labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.data.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data).item()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'valid' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
model_ft = models.densenet161(pretrained=True)
num_ftrs = model_ft.classifier.in_features
del model_ft.classifier
model_ft.dropout = nn.Dropout(p=0.5)
model_ft.classifier = nn.Linear(num_ftrs, 2)
if use_gpu:
model_ft = model_ft.cuda()
# Uncomment below if you want to use multiple GPUs
model_ft = nn.DataParallel(model_ft)
criterion = nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
# optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
optimizer_ft = torch.optim.Adam(model_ft.parameters(), lr=0.0004, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=25, gamma=0.5)
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=100)
finish_time = time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime(time.time()))
model_name = finish_time + '.pkl'
torch.save(model_ft, model_name)
# Loading model use the following code
# model = torch.load('model.pkl') | [
"from __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n\n# Data augmentation and normalization for training\n# Just normalization for validation\n\nDATA_MEAN = 0.20558404267255\nDATA_STD = 0.17694948680626902473216631207703\n\ndata_transforms = {\n 'train': transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD, DATA_STD, DATA_STD])\n ]),\n 'valid': transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD, DATA_STD, DATA_STD])\n ]),\n}\n\ndata_dir = 'MURA_Torch_Format'\nimage_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x])\n for x in ['train', 'valid']}\ndataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=100,\n shuffle=True, num_workers=20)\n for x in ['train', 'valid']}\ndataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}\nclass_names = image_datasets['train'].classes\n\nuse_gpu = torch.cuda.is_available()\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True) # Set model to training mode\n else:\n model.train(False) # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for data in dataloaders[phase]:\n # get the inputs\n inputs, labels = data\n\n # wrap them in Variable\n if use_gpu:\n inputs = Variable(inputs.cuda())\n labels = Variable(labels.cuda())\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.data.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data).item()\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects / dataset_sizes[phase]\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n\n # deep copy the model\n if phase == 'valid' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n print()\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model\n\nmodel_ft = models.densenet161(pretrained=True)\nnum_ftrs = model_ft.classifier.in_features\ndel model_ft.classifier\nmodel_ft.dropout = nn.Dropout(p=0.5)\nmodel_ft.classifier = nn.Linear(num_ftrs, 2)\n\nif use_gpu:\n model_ft = model_ft.cuda()\n # Uncomment below if you want to use multiple GPUs\n model_ft = nn.DataParallel(model_ft)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Observe that all parameters are being optimized\n# optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)\noptimizer_ft = torch.optim.Adam(model_ft.parameters(), lr=0.0004, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)\n\n# Decay LR by a factor of 0.1 every 7 epochs\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=25, gamma=0.5)\n\nmodel_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,\n num_epochs=100)\n\nfinish_time = time.strftime(\"%Y-%m-%d-%H-%M-%S\",time.localtime(time.time()))\nmodel_name = finish_time + '.pkl'\ntorch.save(model_ft, model_name)\n# Loading model use the following code\n# model = torch.load('model.pkl')",
"from __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\nDATA_MEAN = 0.20558404267255\nDATA_STD = 0.176949486806269\ndata_transforms = {'train': transforms.Compose([transforms.\n RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.\n ToTensor(), transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [\n DATA_STD, DATA_STD, DATA_STD])]), 'valid': transforms.Compose([\n transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor\n (), transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD,\n DATA_STD, DATA_STD])])}\ndata_dir = 'MURA_Torch_Format'\nimage_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x]) for x in ['train', 'valid']}\ndataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size\n =100, shuffle=True, num_workers=20) for x in ['train', 'valid']}\ndataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}\nclass_names = image_datasets['train'].classes\nuse_gpu = torch.cuda.is_available()\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n for phase in ['train', 'valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True)\n else:\n model.train(False)\n running_loss = 0.0\n running_corrects = 0\n for data in dataloaders[phase]:\n inputs, labels = data\n if use_gpu:\n inputs = Variable(inputs.cuda())\n labels = Variable(labels.cuda())\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n optimizer.zero_grad()\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n if phase == 'train':\n loss.backward()\n optimizer.step()\n running_loss += loss.data.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data).item()\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss,\n epoch_acc))\n if phase == 'valid' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n print()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n model.load_state_dict(best_model_wts)\n return model\n\n\nmodel_ft = models.densenet161(pretrained=True)\nnum_ftrs = model_ft.classifier.in_features\ndel model_ft.classifier\nmodel_ft.dropout = nn.Dropout(p=0.5)\nmodel_ft.classifier = nn.Linear(num_ftrs, 2)\nif use_gpu:\n model_ft = model_ft.cuda()\n model_ft = nn.DataParallel(model_ft)\ncriterion = nn.CrossEntropyLoss()\noptimizer_ft = torch.optim.Adam(model_ft.parameters(), lr=0.0004, betas=(\n 0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=25, gamma=0.5)\nmodel_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,\n num_epochs=100)\nfinish_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))\nmodel_name = finish_time + '.pkl'\ntorch.save(model_ft, model_name)\n",
"<import token>\nDATA_MEAN = 0.20558404267255\nDATA_STD = 0.176949486806269\ndata_transforms = {'train': transforms.Compose([transforms.\n RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.\n ToTensor(), transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [\n DATA_STD, DATA_STD, DATA_STD])]), 'valid': transforms.Compose([\n transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor\n (), transforms.Normalize([DATA_MEAN, DATA_MEAN, DATA_MEAN], [DATA_STD,\n DATA_STD, DATA_STD])])}\ndata_dir = 'MURA_Torch_Format'\nimage_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x]) for x in ['train', 'valid']}\ndataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size\n =100, shuffle=True, num_workers=20) for x in ['train', 'valid']}\ndataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}\nclass_names = image_datasets['train'].classes\nuse_gpu = torch.cuda.is_available()\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n for phase in ['train', 'valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True)\n else:\n model.train(False)\n running_loss = 0.0\n running_corrects = 0\n for data in dataloaders[phase]:\n inputs, labels = data\n if use_gpu:\n inputs = Variable(inputs.cuda())\n labels = Variable(labels.cuda())\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n optimizer.zero_grad()\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n if phase == 'train':\n loss.backward()\n optimizer.step()\n running_loss += loss.data.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data).item()\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss,\n epoch_acc))\n if phase == 'valid' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n print()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n model.load_state_dict(best_model_wts)\n return model\n\n\nmodel_ft = models.densenet161(pretrained=True)\nnum_ftrs = model_ft.classifier.in_features\ndel model_ft.classifier\nmodel_ft.dropout = nn.Dropout(p=0.5)\nmodel_ft.classifier = nn.Linear(num_ftrs, 2)\nif use_gpu:\n model_ft = model_ft.cuda()\n model_ft = nn.DataParallel(model_ft)\ncriterion = nn.CrossEntropyLoss()\noptimizer_ft = torch.optim.Adam(model_ft.parameters(), lr=0.0004, betas=(\n 0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=25, gamma=0.5)\nmodel_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,\n num_epochs=100)\nfinish_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))\nmodel_name = finish_time + '.pkl'\ntorch.save(model_ft, model_name)\n",
"<import token>\n<assignment token>\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n for phase in ['train', 'valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True)\n else:\n model.train(False)\n running_loss = 0.0\n running_corrects = 0\n for data in dataloaders[phase]:\n inputs, labels = data\n if use_gpu:\n inputs = Variable(inputs.cuda())\n labels = Variable(labels.cuda())\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n optimizer.zero_grad()\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n if phase == 'train':\n loss.backward()\n optimizer.step()\n running_loss += loss.data.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data).item()\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss,\n epoch_acc))\n if phase == 'valid' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n print()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n model.load_state_dict(best_model_wts)\n return model\n\n\n<assignment token>\ndel model_ft.classifier\n<assignment token>\nif use_gpu:\n model_ft = model_ft.cuda()\n model_ft = nn.DataParallel(model_ft)\n<assignment token>\ntorch.save(model_ft, model_name)\n",
"<import token>\n<assignment token>\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n for phase in ['train', 'valid']:\n if phase == 'train':\n scheduler.step()\n model.train(True)\n else:\n model.train(False)\n running_loss = 0.0\n running_corrects = 0\n for data in dataloaders[phase]:\n inputs, labels = data\n if use_gpu:\n inputs = Variable(inputs.cuda())\n labels = Variable(labels.cuda())\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n optimizer.zero_grad()\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n if phase == 'train':\n loss.backward()\n optimizer.step()\n running_loss += loss.data.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data).item()\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss,\n epoch_acc))\n if phase == 'valid' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n print()\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n model.load_state_dict(best_model_wts)\n return model\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
99,969 | a452badb12abe9b1df7bf66963285c6aa93f0dbd | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 5 17:09:33 2022
@author: Santi
Extrae multiples espectros adquiridos en Bruker Avance II
"""
# import nmrglue as ng
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate
from Datos import *
from Espectro import autophase
from scipy.stats import linregress
import matplotlib.ticker as ticker
# Nmuestra: es el n de Mn, ejemplo: M16 ---> Nmuestra = 16
# fecha: correspondiente al directorio de datos. 'MM-DD'
# expn: numero de archivo
# ppmRange: rango de integracion
# bmax: maximo valor de bvalue utilizado para ajustar
#
# info = [Nmuestra, fecha, expni, expnf, ppmRange]
# Q3
# info = [23, '2023-03-08', 20, 35, [-5,3]]
# info = [21, '11-14', 30, 45, [-3, 3]]
# info = [10, '10-11', 20, 29, [-1, 1]]
# info = [11, '10-20', 10, 25, [-1, 1]]
info = [11, '2023-03-08', 102, 117, [-3, 3]] # REMEDICION
# info = [12, '11-14', 72, 85, [-3, 3]]
min_gp = 5
gpshape = 'sin'
factor_b = 1
FIDsignal = False
NptsFid = 4
ABSsignal = False # abs del espectro
centrado_en_maximo = True
save = False
save1d = False
Nmuestra, fecha, expni, expnf, ppmRange = info
expnums = np.arange(expni, expnf+1)
# expnums = [28]
#-------------------- directorios
# path_local = "S:/CNEA/Glicerol-Agua/116MHz"
# path_local = "S:/Posdoc/Glicerol-Agua/116MHz"
path_local = "S:/NMRdata/2022_Glicerol-agua_CNEA"
path_bruker = f"/{fecha}_Diff_Silica_Agua-Glicerol-LiCl/"
path = path_local + path_bruker
# directorio de guradado
# savepath_local = "S:/" # Oficina
savepath_local = "G:/Otros ordenadores/Oficina/" # Acer
savepath = f"{savepath_local}Posdoc/CNEA/Glicerol-Agua/analisis/7Li/"
# -----------------------------------------------
# datos de la muestra
muestra = f"M{Nmuestra}"
N = Nmuestra-10
# matriz es el medio: Bulk, Q30 o Q3
if N > 10:
if Nmuestra == 21 or Nmuestra == 23:
matriz = 'Q3'
elif Nmuestra == 22:
matriz = 'Q30'
elif Nmuestra == 24:
matriz = 'Bulk'
elif N < 3:
matriz = 'Q3'
elif N < 6:
matriz = 'Q30'
elif N < 9:
matriz = 'Bulk'
# pc es el porcentaje de glicerol: 50%, 70% o 90%
if Nmuestra == 23:
pc = 0
elif N > 10:
pc = 30
elif N % 3 == 0:
pc = 50
elif N % 3 == 1:
pc = 70
elif N % 3 == 2:
pc = 90
msg = f"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}"
print(msg)
# %%
gplist = []
intensidades = []
intensidadesFID = []
color = []
fig1d, axs = plt.subplots(nrows=1, ncols=2) # create figure & 1 axis
for nn in range(len(expnums)):
expn = expnums[nn]
print(expn)
if True: # antes era "if expn<15:"
color.append('k')
else:
color.append('b')
# extraigo:
datos = DatosProcesados(f'{path}/{expn}/')
nucleo = datos.nucleo
gplist.append(datos.acqus.gp)
re = datos.espectro.real
im = datos.espectro.imag
ppmAxis = datos.espectro.ppmAxis
# guardo espectros 1d
if save1d:
filename0 = f"{muestra}_{pc}pc_{matriz}"
data = np.array([ppmAxis, re, im]).T
filename = f"{savepath}/datos_Diff/Espectros_vs_gpz/" \
f"{filename0}_gpz{datos.acqus.gp:0>5.2f}.dat"
np.savetxt(filename, data)
# recorto para integrar
datos.espectro.ppmSelect(ppmRange, centrado_en_maximo=centrado_en_maximo)
re = datos.espectro.real
im = datos.espectro.imag
ppmAxis = datos.espectro.ppmAxis
# plt.figure(expn)
# plt.axhline(0)
# plt.plot(ppmAxis, re, 'k')
# plt.plot(ppmAxis, im, 'r')
# plt.plot(ppmAxis, np.abs(re+1j*im), 'orange')
# plt.title(f"GP: {datos.acqus.gp:.2f} %")
if ABSsignal:
spec_integrado = np.abs(re+1j*im)
else:
spec_integrado = re
ancho = np.abs(ppmAxis[0]-ppmAxis[-1])
integral = scipy.integrate.simps(spec_integrado, x=-ppmAxis) / ancho
intensidades.append(integral)
# calculo FID
datos.set_fid()
timeAxis = datos.fid.timeAxis
fid = datos.fid.real
fid = np.abs(datos.fid.real + 1j*datos.fid.imag)
intensidadFID = np.sum(fid[0:NptsFid])
intensidadesFID.append(intensidadFID)
# guardo:
# header = "ppmAxis\t real (norm)\t imag (norm)\t real \t imag"
# dataexport = np.array([ppmAxis, re, im, re, im]).T
# filename = f'{savepath}/{nucleo}_{muestra}.dat'
# # np.savetxt(filename, dataexport, header=header)
# grafico para ver:
print('graficando...', nucleo, muestra)
axs[0].plot(ppmAxis, spec_integrado, linewidth=2, color=color[nn])
axs[0].set_xlabel(f"{nucleo} NMR Shift [ppm]")
# axs[0].set_xlim([np.max(ppmAxis), np.min(ppmAxis)])
axs[1].plot(timeAxis*1000, fid, 'o-', linewidth=2)
axs[1].set_xlabel(f"time [ms]")
if (datos.acqus.gp == min_gp):
spec1d = re
spec1d_im = im
bigDelta = datos.acqus.D[20] # ms
delta = datos.acqus.P[30]*2 * 1e-6 # ms
titulo = f"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n" \
fr"$\Delta = {bigDelta*1e3}$ ms, $\delta = {delta*1e3}$ ms"
fig1d.suptitle(titulo)
# %%
# calculo bvalue:
# gplist = np.loadtxt(f"{path}gp_list.dat")[:,1]
bigDelta = datos.acqus.D[20] # s
delta = datos.acqus.P[30]*2 * 1e-6 # s
gamma = 103.962e6 # rad/(s*T) ---> 7Li
g0 = 12 # T/m
gplist = np.array(gplist)*g0/100
if 'sin' in gpshape.lower():
bvalue = (gamma*gplist*delta/np.pi)**2 * (4*bigDelta-delta) * 1e-9
elif 'rect' in gpshape.lower():
bvalue = (gamma*gplist*delta)**2 * (bigDelta-delta/3) * 1e-9
bvalue = factor_b * bvalue
# Senal:
if FIDsignal:
signal = np.array(intensidadesFID)
else:
signal = np.array(intensidades)
# Ajuste lineal----------------------------
# Reordeno:
signal = signal[bvalue[:].argsort()]
color = np.array(color)[bvalue[:].argsort()]
gplist = gplist[bvalue[:].argsort()]
bvalue = bvalue[bvalue[:].argsort()]
# defino variables de ajuste
y = np.log(signal)
x = bvalue
slope, intercept, r, p, se = linregress(x, y)
yfit = slope*x+intercept
signal_fit = np.exp(yfit)
residuals = signal - signal_fit
# Resultados del ajuste
D = -slope
uD = se
r_squared = r**2
msg = f"Ajuste lineal de Difusion:\n \
D = {D:.8f} 10^-9 m^2/s\n \
Rsquared = {r_squared:.6f}"
print(msg)
# %% Grafico
smax = np.max(signal)
signal = signal/smax
signal_fit = signal_fit/smax
bvalue_fit = bvalue
residuals = residuals/smax
fig, axs = plt.subplots(2, 1, figsize=(6, 7))
# -------------
titulo = f"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n" \
fr"$\Delta = {bigDelta*1e3}$ ms, $\delta = {delta*1e3}$ ms"
axs[0].set_title(titulo)
# axs[0].plot(bvalue, signal, 'ko')
axs[0].scatter(bvalue, signal, c=color)
axs[0].plot(bvalue_fit, signal_fit, 'r-')
text = f"$D =$ {D:.4f} $10^{{-9}}m^2/s$ \n " \
f"$u_D =$ {uD:.1g} $10^{{-9}}m^2/s$ \n " \
f"$r^2 =$ {r_squared:.5g}"
axs[0].text(bvalue[-1]*0.6, 0.5*(max(signal)-min(signal))+min(signal), text,
multialignment="left")
axs[0].set(xlabel=r'$b_{value} [10^9 s/m^2]$', ylabel=r'$S$')
axs[0].set_yscale('log')
axs[0].yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1g'))
axs[0].yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.1g'))
# -------------
axs[1].plot(bvalue, residuals, 'ko')
axs[1].axhline(0, color='k', linestyle='--')
axs[1].set(xlabel=r'$b_{value} [10^9 s/m^2]$', ylabel=r'Residuos')
axs[1].set_yscale('symlog')
ylim = 10**np.ceil(np.log10(np.max(abs(residuals))))
axs[1].set_ylim([-ylim, ylim])
# %%
# guardo data:
if save:
filename0 = f"{muestra}_{pc}pc_{matriz}"
filename = f'{savepath}/datos_Diff/figuras/{filename0}_Diff.png'
fig.savefig(filename) # save the figure to file
filename = f'{savepath}/datos_Diff/figuras/'\
f'{filename0}_Diff-RegionIntegracion.png'
fig1d.savefig(filename) # save the figure to file
header = f"Archivo de datos: {path_bruker}\n" \
f"Rango de integracion: {ppmRange} ppm\n" \
f"bvalue (10^-9 m^2/s)\t S (norm)\n" \
f"gpz (%)"
Diffdata = np.array([bvalue, signal, gplist]).T
np.savetxt(f"{savepath}/datos_Diff/{filename0}_Diff.dat",
Diffdata, header=header)
# data = np.array([ppmAxis, spec1d, spec1d_im]).T
# filename = f"{savepath}/datos_Diff/primerEspectro/" \
# f"{filename0}_primerEspectro.dat"
# np.savetxt(filename, data)
plt.show()
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 5 17:09:33 2022\n\n@author: Santi\n\nExtrae multiples espectros adquiridos en Bruker Avance II\n\"\"\"\n\n# import nmrglue as ng\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.integrate\nfrom Datos import *\nfrom Espectro import autophase\nfrom scipy.stats import linregress\nimport matplotlib.ticker as ticker\n\n\n# Nmuestra: es el n de Mn, ejemplo: M16 ---> Nmuestra = 16\n# fecha: correspondiente al directorio de datos. 'MM-DD'\n# expn: numero de archivo\n# ppmRange: rango de integracion\n# bmax: maximo valor de bvalue utilizado para ajustar\n#\n# info = [Nmuestra, fecha, expni, expnf, ppmRange]\n# Q3\n# info = [23, '2023-03-08', 20, 35, [-5,3]]\n# info = [21, '11-14', 30, 45, [-3, 3]]\n# info = [10, '10-11', 20, 29, [-1, 1]]\n# info = [11, '10-20', 10, 25, [-1, 1]]\ninfo = [11, '2023-03-08', 102, 117, [-3, 3]] # REMEDICION\n# info = [12, '11-14', 72, 85, [-3, 3]]\n\nmin_gp = 5\n\ngpshape = 'sin'\nfactor_b = 1\n\nFIDsignal = False\nNptsFid = 4\nABSsignal = False # abs del espectro\ncentrado_en_maximo = True\n\nsave = False\nsave1d = False\nNmuestra, fecha, expni, expnf, ppmRange = info\nexpnums = np.arange(expni, expnf+1)\n# expnums = [28]\n\n#-------------------- directorios\n# path_local = \"S:/CNEA/Glicerol-Agua/116MHz\"\n# path_local = \"S:/Posdoc/Glicerol-Agua/116MHz\"\npath_local = \"S:/NMRdata/2022_Glicerol-agua_CNEA\"\npath_bruker = f\"/{fecha}_Diff_Silica_Agua-Glicerol-LiCl/\"\npath = path_local + path_bruker\n# directorio de guradado\n# savepath_local = \"S:/\" # Oficina\nsavepath_local = \"G:/Otros ordenadores/Oficina/\" # Acer\nsavepath = f\"{savepath_local}Posdoc/CNEA/Glicerol-Agua/analisis/7Li/\"\n\n\n# -----------------------------------------------\n# datos de la muestra\nmuestra = f\"M{Nmuestra}\"\nN = Nmuestra-10\n# matriz es el medio: Bulk, Q30 o Q3\nif N > 10:\n if Nmuestra == 21 or Nmuestra == 23:\n matriz = 'Q3'\n elif Nmuestra == 22:\n matriz = 'Q30'\n elif Nmuestra == 24:\n matriz = 'Bulk'\nelif N < 3:\n matriz = 'Q3'\nelif N < 6:\n matriz = 'Q30'\nelif N < 9:\n matriz = 'Bulk'\n# pc es el porcentaje de glicerol: 50%, 70% o 90%\nif Nmuestra == 23:\n pc = 0\nelif N > 10:\n pc = 30\nelif N % 3 == 0:\n pc = 50\nelif N % 3 == 1:\n pc = 70\nelif N % 3 == 2:\n pc = 90\nmsg = f\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\"\nprint(msg)\n\n# %%\ngplist = []\nintensidades = []\nintensidadesFID = []\ncolor = []\nfig1d, axs = plt.subplots(nrows=1, ncols=2) # create figure & 1 axis\nfor nn in range(len(expnums)):\n expn = expnums[nn]\n print(expn)\n if True: # antes era \"if expn<15:\"\n color.append('k')\n else:\n color.append('b')\n # extraigo:\n datos = DatosProcesados(f'{path}/{expn}/')\n nucleo = datos.nucleo\n gplist.append(datos.acqus.gp)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n\n # guardo espectros 1d\n if save1d:\n filename0 = f\"{muestra}_{pc}pc_{matriz}\"\n data = np.array([ppmAxis, re, im]).T\n filename = f\"{savepath}/datos_Diff/Espectros_vs_gpz/\" \\\n f\"{filename0}_gpz{datos.acqus.gp:0>5.2f}.dat\"\n np.savetxt(filename, data)\n\n # recorto para integrar\n datos.espectro.ppmSelect(ppmRange, centrado_en_maximo=centrado_en_maximo)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n\n # plt.figure(expn)\n # plt.axhline(0)\n # plt.plot(ppmAxis, re, 'k')\n # plt.plot(ppmAxis, im, 'r')\n # plt.plot(ppmAxis, np.abs(re+1j*im), 'orange')\n # plt.title(f\"GP: {datos.acqus.gp:.2f} %\")\n\n if ABSsignal:\n spec_integrado = np.abs(re+1j*im)\n else:\n spec_integrado = re\n ancho = np.abs(ppmAxis[0]-ppmAxis[-1])\n integral = scipy.integrate.simps(spec_integrado, x=-ppmAxis) / ancho\n intensidades.append(integral)\n\n # calculo FID\n datos.set_fid()\n timeAxis = datos.fid.timeAxis\n fid = datos.fid.real\n fid = np.abs(datos.fid.real + 1j*datos.fid.imag)\n intensidadFID = np.sum(fid[0:NptsFid])\n intensidadesFID.append(intensidadFID)\n\n # guardo:\n # header = \"ppmAxis\\t real (norm)\\t imag (norm)\\t real \\t imag\"\n # dataexport = np.array([ppmAxis, re, im, re, im]).T\n # filename = f'{savepath}/{nucleo}_{muestra}.dat'\n # # np.savetxt(filename, dataexport, header=header)\n\n # grafico para ver:\n print('graficando...', nucleo, muestra)\n axs[0].plot(ppmAxis, spec_integrado, linewidth=2, color=color[nn])\n axs[0].set_xlabel(f\"{nucleo} NMR Shift [ppm]\")\n # axs[0].set_xlim([np.max(ppmAxis), np.min(ppmAxis)])\n axs[1].plot(timeAxis*1000, fid, 'o-', linewidth=2)\n axs[1].set_xlabel(f\"time [ms]\")\n if (datos.acqus.gp == min_gp):\n spec1d = re\n spec1d_im = im\n\nbigDelta = datos.acqus.D[20] # ms\ndelta = datos.acqus.P[30]*2 * 1e-6 # ms\ntitulo = f\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\\n\" \\\n fr\"$\\Delta = {bigDelta*1e3}$ ms, $\\delta = {delta*1e3}$ ms\"\nfig1d.suptitle(titulo)\n# %%\n# calculo bvalue:\n# gplist = np.loadtxt(f\"{path}gp_list.dat\")[:,1]\nbigDelta = datos.acqus.D[20] # s\ndelta = datos.acqus.P[30]*2 * 1e-6 # s\ngamma = 103.962e6 # rad/(s*T) ---> 7Li\ng0 = 12 # T/m\ngplist = np.array(gplist)*g0/100\nif 'sin' in gpshape.lower():\n bvalue = (gamma*gplist*delta/np.pi)**2 * (4*bigDelta-delta) * 1e-9\nelif 'rect' in gpshape.lower():\n bvalue = (gamma*gplist*delta)**2 * (bigDelta-delta/3) * 1e-9\nbvalue = factor_b * bvalue\n# Senal:\n\nif FIDsignal:\n signal = np.array(intensidadesFID)\nelse:\n signal = np.array(intensidades)\n# Ajuste lineal----------------------------\n# Reordeno:\nsignal = signal[bvalue[:].argsort()]\ncolor = np.array(color)[bvalue[:].argsort()]\ngplist = gplist[bvalue[:].argsort()]\nbvalue = bvalue[bvalue[:].argsort()]\n\n# defino variables de ajuste\ny = np.log(signal)\nx = bvalue\nslope, intercept, r, p, se = linregress(x, y)\nyfit = slope*x+intercept\nsignal_fit = np.exp(yfit)\nresiduals = signal - signal_fit\n# Resultados del ajuste\nD = -slope\nuD = se\nr_squared = r**2\nmsg = f\"Ajuste lineal de Difusion:\\n \\\n D = {D:.8f} 10^-9 m^2/s\\n \\\n Rsquared = {r_squared:.6f}\"\nprint(msg)\n\n\n# %% Grafico\nsmax = np.max(signal)\nsignal = signal/smax\nsignal_fit = signal_fit/smax\nbvalue_fit = bvalue\nresiduals = residuals/smax\n\nfig, axs = plt.subplots(2, 1, figsize=(6, 7))\n# -------------\ntitulo = f\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\\n\" \\\n fr\"$\\Delta = {bigDelta*1e3}$ ms, $\\delta = {delta*1e3}$ ms\"\naxs[0].set_title(titulo)\n# axs[0].plot(bvalue, signal, 'ko')\naxs[0].scatter(bvalue, signal, c=color)\naxs[0].plot(bvalue_fit, signal_fit, 'r-')\ntext = f\"$D =$ {D:.4f} $10^{{-9}}m^2/s$ \\n \" \\\n f\"$u_D =$ {uD:.1g} $10^{{-9}}m^2/s$ \\n \" \\\n f\"$r^2 =$ {r_squared:.5g}\"\naxs[0].text(bvalue[-1]*0.6, 0.5*(max(signal)-min(signal))+min(signal), text,\n multialignment=\"left\")\naxs[0].set(xlabel=r'$b_{value} [10^9 s/m^2]$', ylabel=r'$S$')\naxs[0].set_yscale('log')\naxs[0].yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[0].yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.1g'))\n# -------------\naxs[1].plot(bvalue, residuals, 'ko')\naxs[1].axhline(0, color='k', linestyle='--')\naxs[1].set(xlabel=r'$b_{value} [10^9 s/m^2]$', ylabel=r'Residuos')\naxs[1].set_yscale('symlog')\nylim = 10**np.ceil(np.log10(np.max(abs(residuals))))\naxs[1].set_ylim([-ylim, ylim])\n\n# %%\n# guardo data:\nif save:\n filename0 = f\"{muestra}_{pc}pc_{matriz}\"\n\n filename = f'{savepath}/datos_Diff/figuras/{filename0}_Diff.png'\n fig.savefig(filename) # save the figure to file\n\n filename = f'{savepath}/datos_Diff/figuras/'\\\n f'{filename0}_Diff-RegionIntegracion.png'\n fig1d.savefig(filename) # save the figure to file\n\n header = f\"Archivo de datos: {path_bruker}\\n\" \\\n f\"Rango de integracion: {ppmRange} ppm\\n\" \\\n f\"bvalue (10^-9 m^2/s)\\t S (norm)\\n\" \\\n f\"gpz (%)\"\n Diffdata = np.array([bvalue, signal, gplist]).T\n np.savetxt(f\"{savepath}/datos_Diff/{filename0}_Diff.dat\",\n Diffdata, header=header)\n\n # data = np.array([ppmAxis, spec1d, spec1d_im]).T\n # filename = f\"{savepath}/datos_Diff/primerEspectro/\" \\\n # f\"{filename0}_primerEspectro.dat\"\n # np.savetxt(filename, data)\nplt.show()\n",
"<docstring token>\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.integrate\nfrom Datos import *\nfrom Espectro import autophase\nfrom scipy.stats import linregress\nimport matplotlib.ticker as ticker\ninfo = [11, '2023-03-08', 102, 117, [-3, 3]]\nmin_gp = 5\ngpshape = 'sin'\nfactor_b = 1\nFIDsignal = False\nNptsFid = 4\nABSsignal = False\ncentrado_en_maximo = True\nsave = False\nsave1d = False\nNmuestra, fecha, expni, expnf, ppmRange = info\nexpnums = np.arange(expni, expnf + 1)\npath_local = 'S:/NMRdata/2022_Glicerol-agua_CNEA'\npath_bruker = f'/{fecha}_Diff_Silica_Agua-Glicerol-LiCl/'\npath = path_local + path_bruker\nsavepath_local = 'G:/Otros ordenadores/Oficina/'\nsavepath = f'{savepath_local}Posdoc/CNEA/Glicerol-Agua/analisis/7Li/'\nmuestra = f'M{Nmuestra}'\nN = Nmuestra - 10\nif N > 10:\n if Nmuestra == 21 or Nmuestra == 23:\n matriz = 'Q3'\n elif Nmuestra == 22:\n matriz = 'Q30'\n elif Nmuestra == 24:\n matriz = 'Bulk'\nelif N < 3:\n matriz = 'Q3'\nelif N < 6:\n matriz = 'Q30'\nelif N < 9:\n matriz = 'Bulk'\nif Nmuestra == 23:\n pc = 0\nelif N > 10:\n pc = 30\nelif N % 3 == 0:\n pc = 50\nelif N % 3 == 1:\n pc = 70\nelif N % 3 == 2:\n pc = 90\nmsg = f'muestra: M{Nmuestra}, {pc}% glicerol, {matriz}'\nprint(msg)\ngplist = []\nintensidades = []\nintensidadesFID = []\ncolor = []\nfig1d, axs = plt.subplots(nrows=1, ncols=2)\nfor nn in range(len(expnums)):\n expn = expnums[nn]\n print(expn)\n if True:\n color.append('k')\n else:\n color.append('b')\n datos = DatosProcesados(f'{path}/{expn}/')\n nucleo = datos.nucleo\n gplist.append(datos.acqus.gp)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if save1d:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n data = np.array([ppmAxis, re, im]).T\n filename = (\n f'{savepath}/datos_Diff/Espectros_vs_gpz/{filename0}_gpz{datos.acqus.gp:0>5.2f}.dat'\n )\n np.savetxt(filename, data)\n datos.espectro.ppmSelect(ppmRange, centrado_en_maximo=centrado_en_maximo)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if ABSsignal:\n spec_integrado = np.abs(re + 1.0j * im)\n else:\n spec_integrado = re\n ancho = np.abs(ppmAxis[0] - ppmAxis[-1])\n integral = scipy.integrate.simps(spec_integrado, x=-ppmAxis) / ancho\n intensidades.append(integral)\n datos.set_fid()\n timeAxis = datos.fid.timeAxis\n fid = datos.fid.real\n fid = np.abs(datos.fid.real + 1.0j * datos.fid.imag)\n intensidadFID = np.sum(fid[0:NptsFid])\n intensidadesFID.append(intensidadFID)\n print('graficando...', nucleo, muestra)\n axs[0].plot(ppmAxis, spec_integrado, linewidth=2, color=color[nn])\n axs[0].set_xlabel(f'{nucleo} NMR Shift [ppm]')\n axs[1].plot(timeAxis * 1000, fid, 'o-', linewidth=2)\n axs[1].set_xlabel(f'time [ms]')\n if datos.acqus.gp == min_gp:\n spec1d = re\n spec1d_im = im\nbigDelta = datos.acqus.D[20]\ndelta = datos.acqus.P[30] * 2 * 1e-06\ntitulo = f\"\"\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n$\\\\Delta = {bigDelta * 1000.0}$ ms, $\\\\delta = {delta * 1000.0}$ ms\"\"\"\nfig1d.suptitle(titulo)\nbigDelta = datos.acqus.D[20]\ndelta = datos.acqus.P[30] * 2 * 1e-06\ngamma = 103962000.0\ng0 = 12\ngplist = np.array(gplist) * g0 / 100\nif 'sin' in gpshape.lower():\n bvalue = (gamma * gplist * delta / np.pi) ** 2 * (4 * bigDelta - delta\n ) * 1e-09\nelif 'rect' in gpshape.lower():\n bvalue = (gamma * gplist * delta) ** 2 * (bigDelta - delta / 3) * 1e-09\nbvalue = factor_b * bvalue\nif FIDsignal:\n signal = np.array(intensidadesFID)\nelse:\n signal = np.array(intensidades)\nsignal = signal[bvalue[:].argsort()]\ncolor = np.array(color)[bvalue[:].argsort()]\ngplist = gplist[bvalue[:].argsort()]\nbvalue = bvalue[bvalue[:].argsort()]\ny = np.log(signal)\nx = bvalue\nslope, intercept, r, p, se = linregress(x, y)\nyfit = slope * x + intercept\nsignal_fit = np.exp(yfit)\nresiduals = signal - signal_fit\nD = -slope\nuD = se\nr_squared = r ** 2\nmsg = f\"\"\"Ajuste lineal de Difusion:\n D = {D:.8f} 10^-9 m^2/s\n Rsquared = {r_squared:.6f}\"\"\"\nprint(msg)\nsmax = np.max(signal)\nsignal = signal / smax\nsignal_fit = signal_fit / smax\nbvalue_fit = bvalue\nresiduals = residuals / smax\nfig, axs = plt.subplots(2, 1, figsize=(6, 7))\ntitulo = f\"\"\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n$\\\\Delta = {bigDelta * 1000.0}$ ms, $\\\\delta = {delta * 1000.0}$ ms\"\"\"\naxs[0].set_title(titulo)\naxs[0].scatter(bvalue, signal, c=color)\naxs[0].plot(bvalue_fit, signal_fit, 'r-')\ntext = f\"\"\"$D =$ {D:.4f} $10^{{-9}}m^2/s$ \n $u_D =$ {uD:.1g} $10^{{-9}}m^2/s$ \n $r^2 =$ {r_squared:.5g}\"\"\"\naxs[0].text(bvalue[-1] * 0.6, 0.5 * (max(signal) - min(signal)) + min(\n signal), text, multialignment='left')\naxs[0].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='$S$')\naxs[0].set_yscale('log')\naxs[0].yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[0].yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[1].plot(bvalue, residuals, 'ko')\naxs[1].axhline(0, color='k', linestyle='--')\naxs[1].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='Residuos')\naxs[1].set_yscale('symlog')\nylim = 10 ** np.ceil(np.log10(np.max(abs(residuals))))\naxs[1].set_ylim([-ylim, ylim])\nif save:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n filename = f'{savepath}/datos_Diff/figuras/{filename0}_Diff.png'\n fig.savefig(filename)\n filename = (\n f'{savepath}/datos_Diff/figuras/{filename0}_Diff-RegionIntegracion.png'\n )\n fig1d.savefig(filename)\n header = f\"\"\"Archivo de datos: {path_bruker}\nRango de integracion: {ppmRange} ppm\nbvalue (10^-9 m^2/s)\t S (norm)\ngpz (%)\"\"\"\n Diffdata = np.array([bvalue, signal, gplist]).T\n np.savetxt(f'{savepath}/datos_Diff/{filename0}_Diff.dat', Diffdata,\n header=header)\nplt.show()\n",
"<docstring token>\n<import token>\ninfo = [11, '2023-03-08', 102, 117, [-3, 3]]\nmin_gp = 5\ngpshape = 'sin'\nfactor_b = 1\nFIDsignal = False\nNptsFid = 4\nABSsignal = False\ncentrado_en_maximo = True\nsave = False\nsave1d = False\nNmuestra, fecha, expni, expnf, ppmRange = info\nexpnums = np.arange(expni, expnf + 1)\npath_local = 'S:/NMRdata/2022_Glicerol-agua_CNEA'\npath_bruker = f'/{fecha}_Diff_Silica_Agua-Glicerol-LiCl/'\npath = path_local + path_bruker\nsavepath_local = 'G:/Otros ordenadores/Oficina/'\nsavepath = f'{savepath_local}Posdoc/CNEA/Glicerol-Agua/analisis/7Li/'\nmuestra = f'M{Nmuestra}'\nN = Nmuestra - 10\nif N > 10:\n if Nmuestra == 21 or Nmuestra == 23:\n matriz = 'Q3'\n elif Nmuestra == 22:\n matriz = 'Q30'\n elif Nmuestra == 24:\n matriz = 'Bulk'\nelif N < 3:\n matriz = 'Q3'\nelif N < 6:\n matriz = 'Q30'\nelif N < 9:\n matriz = 'Bulk'\nif Nmuestra == 23:\n pc = 0\nelif N > 10:\n pc = 30\nelif N % 3 == 0:\n pc = 50\nelif N % 3 == 1:\n pc = 70\nelif N % 3 == 2:\n pc = 90\nmsg = f'muestra: M{Nmuestra}, {pc}% glicerol, {matriz}'\nprint(msg)\ngplist = []\nintensidades = []\nintensidadesFID = []\ncolor = []\nfig1d, axs = plt.subplots(nrows=1, ncols=2)\nfor nn in range(len(expnums)):\n expn = expnums[nn]\n print(expn)\n if True:\n color.append('k')\n else:\n color.append('b')\n datos = DatosProcesados(f'{path}/{expn}/')\n nucleo = datos.nucleo\n gplist.append(datos.acqus.gp)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if save1d:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n data = np.array([ppmAxis, re, im]).T\n filename = (\n f'{savepath}/datos_Diff/Espectros_vs_gpz/{filename0}_gpz{datos.acqus.gp:0>5.2f}.dat'\n )\n np.savetxt(filename, data)\n datos.espectro.ppmSelect(ppmRange, centrado_en_maximo=centrado_en_maximo)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if ABSsignal:\n spec_integrado = np.abs(re + 1.0j * im)\n else:\n spec_integrado = re\n ancho = np.abs(ppmAxis[0] - ppmAxis[-1])\n integral = scipy.integrate.simps(spec_integrado, x=-ppmAxis) / ancho\n intensidades.append(integral)\n datos.set_fid()\n timeAxis = datos.fid.timeAxis\n fid = datos.fid.real\n fid = np.abs(datos.fid.real + 1.0j * datos.fid.imag)\n intensidadFID = np.sum(fid[0:NptsFid])\n intensidadesFID.append(intensidadFID)\n print('graficando...', nucleo, muestra)\n axs[0].plot(ppmAxis, spec_integrado, linewidth=2, color=color[nn])\n axs[0].set_xlabel(f'{nucleo} NMR Shift [ppm]')\n axs[1].plot(timeAxis * 1000, fid, 'o-', linewidth=2)\n axs[1].set_xlabel(f'time [ms]')\n if datos.acqus.gp == min_gp:\n spec1d = re\n spec1d_im = im\nbigDelta = datos.acqus.D[20]\ndelta = datos.acqus.P[30] * 2 * 1e-06\ntitulo = f\"\"\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n$\\\\Delta = {bigDelta * 1000.0}$ ms, $\\\\delta = {delta * 1000.0}$ ms\"\"\"\nfig1d.suptitle(titulo)\nbigDelta = datos.acqus.D[20]\ndelta = datos.acqus.P[30] * 2 * 1e-06\ngamma = 103962000.0\ng0 = 12\ngplist = np.array(gplist) * g0 / 100\nif 'sin' in gpshape.lower():\n bvalue = (gamma * gplist * delta / np.pi) ** 2 * (4 * bigDelta - delta\n ) * 1e-09\nelif 'rect' in gpshape.lower():\n bvalue = (gamma * gplist * delta) ** 2 * (bigDelta - delta / 3) * 1e-09\nbvalue = factor_b * bvalue\nif FIDsignal:\n signal = np.array(intensidadesFID)\nelse:\n signal = np.array(intensidades)\nsignal = signal[bvalue[:].argsort()]\ncolor = np.array(color)[bvalue[:].argsort()]\ngplist = gplist[bvalue[:].argsort()]\nbvalue = bvalue[bvalue[:].argsort()]\ny = np.log(signal)\nx = bvalue\nslope, intercept, r, p, se = linregress(x, y)\nyfit = slope * x + intercept\nsignal_fit = np.exp(yfit)\nresiduals = signal - signal_fit\nD = -slope\nuD = se\nr_squared = r ** 2\nmsg = f\"\"\"Ajuste lineal de Difusion:\n D = {D:.8f} 10^-9 m^2/s\n Rsquared = {r_squared:.6f}\"\"\"\nprint(msg)\nsmax = np.max(signal)\nsignal = signal / smax\nsignal_fit = signal_fit / smax\nbvalue_fit = bvalue\nresiduals = residuals / smax\nfig, axs = plt.subplots(2, 1, figsize=(6, 7))\ntitulo = f\"\"\"muestra: M{Nmuestra}, {pc}% glicerol, {matriz}\n$\\\\Delta = {bigDelta * 1000.0}$ ms, $\\\\delta = {delta * 1000.0}$ ms\"\"\"\naxs[0].set_title(titulo)\naxs[0].scatter(bvalue, signal, c=color)\naxs[0].plot(bvalue_fit, signal_fit, 'r-')\ntext = f\"\"\"$D =$ {D:.4f} $10^{{-9}}m^2/s$ \n $u_D =$ {uD:.1g} $10^{{-9}}m^2/s$ \n $r^2 =$ {r_squared:.5g}\"\"\"\naxs[0].text(bvalue[-1] * 0.6, 0.5 * (max(signal) - min(signal)) + min(\n signal), text, multialignment='left')\naxs[0].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='$S$')\naxs[0].set_yscale('log')\naxs[0].yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[0].yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[1].plot(bvalue, residuals, 'ko')\naxs[1].axhline(0, color='k', linestyle='--')\naxs[1].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='Residuos')\naxs[1].set_yscale('symlog')\nylim = 10 ** np.ceil(np.log10(np.max(abs(residuals))))\naxs[1].set_ylim([-ylim, ylim])\nif save:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n filename = f'{savepath}/datos_Diff/figuras/{filename0}_Diff.png'\n fig.savefig(filename)\n filename = (\n f'{savepath}/datos_Diff/figuras/{filename0}_Diff-RegionIntegracion.png'\n )\n fig1d.savefig(filename)\n header = f\"\"\"Archivo de datos: {path_bruker}\nRango de integracion: {ppmRange} ppm\nbvalue (10^-9 m^2/s)\t S (norm)\ngpz (%)\"\"\"\n Diffdata = np.array([bvalue, signal, gplist]).T\n np.savetxt(f'{savepath}/datos_Diff/{filename0}_Diff.dat', Diffdata,\n header=header)\nplt.show()\n",
"<docstring token>\n<import token>\n<assignment token>\nif N > 10:\n if Nmuestra == 21 or Nmuestra == 23:\n matriz = 'Q3'\n elif Nmuestra == 22:\n matriz = 'Q30'\n elif Nmuestra == 24:\n matriz = 'Bulk'\nelif N < 3:\n matriz = 'Q3'\nelif N < 6:\n matriz = 'Q30'\nelif N < 9:\n matriz = 'Bulk'\nif Nmuestra == 23:\n pc = 0\nelif N > 10:\n pc = 30\nelif N % 3 == 0:\n pc = 50\nelif N % 3 == 1:\n pc = 70\nelif N % 3 == 2:\n pc = 90\n<assignment token>\nprint(msg)\n<assignment token>\nfor nn in range(len(expnums)):\n expn = expnums[nn]\n print(expn)\n if True:\n color.append('k')\n else:\n color.append('b')\n datos = DatosProcesados(f'{path}/{expn}/')\n nucleo = datos.nucleo\n gplist.append(datos.acqus.gp)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if save1d:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n data = np.array([ppmAxis, re, im]).T\n filename = (\n f'{savepath}/datos_Diff/Espectros_vs_gpz/{filename0}_gpz{datos.acqus.gp:0>5.2f}.dat'\n )\n np.savetxt(filename, data)\n datos.espectro.ppmSelect(ppmRange, centrado_en_maximo=centrado_en_maximo)\n re = datos.espectro.real\n im = datos.espectro.imag\n ppmAxis = datos.espectro.ppmAxis\n if ABSsignal:\n spec_integrado = np.abs(re + 1.0j * im)\n else:\n spec_integrado = re\n ancho = np.abs(ppmAxis[0] - ppmAxis[-1])\n integral = scipy.integrate.simps(spec_integrado, x=-ppmAxis) / ancho\n intensidades.append(integral)\n datos.set_fid()\n timeAxis = datos.fid.timeAxis\n fid = datos.fid.real\n fid = np.abs(datos.fid.real + 1.0j * datos.fid.imag)\n intensidadFID = np.sum(fid[0:NptsFid])\n intensidadesFID.append(intensidadFID)\n print('graficando...', nucleo, muestra)\n axs[0].plot(ppmAxis, spec_integrado, linewidth=2, color=color[nn])\n axs[0].set_xlabel(f'{nucleo} NMR Shift [ppm]')\n axs[1].plot(timeAxis * 1000, fid, 'o-', linewidth=2)\n axs[1].set_xlabel(f'time [ms]')\n if datos.acqus.gp == min_gp:\n spec1d = re\n spec1d_im = im\n<assignment token>\nfig1d.suptitle(titulo)\n<assignment token>\nif 'sin' in gpshape.lower():\n bvalue = (gamma * gplist * delta / np.pi) ** 2 * (4 * bigDelta - delta\n ) * 1e-09\nelif 'rect' in gpshape.lower():\n bvalue = (gamma * gplist * delta) ** 2 * (bigDelta - delta / 3) * 1e-09\n<assignment token>\nif FIDsignal:\n signal = np.array(intensidadesFID)\nelse:\n signal = np.array(intensidades)\n<assignment token>\nprint(msg)\n<assignment token>\naxs[0].set_title(titulo)\naxs[0].scatter(bvalue, signal, c=color)\naxs[0].plot(bvalue_fit, signal_fit, 'r-')\n<assignment token>\naxs[0].text(bvalue[-1] * 0.6, 0.5 * (max(signal) - min(signal)) + min(\n signal), text, multialignment='left')\naxs[0].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='$S$')\naxs[0].set_yscale('log')\naxs[0].yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[0].yaxis.set_minor_formatter(ticker.FormatStrFormatter('%.1g'))\naxs[1].plot(bvalue, residuals, 'ko')\naxs[1].axhline(0, color='k', linestyle='--')\naxs[1].set(xlabel='$b_{value} [10^9 s/m^2]$', ylabel='Residuos')\naxs[1].set_yscale('symlog')\n<assignment token>\naxs[1].set_ylim([-ylim, ylim])\nif save:\n filename0 = f'{muestra}_{pc}pc_{matriz}'\n filename = f'{savepath}/datos_Diff/figuras/{filename0}_Diff.png'\n fig.savefig(filename)\n filename = (\n f'{savepath}/datos_Diff/figuras/{filename0}_Diff-RegionIntegracion.png'\n )\n fig1d.savefig(filename)\n header = f\"\"\"Archivo de datos: {path_bruker}\nRango de integracion: {ppmRange} ppm\nbvalue (10^-9 m^2/s)\t S (norm)\ngpz (%)\"\"\"\n Diffdata = np.array([bvalue, signal, gplist]).T\n np.savetxt(f'{savepath}/datos_Diff/{filename0}_Diff.dat', Diffdata,\n header=header)\nplt.show()\n",
"<docstring token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment 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,970 | 7913ca2d7d428c4b4851e7ad52ccfc578e1a5f65 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:06:17 2023
@author: Gilles.DELBECQ
"""
import sys, struct, math, os, time
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
def read_data(filename):
"""Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.
Data are returned in a dictionary, for future extensibility.
"""
from intanutil.read_header import read_header
from intanutil.get_bytes_per_data_block import get_bytes_per_data_block
from intanutil.read_one_data_block import read_one_data_block
from intanutil.notch_filter import notch_filter
from intanutil.data_to_result import data_to_result
tic = time.time()
fid = open(filename, 'rb')
filesize = os.path.getsize(filename)
header = read_header(fid)
print('Found {} amplifier channel{}.'.format(header['num_amplifier_channels'], plural(header['num_amplifier_channels'])))
print('Found {} auxiliary input channel{}.'.format(header['num_aux_input_channels'], plural(header['num_aux_input_channels'])))
print('Found {} supply voltage channel{}.'.format(header['num_supply_voltage_channels'], plural(header['num_supply_voltage_channels'])))
print('Found {} board ADC channel{}.'.format(header['num_board_adc_channels'], plural(header['num_board_adc_channels'])))
print('Found {} board digital input channel{}.'.format(header['num_board_dig_in_channels'], plural(header['num_board_dig_in_channels'])))
print('Found {} board digital output channel{}.'.format(header['num_board_dig_out_channels'], plural(header['num_board_dig_out_channels'])))
print('Found {} temperature sensors channel{}.'.format(header['num_temp_sensor_channels'], plural(header['num_temp_sensor_channels'])))
print('')
# Determine how many samples the data file contains.
bytes_per_block = get_bytes_per_data_block(header)
# How many data blocks remain in this file?
data_present = False
bytes_remaining = filesize - fid.tell()
if bytes_remaining > 0:
data_present = True
if bytes_remaining % bytes_per_block != 0:
raise Exception('Something is wrong with file size : should have a whole number of data blocks')
num_data_blocks = int(bytes_remaining / bytes_per_block)
num_amplifier_samples = header['num_samples_per_data_block'] * num_data_blocks
num_aux_input_samples = int((header['num_samples_per_data_block'] / 4) * num_data_blocks)
num_supply_voltage_samples = 1 * num_data_blocks
num_board_adc_samples = header['num_samples_per_data_block'] * num_data_blocks
num_board_dig_in_samples = header['num_samples_per_data_block'] * num_data_blocks
num_board_dig_out_samples = header['num_samples_per_data_block'] * num_data_blocks
record_time = num_amplifier_samples / header['sample_rate']
if data_present:
print('File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'.format(record_time, header['sample_rate'] / 1000))
else:
print('Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'.format(header['sample_rate'] / 1000))
if data_present:
# Pre-allocate memory for data.
print('')
print('Allocating memory for data...')
data = {}
if (header['version']['major'] == 1 and header['version']['minor'] >= 2) or (header['version']['major'] > 1):
data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_)
else:
data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint)
data['amplifier_data'] = np.zeros([header['num_amplifier_channels'], num_amplifier_samples], dtype=np.uint)
data['aux_input_data'] = np.zeros([header['num_aux_input_channels'], num_aux_input_samples], dtype=np.uint)
data['supply_voltage_data'] = np.zeros([header['num_supply_voltage_channels'], num_supply_voltage_samples], dtype=np.uint)
data['temp_sensor_data'] = np.zeros([header['num_temp_sensor_channels'], num_supply_voltage_samples], dtype=np.uint)
data['board_adc_data'] = np.zeros([header['num_board_adc_channels'], num_board_adc_samples], dtype=np.uint)
# by default, this script interprets digital events (digital inputs and outputs) as booleans
# if unsigned int values are preferred(0 for False, 1 for True), replace the 'dtype=np.bool_' argument with 'dtype=np.uint' as shown
# the commented line below illustrates this for digital input data; the same can be done for digital out
#data['board_dig_in_data'] = np.zeros([header['num_board_dig_in_channels'], num_board_dig_in_samples], dtype=np.uint)
data['board_dig_in_data'] = np.zeros([header['num_board_dig_in_channels'], num_board_dig_in_samples], dtype=np.bool_)
data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype=np.uint)
data['board_dig_out_data'] = np.zeros([header['num_board_dig_out_channels'], num_board_dig_out_samples], dtype=np.bool_)
data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples, dtype=np.uint)
# Read sampled data from file.
print('Reading data from file...')
# Initialize indices used in looping
indices = {}
indices['amplifier'] = 0
indices['aux_input'] = 0
indices['supply_voltage'] = 0
indices['board_adc'] = 0
indices['board_dig_in'] = 0
indices['board_dig_out'] = 0
print_increment = 10
percent_done = print_increment
for i in range(num_data_blocks):
read_one_data_block(data, header, indices, fid)
# Increment indices
indices['amplifier'] += header['num_samples_per_data_block']
indices['aux_input'] += int(header['num_samples_per_data_block'] / 4)
indices['supply_voltage'] += 1
indices['board_adc'] += header['num_samples_per_data_block']
indices['board_dig_in'] += header['num_samples_per_data_block']
indices['board_dig_out'] += header['num_samples_per_data_block']
fraction_done = 100 * (1.0 * i / num_data_blocks)
if fraction_done >= percent_done:
print('{}% done...'.format(percent_done))
percent_done = percent_done + print_increment
# Make sure we have read exactly the right amount of data.
bytes_remaining = filesize - fid.tell()
if bytes_remaining != 0: raise Exception('Error: End of file not reached.')
# Close data file.
fid.close()
if (data_present):
print('Parsing data...')
# Extract digital input channels to separate variables.
for i in range(header['num_board_dig_in_channels']):
data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(data['board_dig_in_raw'], (1 << header['board_dig_in_channels'][i]['native_order'])), 0)
# Extract digital output channels to separate variables.
for i in range(header['num_board_dig_out_channels']):
data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(data['board_dig_out_raw'], (1 << header['board_dig_out_channels'][i]['native_order'])), 0)
# Scale voltage levels appropriately.
data['amplifier_data'] = np.multiply(0.195, (data['amplifier_data'].astype(np.int32) - 32768)) # units = microvolts
data['aux_input_data'] = np.multiply(37.4e-6, data['aux_input_data']) # units = volts
data['supply_voltage_data'] = np.multiply(74.8e-6, data['supply_voltage_data']) # units = volts
if header['eval_board_mode'] == 1:
data['board_adc_data'] = np.multiply(152.59e-6, (data['board_adc_data'].astype(np.int32) - 32768)) # units = volts
elif header['eval_board_mode'] == 13:
data['board_adc_data'] = np.multiply(312.5e-6, (data['board_adc_data'].astype(np.int32) - 32768)) # units = volts
else:
data['board_adc_data'] = np.multiply(50.354e-6, data['board_adc_data']) # units = volts
data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data']) # units = deg C
# Check for gaps in timestamps.
num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:]-data['t_amplifier'][:-1], 1))
if num_gaps == 0:
print('No missing timestamps in data.')
else:
print('Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'.format(num_gaps))
# Scale time steps (units = seconds).
data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']
data['t_aux_input'] = data['t_amplifier'][range(0, len(data['t_amplifier']), 4)]
data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data['t_amplifier']), header['num_samples_per_data_block'])]
data['t_board_adc'] = data['t_amplifier']
data['t_dig'] = data['t_amplifier']
data['t_temp_sensor'] = data['t_supply_voltage']
# If the software notch filter was selected during the recording, apply the
# same notch filter to amplifier data here.
if header['notch_filter_frequency'] > 0 and header['version']['major'] < 3:
print('Applying notch filter...')
print_increment = 10
percent_done = print_increment
for i in range(header['num_amplifier_channels']):
data['amplifier_data'][i,:] = notch_filter(data['amplifier_data'][i,:], header['sample_rate'], header['notch_filter_frequency'], 10)
fraction_done = 100 * (i / header['num_amplifier_channels'])
if fraction_done >= percent_done:
print('{}% done...'.format(percent_done))
percent_done += print_increment
else:
data = [];
# Move variables to result struct.
result = data_to_result(header, data, data_present)
print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))
return result
def plural(n):
"""Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's'
path="//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd"
reader=read_data(path)
sampling_rate = reader['frequency_parameters']['amplifier_sample_rate']
time_vector=reader['t_amplifier']
signal=reader['amplifier_data']
selected_channels=['2','3','4','9','10','11','12','14','15']
#Filtering parameters
freq_low = 300
freq_high = 3000
order = 4
# Noise parameters
std_threshold = 5 #Times the std
noise_window = 5 #window for the noise calculation in sec
distance = 50 # distance between 2 spikes
#waveform window
waveform_window=5 #ms
Waveforms = True
def extract_spike_waveform(signal, spike_idx, left_width=(waveform_window/1000)*20000/2, right_width=(waveform_window/1000)*20000/2):
'''
Function to extract spikes waveforms in spike2 recordings
INPUTS :
signal (1-d array) : the ephy signal
spike_idx (1-d array or integer list) : array containing the spike indexes (in points)
width (int) = width for spike window
OUTPUTS :
SPIKES (list) : a list containg the waveform of each spike
'''
SPIKES = []
left_width = int(left_width)
right_width = int(right_width)
for i in range(len(spike_idx)):
index = spike_idx[i]
spike_wf = signal[index-left_width : index+right_width]
SPIKES.append(spike_wf)
return SPIKES
def filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=freq_low, freq_high=freq_high, axis=0):
"""
From Théo G.
Filtering with scipy
inputs raw signal (array)
returns filtered signal (array)
"""
import scipy.signal
Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]
sos_coeff = scipy.signal.iirfilter(order, Wn, btype="band", ftype="butter", output="sos")
filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)
return filtered_signal
# def notch_filter(signal, order=4, sample_rate=20000, freq_low=48, freq_high=52, axis=0):
# import scipy.signal
# Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]
# notch_coeff = scipy.signal.iirfilter(order, Wn, btype="bandstop", ftype="butter", output="sos")
# notch_signal = scipy.signal.sosfiltfilt(notch_coeff, signal, axis=axis)
# return notch_signal
filtered_signals=[]
for i in selected_channels:
filtered_signal=filter_signal(signal[int(i),:])
filtered_signals.append(filtered_signal)
# plt.figure()
# # plt.plot(time_vector,signal[0,:])
# plt.plot(time_vector,filtered_signal)
# plt.title(rf'channel {int(i)}')
filtered_signals = np.array(filtered_signals)
median = np.median(filtered_signals, axis=0)#compute median on all
cmr_signals = filtered_signals-median #compute common ref removal median on all
for i in range(len(cmr_signals)):
plt.figure()
plt.plot(time_vector,cmr_signals[i])
plt.title(rf'channel {int(selected_channels[i])}')
"""
Spike detection
"""
thresholds=[]
spikes_list=[]
spikes_list_y=[]
wfs=[]
waveforms=[]
for signal in cmr_signals:
# Threshold calculation
noise = signal[0:int(noise_window*sampling_rate)] #noise window taken from individual channel signal
threshold = np.median(noise)+std_threshold*np.std(noise) #threshold calculation for the channel
thresholds.append(threshold) #append it to the list regrouping threshold for each channel
#Detect the spike indexes
spike_idx, _ = sp.find_peaks(-signal,height=threshold,distance=distance)
#Convert to spike times
spike_times = spike_idx*1./sampling_rate
#Get spikes peak
spike_y = signal[spike_idx]
#Append spikes times to the list of all channels spikes
spikes_list.append(spike_times)
spikes_list_y.append(spike_y)
if Waveforms == True :
wfs = extract_spike_waveform(signal,spike_idx)
waveforms.append(wfs)
for index,i in np.ndenumerate(waveforms):
plt.figure()
# plt.title(rf'waveform_chan_{selected_chan[index[0]]}')
time_axis=np.array(range(int(-(waveform_window/1000)*20000/2),int(waveform_window/1000*20000/2)))/20000*1000
for j in i:
plt.plot(j*1000)
# plt.savefig(rf'{save_path}\waveform_chan_{selected_chan[index[0]]}.svg') | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 28 16:06:17 2023\n\n@author: Gilles.DELBECQ\n\"\"\"\n\nimport sys, struct, math, os, time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport scipy.signal as sp\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result \n \n\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n\n header = read_header(fid)\n\n print('Found {} amplifier channel{}.'.format(header['num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header['num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header['num_supply_voltage_channels'], plural(header['num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header['num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header['num_board_dig_in_channels'], plural(header['num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header['num_board_dig_out_channels'], plural(header['num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header['num_temp_sensor_channels'], plural(header['num_temp_sensor_channels'])))\n print('')\n\n # Determine how many samples the data file contains.\n bytes_per_block = get_bytes_per_data_block(header)\n\n # How many data blocks remain in this file?\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n\n if bytes_remaining % bytes_per_block != 0:\n raise Exception('Something is wrong with file size : should have a whole number of data blocks')\n\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n\n num_amplifier_samples = header['num_samples_per_data_block'] * num_data_blocks\n num_aux_input_samples = int((header['num_samples_per_data_block'] / 4) * num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'] * num_data_blocks\n\n record_time = num_amplifier_samples / header['sample_rate']\n\n if data_present:\n print('File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'.format(record_time, header['sample_rate'] / 1000))\n else:\n print('Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'.format(header['sample_rate'] / 1000))\n\n if data_present:\n # Pre-allocate memory for data.\n print('')\n print('Allocating memory for data...')\n\n data = {}\n if (header['version']['major'] == 1 and header['version']['minor'] >= 2) or (header['version']['major'] > 1):\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_)\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint)\n\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'], num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'], num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header['num_supply_voltage_channels'], num_supply_voltage_samples], dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header['num_temp_sensor_channels'], num_supply_voltage_samples], dtype=np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'], num_board_adc_samples], dtype=np.uint)\n \n # by default, this script interprets digital events (digital inputs and outputs) as booleans\n # if unsigned int values are preferred(0 for False, 1 for True), replace the 'dtype=np.bool_' argument with 'dtype=np.uint' as shown\n # the commented line below illustrates this for digital input data; the same can be done for digital out\n \n #data['board_dig_in_data'] = np.zeros([header['num_board_dig_in_channels'], num_board_dig_in_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header['num_board_dig_in_channels'], num_board_dig_in_samples], dtype=np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype=np.uint)\n \n data['board_dig_out_data'] = np.zeros([header['num_board_dig_out_channels'], num_board_dig_out_samples], dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples, dtype=np.uint)\n\n # Read sampled data from file.\n print('Reading data from file...')\n\n # Initialize indices used in looping\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n\n # Increment indices\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block'] \n\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n\n # Make sure we have read exactly the right amount of data.\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0: raise Exception('Error: End of file not reached.')\n\n\n\n # Close data file.\n fid.close()\n\n if (data_present):\n print('Parsing data...')\n\n # Extract digital input channels to separate variables.\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(data['board_dig_in_raw'], (1 << header['board_dig_in_channels'][i]['native_order'])), 0)\n\n # Extract digital output channels to separate variables.\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(data['board_dig_out_raw'], (1 << header['board_dig_out_channels'][i]['native_order'])), 0)\n\n # Scale voltage levels appropriately.\n data['amplifier_data'] = np.multiply(0.195, (data['amplifier_data'].astype(np.int32) - 32768)) # units = microvolts\n data['aux_input_data'] = np.multiply(37.4e-6, data['aux_input_data']) # units = volts\n data['supply_voltage_data'] = np.multiply(74.8e-6, data['supply_voltage_data']) # units = volts\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(152.59e-6, (data['board_adc_data'].astype(np.int32) - 32768)) # units = volts\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(312.5e-6, (data['board_adc_data'].astype(np.int32) - 32768)) # units = volts\n else:\n data['board_adc_data'] = np.multiply(50.354e-6, data['board_adc_data']) # units = volts\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data']) # units = deg C\n\n # Check for gaps in timestamps.\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:]-data['t_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print('Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'.format(num_gaps))\n\n # Scale time steps (units = seconds).\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data['t_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data['t_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n\n # If the software notch filter was selected during the recording, apply the\n # same notch filter to amplifier data here.\n if header['notch_filter_frequency'] > 0 and header['version']['major'] < 3:\n print('Applying notch filter...')\n\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i,:] = notch_filter(data['amplifier_data'][i,:], header['sample_rate'], header['notch_filter_frequency'], 10)\n\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = [];\n\n # Move variables to result struct.\n result = data_to_result(header, data, data_present)\n\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n\n if n == 1:\n return ''\n else:\n return 's'\n\n\n\npath=\"//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd\"\n\nreader=read_data(path)\n\nsampling_rate = reader['frequency_parameters']['amplifier_sample_rate']\ntime_vector=reader['t_amplifier']\nsignal=reader['amplifier_data']\n\nselected_channels=['2','3','4','9','10','11','12','14','15']\n\n#Filtering parameters\nfreq_low = 300\nfreq_high = 3000\norder = 4\n\n\n# Noise parameters\nstd_threshold = 5 #Times the std\nnoise_window = 5 #window for the noise calculation in sec\ndistance = 50 # distance between 2 spikes\n\n#waveform window\nwaveform_window=5 #ms\nWaveforms = True\n\ndef extract_spike_waveform(signal, spike_idx, left_width=(waveform_window/1000)*20000/2, right_width=(waveform_window/1000)*20000/2):\n \n '''\n Function to extract spikes waveforms in spike2 recordings\n \n INPUTS :\n signal (1-d array) : the ephy signal\n spike_idx (1-d array or integer list) : array containing the spike indexes (in points)\n width (int) = width for spike window\n \n OUTPUTS : \n SPIKES (list) : a list containg the waveform of each spike \n \n '''\n \n SPIKES = []\n \n left_width = int(left_width)\n right_width = int(right_width)\n \n for i in range(len(spike_idx)): \n index = spike_idx[i]\n\n spike_wf = signal[index-left_width : index+right_width]\n\n SPIKES.append(spike_wf)\n return SPIKES\n\n\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n \n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype=\"band\", ftype=\"butter\", output=\"sos\")\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\n# def notch_filter(signal, order=4, sample_rate=20000, freq_low=48, freq_high=52, axis=0):\n# import scipy.signal\n# Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n# notch_coeff = scipy.signal.iirfilter(order, Wn, btype=\"bandstop\", ftype=\"butter\", output=\"sos\")\n# notch_signal = scipy.signal.sosfiltfilt(notch_coeff, signal, axis=axis)\n\n# return notch_signal\n\nfiltered_signals=[]\n\nfor i in selected_channels:\n \n filtered_signal=filter_signal(signal[int(i),:])\n filtered_signals.append(filtered_signal)\n # plt.figure()\n # # plt.plot(time_vector,signal[0,:])\n # plt.plot(time_vector,filtered_signal)\n # plt.title(rf'channel {int(i)}')\n\nfiltered_signals = np.array(filtered_signals)\nmedian = np.median(filtered_signals, axis=0)#compute median on all \ncmr_signals = filtered_signals-median #compute common ref removal median on all \n\nfor i in range(len(cmr_signals)):\n plt.figure()\n plt.plot(time_vector,cmr_signals[i])\n plt.title(rf'channel {int(selected_channels[i])}')\n \n\n\"\"\"\nSpike detection\n\"\"\"\nthresholds=[]\nspikes_list=[]\nspikes_list_y=[]\nwfs=[]\nwaveforms=[]\nfor signal in cmr_signals:\n # Threshold calculation\n noise = signal[0:int(noise_window*sampling_rate)] #noise window taken from individual channel signal\n threshold = np.median(noise)+std_threshold*np.std(noise) #threshold calculation for the channel\n thresholds.append(threshold) #append it to the list regrouping threshold for each channel\n \n \n #Detect the spike indexes\n spike_idx, _ = sp.find_peaks(-signal,height=threshold,distance=distance)\n #Convert to spike times\n spike_times = spike_idx*1./sampling_rate\n #Get spikes peak \n spike_y = signal[spike_idx]\n \n #Append spikes times to the list of all channels spikes\n spikes_list.append(spike_times)\n spikes_list_y.append(spike_y)\n \n if Waveforms == True :\n wfs = extract_spike_waveform(signal,spike_idx)\n waveforms.append(wfs)\n\nfor index,i in np.ndenumerate(waveforms):\n plt.figure()\n # plt.title(rf'waveform_chan_{selected_chan[index[0]]}')\n time_axis=np.array(range(int(-(waveform_window/1000)*20000/2),int(waveform_window/1000*20000/2)))/20000*1000\n for j in i:\n plt.plot(j*1000)\n # plt.savefig(rf'{save_path}\\waveform_chan_{selected_chan[index[0]]}.svg')",
"<docstring token>\nimport sys, struct, math, os, time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sp\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n if n == 1:\n return ''\n else:\n return 's'\n\n\npath = (\n '//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd'\n )\nreader = read_data(path)\nsampling_rate = reader['frequency_parameters']['amplifier_sample_rate']\ntime_vector = reader['t_amplifier']\nsignal = reader['amplifier_data']\nselected_channels = ['2', '3', '4', '9', '10', '11', '12', '14', '15']\nfreq_low = 300\nfreq_high = 3000\norder = 4\nstd_threshold = 5\nnoise_window = 5\ndistance = 50\nwaveform_window = 5\nWaveforms = True\n\n\ndef extract_spike_waveform(signal, spike_idx, left_width=waveform_window / \n 1000 * 20000 / 2, right_width=waveform_window / 1000 * 20000 / 2):\n \"\"\"\n Function to extract spikes waveforms in spike2 recordings\n \n INPUTS :\n signal (1-d array) : the ephy signal\n spike_idx (1-d array or integer list) : array containing the spike indexes (in points)\n width (int) = width for spike window\n \n OUTPUTS : \n SPIKES (list) : a list containg the waveform of each spike \n \n \"\"\"\n SPIKES = []\n left_width = int(left_width)\n right_width = int(right_width)\n for i in range(len(spike_idx)):\n index = spike_idx[i]\n spike_wf = signal[index - left_width:index + right_width]\n SPIKES.append(spike_wf)\n return SPIKES\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\nfiltered_signals = []\nfor i in selected_channels:\n filtered_signal = filter_signal(signal[int(i), :])\n filtered_signals.append(filtered_signal)\nfiltered_signals = np.array(filtered_signals)\nmedian = np.median(filtered_signals, axis=0)\ncmr_signals = filtered_signals - median\nfor i in range(len(cmr_signals)):\n plt.figure()\n plt.plot(time_vector, cmr_signals[i])\n plt.title(f'channel {int(selected_channels[i])}')\n<docstring token>\nthresholds = []\nspikes_list = []\nspikes_list_y = []\nwfs = []\nwaveforms = []\nfor signal in cmr_signals:\n noise = signal[0:int(noise_window * sampling_rate)]\n threshold = np.median(noise) + std_threshold * np.std(noise)\n thresholds.append(threshold)\n spike_idx, _ = sp.find_peaks(-signal, height=threshold, distance=distance)\n spike_times = spike_idx * 1.0 / sampling_rate\n spike_y = signal[spike_idx]\n spikes_list.append(spike_times)\n spikes_list_y.append(spike_y)\n if Waveforms == True:\n wfs = extract_spike_waveform(signal, spike_idx)\n waveforms.append(wfs)\nfor index, i in np.ndenumerate(waveforms):\n plt.figure()\n time_axis = np.array(range(int(-(waveform_window / 1000) * 20000 / 2),\n int(waveform_window / 1000 * 20000 / 2))) / 20000 * 1000\n for j in i:\n plt.plot(j * 1000)\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n if n == 1:\n return ''\n else:\n return 's'\n\n\npath = (\n '//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd'\n )\nreader = read_data(path)\nsampling_rate = reader['frequency_parameters']['amplifier_sample_rate']\ntime_vector = reader['t_amplifier']\nsignal = reader['amplifier_data']\nselected_channels = ['2', '3', '4', '9', '10', '11', '12', '14', '15']\nfreq_low = 300\nfreq_high = 3000\norder = 4\nstd_threshold = 5\nnoise_window = 5\ndistance = 50\nwaveform_window = 5\nWaveforms = True\n\n\ndef extract_spike_waveform(signal, spike_idx, left_width=waveform_window / \n 1000 * 20000 / 2, right_width=waveform_window / 1000 * 20000 / 2):\n \"\"\"\n Function to extract spikes waveforms in spike2 recordings\n \n INPUTS :\n signal (1-d array) : the ephy signal\n spike_idx (1-d array or integer list) : array containing the spike indexes (in points)\n width (int) = width for spike window\n \n OUTPUTS : \n SPIKES (list) : a list containg the waveform of each spike \n \n \"\"\"\n SPIKES = []\n left_width = int(left_width)\n right_width = int(right_width)\n for i in range(len(spike_idx)):\n index = spike_idx[i]\n spike_wf = signal[index - left_width:index + right_width]\n SPIKES.append(spike_wf)\n return SPIKES\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\nfiltered_signals = []\nfor i in selected_channels:\n filtered_signal = filter_signal(signal[int(i), :])\n filtered_signals.append(filtered_signal)\nfiltered_signals = np.array(filtered_signals)\nmedian = np.median(filtered_signals, axis=0)\ncmr_signals = filtered_signals - median\nfor i in range(len(cmr_signals)):\n plt.figure()\n plt.plot(time_vector, cmr_signals[i])\n plt.title(f'channel {int(selected_channels[i])}')\n<docstring token>\nthresholds = []\nspikes_list = []\nspikes_list_y = []\nwfs = []\nwaveforms = []\nfor signal in cmr_signals:\n noise = signal[0:int(noise_window * sampling_rate)]\n threshold = np.median(noise) + std_threshold * np.std(noise)\n thresholds.append(threshold)\n spike_idx, _ = sp.find_peaks(-signal, height=threshold, distance=distance)\n spike_times = spike_idx * 1.0 / sampling_rate\n spike_y = signal[spike_idx]\n spikes_list.append(spike_times)\n spikes_list_y.append(spike_y)\n if Waveforms == True:\n wfs = extract_spike_waveform(signal, spike_idx)\n waveforms.append(wfs)\nfor index, i in np.ndenumerate(waveforms):\n plt.figure()\n time_axis = np.array(range(int(-(waveform_window / 1000) * 20000 / 2),\n int(waveform_window / 1000 * 20000 / 2))) / 20000 * 1000\n for j in i:\n plt.plot(j * 1000)\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n if n == 1:\n return ''\n else:\n return 's'\n\n\n<assignment token>\n\n\ndef extract_spike_waveform(signal, spike_idx, left_width=waveform_window / \n 1000 * 20000 / 2, right_width=waveform_window / 1000 * 20000 / 2):\n \"\"\"\n Function to extract spikes waveforms in spike2 recordings\n \n INPUTS :\n signal (1-d array) : the ephy signal\n spike_idx (1-d array or integer list) : array containing the spike indexes (in points)\n width (int) = width for spike window\n \n OUTPUTS : \n SPIKES (list) : a list containg the waveform of each spike \n \n \"\"\"\n SPIKES = []\n left_width = int(left_width)\n right_width = int(right_width)\n for i in range(len(spike_idx)):\n index = spike_idx[i]\n spike_wf = signal[index - left_width:index + right_width]\n SPIKES.append(spike_wf)\n return SPIKES\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\n<assignment token>\nfor i in selected_channels:\n filtered_signal = filter_signal(signal[int(i), :])\n filtered_signals.append(filtered_signal)\n<assignment token>\nfor i in range(len(cmr_signals)):\n plt.figure()\n plt.plot(time_vector, cmr_signals[i])\n plt.title(f'channel {int(selected_channels[i])}')\n<docstring token>\n<assignment token>\nfor signal in cmr_signals:\n noise = signal[0:int(noise_window * sampling_rate)]\n threshold = np.median(noise) + std_threshold * np.std(noise)\n thresholds.append(threshold)\n spike_idx, _ = sp.find_peaks(-signal, height=threshold, distance=distance)\n spike_times = spike_idx * 1.0 / sampling_rate\n spike_y = signal[spike_idx]\n spikes_list.append(spike_times)\n spikes_list_y.append(spike_y)\n if Waveforms == True:\n wfs = extract_spike_waveform(signal, spike_idx)\n waveforms.append(wfs)\nfor index, i in np.ndenumerate(waveforms):\n plt.figure()\n time_axis = np.array(range(int(-(waveform_window / 1000) * 20000 / 2),\n int(waveform_window / 1000 * 20000 / 2))) / 20000 * 1000\n for j in i:\n plt.plot(j * 1000)\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n if n == 1:\n return ''\n else:\n return 's'\n\n\n<assignment token>\n\n\ndef extract_spike_waveform(signal, spike_idx, left_width=waveform_window / \n 1000 * 20000 / 2, right_width=waveform_window / 1000 * 20000 / 2):\n \"\"\"\n Function to extract spikes waveforms in spike2 recordings\n \n INPUTS :\n signal (1-d array) : the ephy signal\n spike_idx (1-d array or integer list) : array containing the spike indexes (in points)\n width (int) = width for spike window\n \n OUTPUTS : \n SPIKES (list) : a list containg the waveform of each spike \n \n \"\"\"\n SPIKES = []\n left_width = int(left_width)\n right_width = int(right_width)\n for i in range(len(spike_idx)):\n index = spike_idx[i]\n spike_wf = signal[index - left_width:index + right_width]\n SPIKES.append(spike_wf)\n return SPIKES\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\ndef plural(n):\n \"\"\"Utility function to optionally pluralize words based on the value of n.\n \"\"\"\n if n == 1:\n return ''\n else:\n return 's'\n\n\n<assignment token>\n<function token>\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\n<function token>\n<assignment token>\n<function token>\n\n\ndef filter_signal(signal, order=order, sample_rate=sampling_rate, freq_low=\n freq_low, freq_high=freq_high, axis=0):\n \"\"\"\n From Théo G.\n Filtering with scipy\n \n inputs raw signal (array)\n returns filtered signal (array)\n \"\"\"\n import scipy.signal\n Wn = [freq_low / (sample_rate / 2), freq_high / (sample_rate / 2)]\n sos_coeff = scipy.signal.iirfilter(order, Wn, btype='band', ftype=\n 'butter', output='sos')\n filtered_signal = scipy.signal.sosfiltfilt(sos_coeff, signal, axis=axis)\n return filtered_signal\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n",
"<docstring token>\n<import token>\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.\n \n Data are returned in a dictionary, for future extensibility.\n \"\"\"\n from intanutil.read_header import read_header\n from intanutil.get_bytes_per_data_block import get_bytes_per_data_block\n from intanutil.read_one_data_block import read_one_data_block\n from intanutil.notch_filter import notch_filter\n from intanutil.data_to_result import data_to_result\n tic = time.time()\n fid = open(filename, 'rb')\n filesize = os.path.getsize(filename)\n header = read_header(fid)\n print('Found {} amplifier channel{}.'.format(header[\n 'num_amplifier_channels'], plural(header['num_amplifier_channels'])))\n print('Found {} auxiliary input channel{}.'.format(header[\n 'num_aux_input_channels'], plural(header['num_aux_input_channels'])))\n print('Found {} supply voltage channel{}.'.format(header[\n 'num_supply_voltage_channels'], plural(header[\n 'num_supply_voltage_channels'])))\n print('Found {} board ADC channel{}.'.format(header[\n 'num_board_adc_channels'], plural(header['num_board_adc_channels'])))\n print('Found {} board digital input channel{}.'.format(header[\n 'num_board_dig_in_channels'], plural(header[\n 'num_board_dig_in_channels'])))\n print('Found {} board digital output channel{}.'.format(header[\n 'num_board_dig_out_channels'], plural(header[\n 'num_board_dig_out_channels'])))\n print('Found {} temperature sensors channel{}.'.format(header[\n 'num_temp_sensor_channels'], plural(header[\n 'num_temp_sensor_channels'])))\n print('')\n bytes_per_block = get_bytes_per_data_block(header)\n data_present = False\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining > 0:\n data_present = True\n if bytes_remaining % bytes_per_block != 0:\n raise Exception(\n 'Something is wrong with file size : should have a whole number of data blocks'\n )\n num_data_blocks = int(bytes_remaining / bytes_per_block)\n num_amplifier_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_aux_input_samples = int(header['num_samples_per_data_block'] / 4 *\n num_data_blocks)\n num_supply_voltage_samples = 1 * num_data_blocks\n num_board_adc_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_in_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n num_board_dig_out_samples = header['num_samples_per_data_block'\n ] * num_data_blocks\n record_time = num_amplifier_samples / header['sample_rate']\n if data_present:\n print(\n 'File contains {:0.3f} seconds of data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(record_time, header['sample_rate'] / 1000))\n else:\n print(\n 'Header file contains no data. Amplifiers were sampled at {:0.2f} kS/s.'\n .format(header['sample_rate'] / 1000))\n if data_present:\n print('')\n print('Allocating memory for data...')\n data = {}\n if header['version']['major'] == 1 and header['version']['minor'\n ] >= 2 or header['version']['major'] > 1:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.int_\n )\n else:\n data['t_amplifier'] = np.zeros(num_amplifier_samples, dtype=np.uint\n )\n data['amplifier_data'] = np.zeros([header['num_amplifier_channels'],\n num_amplifier_samples], dtype=np.uint)\n data['aux_input_data'] = np.zeros([header['num_aux_input_channels'],\n num_aux_input_samples], dtype=np.uint)\n data['supply_voltage_data'] = np.zeros([header[\n 'num_supply_voltage_channels'], num_supply_voltage_samples],\n dtype=np.uint)\n data['temp_sensor_data'] = np.zeros([header[\n 'num_temp_sensor_channels'], num_supply_voltage_samples], dtype\n =np.uint)\n data['board_adc_data'] = np.zeros([header['num_board_adc_channels'],\n num_board_adc_samples], dtype=np.uint)\n data['board_dig_in_data'] = np.zeros([header[\n 'num_board_dig_in_channels'], num_board_dig_in_samples], dtype=\n np.bool_)\n data['board_dig_in_raw'] = np.zeros(num_board_dig_in_samples, dtype\n =np.uint)\n data['board_dig_out_data'] = np.zeros([header[\n 'num_board_dig_out_channels'], num_board_dig_out_samples],\n dtype=np.bool_)\n data['board_dig_out_raw'] = np.zeros(num_board_dig_out_samples,\n dtype=np.uint)\n print('Reading data from file...')\n indices = {}\n indices['amplifier'] = 0\n indices['aux_input'] = 0\n indices['supply_voltage'] = 0\n indices['board_adc'] = 0\n indices['board_dig_in'] = 0\n indices['board_dig_out'] = 0\n print_increment = 10\n percent_done = print_increment\n for i in range(num_data_blocks):\n read_one_data_block(data, header, indices, fid)\n indices['amplifier'] += header['num_samples_per_data_block']\n indices['aux_input'] += int(header['num_samples_per_data_block'\n ] / 4)\n indices['supply_voltage'] += 1\n indices['board_adc'] += header['num_samples_per_data_block']\n indices['board_dig_in'] += header['num_samples_per_data_block']\n indices['board_dig_out'] += header['num_samples_per_data_block']\n fraction_done = 100 * (1.0 * i / num_data_blocks)\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done = percent_done + print_increment\n bytes_remaining = filesize - fid.tell()\n if bytes_remaining != 0:\n raise Exception('Error: End of file not reached.')\n fid.close()\n if data_present:\n print('Parsing data...')\n for i in range(header['num_board_dig_in_channels']):\n data['board_dig_in_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_in_raw'], 1 << header[\n 'board_dig_in_channels'][i]['native_order']), 0)\n for i in range(header['num_board_dig_out_channels']):\n data['board_dig_out_data'][i, :] = np.not_equal(np.bitwise_and(\n data['board_dig_out_raw'], 1 << header[\n 'board_dig_out_channels'][i]['native_order']), 0)\n data['amplifier_data'] = np.multiply(0.195, data['amplifier_data'].\n astype(np.int32) - 32768)\n data['aux_input_data'] = np.multiply(3.74e-05, data['aux_input_data'])\n data['supply_voltage_data'] = np.multiply(7.48e-05, data[\n 'supply_voltage_data'])\n if header['eval_board_mode'] == 1:\n data['board_adc_data'] = np.multiply(0.00015259, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n elif header['eval_board_mode'] == 13:\n data['board_adc_data'] = np.multiply(0.0003125, data[\n 'board_adc_data'].astype(np.int32) - 32768)\n else:\n data['board_adc_data'] = np.multiply(5.0354e-05, data[\n 'board_adc_data'])\n data['temp_sensor_data'] = np.multiply(0.01, data['temp_sensor_data'])\n num_gaps = np.sum(np.not_equal(data['t_amplifier'][1:] - data[\n 't_amplifier'][:-1], 1))\n if num_gaps == 0:\n print('No missing timestamps in data.')\n else:\n print(\n 'Warning: {0} gaps in timestamp data found. Time scale will not be uniform!'\n .format(num_gaps))\n data['t_amplifier'] = data['t_amplifier'] / header['sample_rate']\n data['t_aux_input'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), 4)]\n data['t_supply_voltage'] = data['t_amplifier'][range(0, len(data[\n 't_amplifier']), header['num_samples_per_data_block'])]\n data['t_board_adc'] = data['t_amplifier']\n data['t_dig'] = data['t_amplifier']\n data['t_temp_sensor'] = data['t_supply_voltage']\n if header['notch_filter_frequency'] > 0 and header['version']['major'\n ] < 3:\n print('Applying notch filter...')\n print_increment = 10\n percent_done = print_increment\n for i in range(header['num_amplifier_channels']):\n data['amplifier_data'][i, :] = notch_filter(data[\n 'amplifier_data'][i, :], header['sample_rate'], header[\n 'notch_filter_frequency'], 10)\n fraction_done = 100 * (i / header['num_amplifier_channels'])\n if fraction_done >= percent_done:\n print('{}% done...'.format(percent_done))\n percent_done += print_increment\n else:\n data = []\n result = data_to_result(header, data, data_present)\n print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))\n return result\n\n\n<function token>\n<assignment token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n<assignment token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<docstring token>\n<assignment token>\n<code token>\n"
] | false |
99,971 | cd6b1c8c1dae53c95f77b4af60fd401ff6c71285 | import numpy as np
import base64
import cv2
import os
class LSB:
# to get object's format, size, data
def get_object_info(self, file, itype):
try:
file_format = os.path.splitext(file)[-1].lower()
size = os.path.getsize(file)
name = os.path.basename(file)
name = name.replace(file_format, '')
except IOError:
print('[!] {} file could not be opened.'.format(itype.title()))
return size, file_format, name
def get_secret_object(self, file, itype):
try:
with open(file, 'rb') as data:
data = data.read()
except IOError:
print('[!] {} file could not be opened.'.format(itype.title()))
return data
def write_file(self, file_format, name, text):
with open('static\decode_output\\' + name + '_secret' + file_format, 'wb') as f:
f.write(text)
# ========================================== COVER OBJECT : IMAGE ==========================================
def get_cover_image(self, file, itype):
try:
data = cv2.imread(file)
except IOError:
print('[!] {} file could not be opened.'.format(itype.title()))
return data
def save_cover_image(self, data, outfile):
try:
cv2.imwrite(outfile, data)
except IOError as e:
raise IOError('[!] {} file could not be written.'.format(outfile) + '\n[!] {}'.format(e))
except Exception as e:
raise Exception('[!] Unable to save file.' + '\n[!] {}'.format(e))
# =============================================== CONVERTING ===============================================
# convert 'data' to binary format as string
def to_binary(self, data):
if isinstance(data, str):
return ''.join([format(ord(i), "08b") for i in data])
elif isinstance(data, bytes) or isinstance(data,np.ndarray):
return [format(i, "08b") for i in data]
elif isinstance(data, int) or isinstance(data,np.uint8):
return ''.join(data, "08b")
else:
raise TypeError("Type not supported.")
# convert binary into 'data'
def to_utf8_bytes(self, data):
return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')
class Img_Encode(LSB):
def __init__(self, cover, secret, bits):
print('[*] Encoding... ')
self.cover = self.get_cover_image(cover, 'cover')
cover_info = self.get_object_info(cover, 'cover')
cover_size = cover_info[0]
self.outfile = 'static\encode_output\\' + cover_info[2] + "_copy" + cover_info[1]
self.secret = self.get_secret_object(secret, 'secret')
secret_info = self.get_object_info(secret, 'secret')
secret_size = secret_info[0]
bit_pos = bits
self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)
# b64 -> binary
def to_base64(self, secret_info):
encoded_string = base64.b64encode(self.secret)
encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))
encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))
criteria = '#####'.encode('utf8') # add stopping criteria
result = encoded_string + criteria + encoded_file_format + criteria + encoded_name + criteria
result = ''.join(self.to_binary(result))
return result
def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):
data_index = 0
print("[*] Maximum bytes to encode: ", cover_size)
if secret_size > cover_size:
raise ValueError("[!] Insufficient bytes, need bigger image or less data.")
binary_secret_data = self.to_base64(secret_info)
data_len = len(binary_secret_data) # size of data to hide
for row in self.cover:
for pixel in row:
r, g, b = self.to_binary(pixel) # convert RGB values to binary format
list_r = list(r)
list_g = list(g)
list_b = list(b)
for i in range(len(bit_pos)):
if data_index < data_len: # modify the least significant bit only if there is still data to store
list_r[bit_pos[i]] = binary_secret_data[data_index] # least significant red pixel bit
pixel[0] = int("".join(list_r), 2)
data_index += 1
else:
break
for i in range(len(bit_pos)):
if data_index < data_len:
list_g[bit_pos[i]] = binary_secret_data[data_index] # least significant green pixel bit
pixel[1] = int("".join(list_g), 2)
data_index += 1
else:
break
for i in range(len(bit_pos)):
if data_index < data_len:
list_b[bit_pos[i]] = binary_secret_data[data_index] # least significant blue pixel bit
pixel[2] = int("".join(list_b), 2)
data_index += 1
else:
break
self.save_cover_image(self.cover, self.outfile)
class Img_Decode(LSB):
def __init__(self, steg, bits):
print('[*] Decoding... ')
self.steg = self.get_cover_image(steg, 'steg')
bit_pos = bits
self.file_format = self.decode_from_image(bit_pos)
def __str__(self):
return str(self.file_format)
# binary -> b64
def from_base64(self, data):
decoded_string = self.to_utf8_bytes(data)
result = decoded_string.split('#####'.encode('utf8'))
message = base64.b64decode(result[0])
file_format = base64.b64decode(result[1])
name = base64.b64decode(result[2])
return message, file_format, name
def decode_from_image(self, bit_pos):
binary_data = ""
for row in self.steg:
for pixel in row:
r, g, b = self.to_binary(pixel)
for i in range(len(bit_pos)):
binary_data += r[bit_pos[i]]
for i in range(len(bit_pos)):
binary_data += g[bit_pos[i]]
for i in range(len(bit_pos)):
binary_data += b[bit_pos[i]]
# split by 8 bits
extracted_bin = [binary_data[i: i+8] for i in range(0, len(binary_data), 8)]
message = self.from_base64(extracted_bin)[0]
file_format = self.from_base64(extracted_bin)[1].decode("utf-8")
name = self.from_base64(extracted_bin)[2].decode("utf-8")
self.write_file(file_format, name, message)
return name + "_secret" + file_format
def main():
payload = input("Enter payload file: ")
cover_image = input("Enter image file: ")
bits = int(input("Bits to replace? "))
bit_pos = []
for i in range(bits):
bitPosInput = int(input("Enter bit position #" + str(i+1) + " to replace (0 - 7) : "))
bit_pos.append(bitPosInput)
bit_pos.sort()
Img_Encode(cover_image, payload, bit_pos)
steg_image = input("Enter steg image name: ")
Img_Decode(steg_image, bit_pos)
if __name__ == '__main__':
main() | [
"import numpy as np\nimport base64\nimport cv2\nimport os\n\nclass LSB:\n # to get object's format, size, data \n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\decode_output\\\\' + name + '_secret' + file_format, 'wb') as f:\n f.write(text)\n \n # ========================================== COVER OBJECT : IMAGE ==========================================\n def get_cover_image(self, file, itype):\n try:\n data = cv2.imread(file)\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n \n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n \n # =============================================== CONVERTING ===============================================\n # convert 'data' to binary format as string\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), \"08b\") for i in data])\n elif isinstance(data, bytes) or isinstance(data,np.ndarray):\n return [format(i, \"08b\") for i in data]\n elif isinstance(data, int) or isinstance(data,np.uint8):\n return ''.join(data, \"08b\")\n else:\n raise TypeError(\"Type not supported.\")\n\n # convert binary into 'data'\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n \nclass Img_Encode(LSB):\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\encode_output\\\\' + cover_info[2] + \"_copy\" + cover_info[1]\n\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n # b64 -> binary\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n \n criteria = '#####'.encode('utf8') # add stopping criteria\n result = encoded_string + criteria + encoded_file_format + criteria + encoded_name + criteria\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n\n print(\"[*] Maximum bytes to encode: \", cover_size)\n if secret_size > cover_size:\n raise ValueError(\"[!] Insufficient bytes, need bigger image or less data.\")\n\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data) # size of data to hide\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel) # convert RGB values to binary format\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len: # modify the least significant bit only if there is still data to store\n list_r[bit_pos[i]] = binary_secret_data[data_index] # least significant red pixel bit\n pixel[0] = int(\"\".join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index] # least significant green pixel bit\n pixel[1] = int(\"\".join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len: \n list_b[bit_pos[i]] = binary_secret_data[data_index] # least significant blue pixel bit\n pixel[2] = int(\"\".join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n \nclass Img_Decode(LSB):\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n \n def __str__(self):\n return str(self.file_format)\n \n # binary -> b64\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = \"\"\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n \n # split by 8 bits\n extracted_bin = [binary_data[i: i+8] for i in range(0, len(binary_data), 8)]\n \n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode(\"utf-8\")\n name = self.from_base64(extracted_bin)[2].decode(\"utf-8\")\n self.write_file(file_format, name, message)\n\n return name + \"_secret\" + file_format\n\ndef main():\n \n payload = input(\"Enter payload file: \")\n cover_image = input(\"Enter image file: \")\n\n bits = int(input(\"Bits to replace? \"))\n bit_pos = []\n for i in range(bits):\n bitPosInput = int(input(\"Enter bit position #\" + str(i+1) + \" to replace (0 - 7) : \"))\n bit_pos.append(bitPosInput)\n bit_pos.sort()\n\n Img_Encode(cover_image, payload, bit_pos)\n \n steg_image = input(\"Enter steg image name: \") \n \n Img_Decode(steg_image, bit_pos)\n\n\nif __name__ == '__main__':\n main()",
"import numpy as np\nimport base64\nimport cv2\nimport os\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n\n def get_cover_image(self, file, itype):\n try:\n data = cv2.imread(file)\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\ndef main():\n payload = input('Enter payload file: ')\n cover_image = input('Enter image file: ')\n bits = int(input('Bits to replace? '))\n bit_pos = []\n for i in range(bits):\n bitPosInput = int(input('Enter bit position #' + str(i + 1) +\n ' to replace (0 - 7) : '))\n bit_pos.append(bitPosInput)\n bit_pos.sort()\n Img_Encode(cover_image, payload, bit_pos)\n steg_image = input('Enter steg image name: ')\n Img_Decode(steg_image, bit_pos)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n\n def get_cover_image(self, file, itype):\n try:\n data = cv2.imread(file)\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\ndef main():\n payload = input('Enter payload file: ')\n cover_image = input('Enter image file: ')\n bits = int(input('Bits to replace? '))\n bit_pos = []\n for i in range(bits):\n bitPosInput = int(input('Enter bit position #' + str(i + 1) +\n ' to replace (0 - 7) : '))\n bit_pos.append(bitPosInput)\n bit_pos.sort()\n Img_Encode(cover_image, payload, bit_pos)\n steg_image = input('Enter steg image name: ')\n Img_Decode(steg_image, bit_pos)\n\n\nif __name__ == '__main__':\n main()\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n\n def get_cover_image(self, file, itype):\n try:\n data = cv2.imread(file)\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\ndef main():\n payload = input('Enter payload file: ')\n cover_image = input('Enter image file: ')\n bits = int(input('Bits to replace? '))\n bit_pos = []\n for i in range(bits):\n bitPosInput = int(input('Enter bit position #' + str(i + 1) +\n ' to replace (0 - 7) : '))\n bit_pos.append(bitPosInput)\n bit_pos.sort()\n Img_Encode(cover_image, payload, bit_pos)\n steg_image = input('Enter steg image name: ')\n Img_Decode(steg_image, bit_pos)\n\n\n<code token>\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n\n def get_cover_image(self, file, itype):\n try:\n data = cv2.imread(file)\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n\n def get_secret_object(self, file, itype):\n try:\n with open(file, 'rb') as data:\n data = data.read()\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return data\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n <function token>\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n <function token>\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n <function token>\n\n def save_cover_image(self, data, outfile):\n try:\n cv2.imwrite(outfile, data)\n except IOError as e:\n raise IOError('[!] {} file could not be written.'.format(\n outfile) + '\\n[!] {}'.format(e))\n except Exception as e:\n raise Exception('[!] Unable to save file.' + '\\n[!] {}'.format(e))\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n\n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(file)\n name = name.replace(file_format, '')\n except IOError:\n print('[!] {} file could not be opened.'.format(itype.title()))\n return size, file_format, name\n <function token>\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n <function token>\n <function token>\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n <function token>\n <function token>\n\n def write_file(self, file_format, name, text):\n with open('static\\\\decode_output\\\\' + name + '_secret' +\n file_format, 'wb') as f:\n f.write(text)\n <function token>\n <function token>\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n\n def to_utf8_bytes(self, data):\n return bytes(''.join(chr(int(x, 2)) for x in data), encoding='utf8')\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def to_binary(self, data):\n if isinstance(data, str):\n return ''.join([format(ord(i), '08b') for i in data])\n elif isinstance(data, bytes) or isinstance(data, np.ndarray):\n return [format(i, '08b') for i in data]\n elif isinstance(data, int) or isinstance(data, np.uint8):\n return ''.join(data, '08b')\n else:\n raise TypeError('Type not supported.')\n <function token>\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n\n\nclass LSB:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n\n def to_base64(self, secret_info):\n encoded_string = base64.b64encode(self.secret)\n encoded_file_format = base64.b64encode(secret_info[1].encode('utf-8'))\n encoded_name = base64.b64encode(secret_info[2].encode('utf-8'))\n criteria = '#####'.encode('utf8')\n result = (encoded_string + criteria + encoded_file_format +\n criteria + encoded_name + criteria)\n result = ''.join(self.to_binary(result))\n return result\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Img_Encode(LSB):\n\n def __init__(self, cover, secret, bits):\n print('[*] Encoding... ')\n self.cover = self.get_cover_image(cover, 'cover')\n cover_info = self.get_object_info(cover, 'cover')\n cover_size = cover_info[0]\n self.outfile = 'static\\\\encode_output\\\\' + cover_info[2\n ] + '_copy' + cover_info[1]\n self.secret = self.get_secret_object(secret, 'secret')\n secret_info = self.get_object_info(secret, 'secret')\n secret_size = secret_info[0]\n bit_pos = bits\n self.encode_to_image(secret_size, secret_info, cover_size, bit_pos)\n <function token>\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Img_Encode(LSB):\n <function token>\n <function token>\n\n def encode_to_image(self, secret_size, secret_info, cover_size, bit_pos):\n data_index = 0\n print('[*] Maximum bytes to encode: ', cover_size)\n if secret_size > cover_size:\n raise ValueError(\n '[!] Insufficient bytes, need bigger image or less data.')\n binary_secret_data = self.to_base64(secret_info)\n data_len = len(binary_secret_data)\n for row in self.cover:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n list_r = list(r)\n list_g = list(g)\n list_b = list(b)\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_r[bit_pos[i]] = binary_secret_data[data_index]\n pixel[0] = int(''.join(list_r), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_g[bit_pos[i]] = binary_secret_data[data_index]\n pixel[1] = int(''.join(list_g), 2)\n data_index += 1\n else:\n break\n for i in range(len(bit_pos)):\n if data_index < data_len:\n list_b[bit_pos[i]] = binary_secret_data[data_index]\n pixel[2] = int(''.join(list_b), 2)\n data_index += 1\n else:\n break\n self.save_cover_image(self.cover, self.outfile)\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n\n\nclass Img_Encode(LSB):\n <function token>\n <function token>\n <function token>\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Img_Decode(LSB):\n\n def __init__(self, steg, bits):\n print('[*] Decoding... ')\n self.steg = self.get_cover_image(steg, 'steg')\n bit_pos = bits\n self.file_format = self.decode_from_image(bit_pos)\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Img_Decode(LSB):\n <function token>\n\n def __str__(self):\n return str(self.file_format)\n\n def from_base64(self, data):\n decoded_string = self.to_utf8_bytes(data)\n result = decoded_string.split('#####'.encode('utf8'))\n message = base64.b64decode(result[0])\n file_format = base64.b64decode(result[1])\n name = base64.b64decode(result[2])\n return message, file_format, name\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Img_Decode(LSB):\n <function token>\n\n def __str__(self):\n return str(self.file_format)\n <function token>\n\n def decode_from_image(self, bit_pos):\n binary_data = ''\n for row in self.steg:\n for pixel in row:\n r, g, b = self.to_binary(pixel)\n for i in range(len(bit_pos)):\n binary_data += r[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += g[bit_pos[i]]\n for i in range(len(bit_pos)):\n binary_data += b[bit_pos[i]]\n extracted_bin = [binary_data[i:i + 8] for i in range(0, len(\n binary_data), 8)]\n message = self.from_base64(extracted_bin)[0]\n file_format = self.from_base64(extracted_bin)[1].decode('utf-8')\n name = self.from_base64(extracted_bin)[2].decode('utf-8')\n self.write_file(file_format, name, message)\n return name + '_secret' + file_format\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Img_Decode(LSB):\n <function token>\n\n def __str__(self):\n return str(self.file_format)\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n\n\nclass Img_Decode(LSB):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n",
"<import token>\n<class token>\n<class token>\n<class token>\n<function token>\n<code token>\n"
] | false |
99,972 | 260c40c7fd9ebff889f88d9a3f6e3c6d183d4cb4 | from bootstrap import db
from um import models
# Contact 1
u1 = models.Contact('Contact 1', 'user1@example.com')
db.session.add(u1)
db.session.commit()
# Contact 1 properties
p = models.Property('first_name', 'Peter', u1.id)
p1 = models.Property('last_name', 'Wanowan', u1.id)
p2 = models.Property('email', 'peter.wanowan@example.com', u1.id)
p3 = models.Property('fon', '+1 555 101', u1.id)
db.session.add(p)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.commit()
# Contact 2
u2 = models.Contact('Contact 2', 'user2@example.com')
db.session.add(u2)
db.session.commit()
# Contact 2 properties
p = models.Property('first_name', 'John', u2.id)
p1 = models.Property('last_name', 'Twootwo', u2.id)
p2 = models.Property('email', 'j.twootwo@example.com', u2.id)
p3 = models.Property('fon', '+1 555 202', u2.id)
db.session.add(p)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.commit()
# Contact 3
u3 = models.Contact('Contact 3', 'user3@example.com')
db.session.add(u3)
db.session.commit()
# Contact 3 properties
p = models.Property('first_name', 'Steve', u3.id)
p1 = models.Property('last_name', 'Thriotree', u3.id)
p2 = models.Property('email', 'steven.thriotree@example.com', u3.id)
p3 = models.Property('fon', '+1 555 303', u3.id)
db.session.add(p)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.commit()
# Contacts attributes
a = models.Attribute('age')
a1 = models.Attribute('group')
a2 = models.Attribute('department')
u1.attributes.append(a)
u1.attributes.append(a1)
u1.attributes.append(a2)
u2.attributes.append(a)
u2.attributes.append(a2)
u3.attributes.append(a1)
db.session.add(u1)
db.session.add(u2)
db.session.add(u3)
db.session.commit() | [
"from bootstrap import db\nfrom um import models\n\n# Contact 1\nu1 = models.Contact('Contact 1', 'user1@example.com')\ndb.session.add(u1)\ndb.session.commit()\n\n# Contact 1 properties\np = models.Property('first_name', 'Peter', u1.id)\np1 = models.Property('last_name', 'Wanowan', u1.id)\np2 = models.Property('email', 'peter.wanowan@example.com', u1.id)\np3 = models.Property('fon', '+1 555 101', u1.id)\n\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n\n# Contact 2\nu2 = models.Contact('Contact 2', 'user2@example.com')\ndb.session.add(u2)\ndb.session.commit()\n\n# Contact 2 properties\np = models.Property('first_name', 'John', u2.id)\np1 = models.Property('last_name', 'Twootwo', u2.id)\np2 = models.Property('email', 'j.twootwo@example.com', u2.id)\np3 = models.Property('fon', '+1 555 202', u2.id)\n\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n\n# Contact 3\nu3 = models.Contact('Contact 3', 'user3@example.com')\ndb.session.add(u3)\ndb.session.commit()\n\n# Contact 3 properties\np = models.Property('first_name', 'Steve', u3.id)\np1 = models.Property('last_name', 'Thriotree', u3.id)\np2 = models.Property('email', 'steven.thriotree@example.com', u3.id)\np3 = models.Property('fon', '+1 555 303', u3.id)\n\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n\n# Contacts attributes\na = models.Attribute('age')\na1 = models.Attribute('group')\na2 = models.Attribute('department')\n\nu1.attributes.append(a)\nu1.attributes.append(a1)\nu1.attributes.append(a2)\n\nu2.attributes.append(a)\nu2.attributes.append(a2)\n\nu3.attributes.append(a1)\n\ndb.session.add(u1)\ndb.session.add(u2)\ndb.session.add(u3)\ndb.session.commit()",
"from bootstrap import db\nfrom um import models\nu1 = models.Contact('Contact 1', 'user1@example.com')\ndb.session.add(u1)\ndb.session.commit()\np = models.Property('first_name', 'Peter', u1.id)\np1 = models.Property('last_name', 'Wanowan', u1.id)\np2 = models.Property('email', 'peter.wanowan@example.com', u1.id)\np3 = models.Property('fon', '+1 555 101', u1.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\nu2 = models.Contact('Contact 2', 'user2@example.com')\ndb.session.add(u2)\ndb.session.commit()\np = models.Property('first_name', 'John', u2.id)\np1 = models.Property('last_name', 'Twootwo', u2.id)\np2 = models.Property('email', 'j.twootwo@example.com', u2.id)\np3 = models.Property('fon', '+1 555 202', u2.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\nu3 = models.Contact('Contact 3', 'user3@example.com')\ndb.session.add(u3)\ndb.session.commit()\np = models.Property('first_name', 'Steve', u3.id)\np1 = models.Property('last_name', 'Thriotree', u3.id)\np2 = models.Property('email', 'steven.thriotree@example.com', u3.id)\np3 = models.Property('fon', '+1 555 303', u3.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\na = models.Attribute('age')\na1 = models.Attribute('group')\na2 = models.Attribute('department')\nu1.attributes.append(a)\nu1.attributes.append(a1)\nu1.attributes.append(a2)\nu2.attributes.append(a)\nu2.attributes.append(a2)\nu3.attributes.append(a1)\ndb.session.add(u1)\ndb.session.add(u2)\ndb.session.add(u3)\ndb.session.commit()\n",
"<import token>\nu1 = models.Contact('Contact 1', 'user1@example.com')\ndb.session.add(u1)\ndb.session.commit()\np = models.Property('first_name', 'Peter', u1.id)\np1 = models.Property('last_name', 'Wanowan', u1.id)\np2 = models.Property('email', 'peter.wanowan@example.com', u1.id)\np3 = models.Property('fon', '+1 555 101', u1.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\nu2 = models.Contact('Contact 2', 'user2@example.com')\ndb.session.add(u2)\ndb.session.commit()\np = models.Property('first_name', 'John', u2.id)\np1 = models.Property('last_name', 'Twootwo', u2.id)\np2 = models.Property('email', 'j.twootwo@example.com', u2.id)\np3 = models.Property('fon', '+1 555 202', u2.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\nu3 = models.Contact('Contact 3', 'user3@example.com')\ndb.session.add(u3)\ndb.session.commit()\np = models.Property('first_name', 'Steve', u3.id)\np1 = models.Property('last_name', 'Thriotree', u3.id)\np2 = models.Property('email', 'steven.thriotree@example.com', u3.id)\np3 = models.Property('fon', '+1 555 303', u3.id)\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\na = models.Attribute('age')\na1 = models.Attribute('group')\na2 = models.Attribute('department')\nu1.attributes.append(a)\nu1.attributes.append(a1)\nu1.attributes.append(a2)\nu2.attributes.append(a)\nu2.attributes.append(a2)\nu3.attributes.append(a1)\ndb.session.add(u1)\ndb.session.add(u2)\ndb.session.add(u3)\ndb.session.commit()\n",
"<import token>\n<assignment token>\ndb.session.add(u1)\ndb.session.commit()\n<assignment token>\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n<assignment token>\ndb.session.add(u2)\ndb.session.commit()\n<assignment token>\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n<assignment token>\ndb.session.add(u3)\ndb.session.commit()\n<assignment token>\ndb.session.add(p)\ndb.session.add(p1)\ndb.session.add(p2)\ndb.session.add(p3)\ndb.session.commit()\n<assignment token>\nu1.attributes.append(a)\nu1.attributes.append(a1)\nu1.attributes.append(a2)\nu2.attributes.append(a)\nu2.attributes.append(a2)\nu3.attributes.append(a1)\ndb.session.add(u1)\ndb.session.add(u2)\ndb.session.add(u3)\ndb.session.commit()\n",
"<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment 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,973 | 8cdf2354dead12b292b47a12663748c0c1c09351 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ['NameSpace', 'ns']
from .utils import UnicodeDict
class NameSpace(dict):
@classmethod
def instance(cls):
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError:
raise AttributeError
ns = NameSpace.instance()
#defaults
ns.storage = NameSpace()
ns.storage.errors = [] # error list storage
ns.storage.status = NameSpace() # status of the blog info
ns.storage.functions = NameSpace() # functions storage for writer
ns.storage.root = None
ns.storage.posts = []
ns.storage.files = []
ns.context = UnicodeDict() # [context] in config file
# [site] in config file
ns.site = NameSpace({
'postdir': 'content',
'deploydir': 'deploy',
'staticdir': 'static',
'static_prefix': '/static',
'template': '_templates',
'format': 'year',
'slug': 'html',
'syntax': 'class',
'autoescape': 'false',
'feed_count': 10,
'perpage': 30,
'index': 'index.html',
'feed_template': 'feed.xml',
'archive_template': 'archive.html',
'tagcloud_template': 'tagcloud.html',
})
# [readers] in config file
ns.readers = NameSpace({
'mkd': 'liquidluck.readers.mkd.MarkdownReader',
'rst': 'liquidluck.readers.rst.RstReader',
})
# [writers] in config file
ns.writers = NameSpace({
'static': 'liquidluck.writers.default.StaticWriter',
'post': 'liquidluck.writers.default.PostWriter',
'file': 'liquidluck.writers.default.FileWriter',
'archive': 'liquidluck.writers.default.IndexWriter',
'year': 'liquidluck.writers.default.YearWriter',
'tag': 'liquidluck.writers.default.TagWriter',
})
# [filters] in config file
ns.filters = NameSpace({
'restructuredtext': 'liquidluck.readers.rst.restructuredtext',
'markdown': 'liquidluck.readers.mkd.markdown',
'xmldatetime': 'liquidluck.filters.xmldatetime',
})
# other sections in config file
# ns.sections[section] = sectionData
ns.sections = NameSpace()
# data in sections
# section name: xxx_data
ns.data = NameSpace()
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__all__ = ['NameSpace', 'ns']\n\nfrom .utils import UnicodeDict\n\n\nclass NameSpace(dict):\n @classmethod\n def instance(cls):\n if not hasattr(cls, \"_instance\"):\n cls._instance = cls()\n return cls._instance\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\nns = NameSpace.instance()\n\n\n#defaults\nns.storage = NameSpace()\nns.storage.errors = [] # error list storage\nns.storage.status = NameSpace() # status of the blog info\nns.storage.functions = NameSpace() # functions storage for writer\nns.storage.root = None\nns.storage.posts = []\nns.storage.files = []\n\n\nns.context = UnicodeDict() # [context] in config file\n\n# [site] in config file\nns.site = NameSpace({\n 'postdir': 'content',\n 'deploydir': 'deploy',\n 'staticdir': 'static',\n 'static_prefix': '/static',\n 'template': '_templates',\n 'format': 'year',\n 'slug': 'html',\n 'syntax': 'class',\n 'autoescape': 'false',\n 'feed_count': 10,\n 'perpage': 30,\n 'index': 'index.html',\n 'feed_template': 'feed.xml',\n 'archive_template': 'archive.html',\n 'tagcloud_template': 'tagcloud.html',\n})\n# [readers] in config file\nns.readers = NameSpace({\n 'mkd': 'liquidluck.readers.mkd.MarkdownReader',\n 'rst': 'liquidluck.readers.rst.RstReader',\n})\n# [writers] in config file\nns.writers = NameSpace({\n 'static': 'liquidluck.writers.default.StaticWriter',\n 'post': 'liquidluck.writers.default.PostWriter',\n 'file': 'liquidluck.writers.default.FileWriter',\n 'archive': 'liquidluck.writers.default.IndexWriter',\n 'year': 'liquidluck.writers.default.YearWriter',\n 'tag': 'liquidluck.writers.default.TagWriter',\n})\n# [filters] in config file\nns.filters = NameSpace({\n 'restructuredtext': 'liquidluck.readers.rst.restructuredtext',\n 'markdown': 'liquidluck.readers.mkd.markdown',\n 'xmldatetime': 'liquidluck.filters.xmldatetime',\n})\n# other sections in config file\n# ns.sections[section] = sectionData\nns.sections = NameSpace()\n\n# data in sections\n# section name: xxx_data\nns.data = NameSpace()\n",
"__all__ = ['NameSpace', 'ns']\nfrom .utils import UnicodeDict\n\n\nclass NameSpace(dict):\n\n @classmethod\n def instance(cls):\n if not hasattr(cls, '_instance'):\n cls._instance = cls()\n return cls._instance\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\n\nns = NameSpace.instance()\nns.storage = NameSpace()\nns.storage.errors = []\nns.storage.status = NameSpace()\nns.storage.functions = NameSpace()\nns.storage.root = None\nns.storage.posts = []\nns.storage.files = []\nns.context = UnicodeDict()\nns.site = NameSpace({'postdir': 'content', 'deploydir': 'deploy',\n 'staticdir': 'static', 'static_prefix': '/static', 'template':\n '_templates', 'format': 'year', 'slug': 'html', 'syntax': 'class',\n 'autoescape': 'false', 'feed_count': 10, 'perpage': 30, 'index':\n 'index.html', 'feed_template': 'feed.xml', 'archive_template':\n 'archive.html', 'tagcloud_template': 'tagcloud.html'})\nns.readers = NameSpace({'mkd': 'liquidluck.readers.mkd.MarkdownReader',\n 'rst': 'liquidluck.readers.rst.RstReader'})\nns.writers = NameSpace({'static': 'liquidluck.writers.default.StaticWriter',\n 'post': 'liquidluck.writers.default.PostWriter', 'file':\n 'liquidluck.writers.default.FileWriter', 'archive':\n 'liquidluck.writers.default.IndexWriter', 'year':\n 'liquidluck.writers.default.YearWriter', 'tag':\n 'liquidluck.writers.default.TagWriter'})\nns.filters = NameSpace({'restructuredtext':\n 'liquidluck.readers.rst.restructuredtext', 'markdown':\n 'liquidluck.readers.mkd.markdown', 'xmldatetime':\n 'liquidluck.filters.xmldatetime'})\nns.sections = NameSpace()\nns.data = NameSpace()\n",
"__all__ = ['NameSpace', 'ns']\n<import token>\n\n\nclass NameSpace(dict):\n\n @classmethod\n def instance(cls):\n if not hasattr(cls, '_instance'):\n cls._instance = cls()\n return cls._instance\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\n\nns = NameSpace.instance()\nns.storage = NameSpace()\nns.storage.errors = []\nns.storage.status = NameSpace()\nns.storage.functions = NameSpace()\nns.storage.root = None\nns.storage.posts = []\nns.storage.files = []\nns.context = UnicodeDict()\nns.site = NameSpace({'postdir': 'content', 'deploydir': 'deploy',\n 'staticdir': 'static', 'static_prefix': '/static', 'template':\n '_templates', 'format': 'year', 'slug': 'html', 'syntax': 'class',\n 'autoescape': 'false', 'feed_count': 10, 'perpage': 30, 'index':\n 'index.html', 'feed_template': 'feed.xml', 'archive_template':\n 'archive.html', 'tagcloud_template': 'tagcloud.html'})\nns.readers = NameSpace({'mkd': 'liquidluck.readers.mkd.MarkdownReader',\n 'rst': 'liquidluck.readers.rst.RstReader'})\nns.writers = NameSpace({'static': 'liquidluck.writers.default.StaticWriter',\n 'post': 'liquidluck.writers.default.PostWriter', 'file':\n 'liquidluck.writers.default.FileWriter', 'archive':\n 'liquidluck.writers.default.IndexWriter', 'year':\n 'liquidluck.writers.default.YearWriter', 'tag':\n 'liquidluck.writers.default.TagWriter'})\nns.filters = NameSpace({'restructuredtext':\n 'liquidluck.readers.rst.restructuredtext', 'markdown':\n 'liquidluck.readers.mkd.markdown', 'xmldatetime':\n 'liquidluck.filters.xmldatetime'})\nns.sections = NameSpace()\nns.data = NameSpace()\n",
"<assignment token>\n<import token>\n\n\nclass NameSpace(dict):\n\n @classmethod\n def instance(cls):\n if not hasattr(cls, '_instance'):\n cls._instance = cls()\n return cls._instance\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\n\n<assignment token>\n",
"<assignment token>\n<import token>\n\n\nclass NameSpace(dict):\n <function token>\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\n\n<assignment token>\n",
"<assignment token>\n<import token>\n\n\nclass NameSpace(dict):\n <function token>\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n <function token>\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError:\n raise AttributeError\n\n\n<assignment token>\n",
"<assignment token>\n<import token>\n\n\nclass NameSpace(dict):\n <function token>\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError\n <function token>\n <function token>\n\n\n<assignment token>\n",
"<assignment token>\n<import token>\n\n\nclass NameSpace(dict):\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n",
"<assignment token>\n<import token>\n<class token>\n<assignment token>\n"
] | false |
99,974 | 758f6328f197e4fbcbf52ac5c91ed68c3e8fc112 | # class first_class:
# age = 10
# name = 'gilbert'
# p1 = first_class()
# print(p1.name)
# class meth:
# def __init__(self, name='gilbert', age=25):
# self.name = name
# self.age = age
# def get_name(self):
# print(f'hello {self.name} your age is {self.age}')
# p1 = meth('henry', 30)
# print(p1.get_name())
# p1.age = 50
# print(print(p1.get_name()))
# class meth2(meth):
# pass
# p2 = meth2('ben', 59)
# print(p2.get_name())
print(__name__, ' dunder')
class Parent:
def __init__(self, name = 'dafaultName', age = 'none supplied'):
self.name = name
self.age = age
def get_info(self):
print(f'my name is {self.name} with age {self.age}')
if __name__ == '__main__':
p1 = Parent('Gilbert', 4090)
print(p1.name)
print(p1.get_info())
class Child(Parent):
fat = True
def __init__(self, name = 'none supplied', age = 'second noe availabele', birth_day = 'none supplied'):
super().__init__(name, age)
self.birth_day = birth_day
def get_info(self):
print('nothing for you')
if __name__ == '__main__':
p2 = Child('Angel', birth_day = '2nd of june')
print(p2.fat)
| [
"# class first_class:\n# age = 10\n# name = 'gilbert'\n# p1 = first_class()\n# print(p1.name)\n\n# class meth:\n# def __init__(self, name='gilbert', age=25):\n# self.name = name\n# self.age = age\n \n# def get_name(self):\n# print(f'hello {self.name} your age is {self.age}')\n\n# p1 = meth('henry', 30)\n# print(p1.get_name())\n# p1.age = 50\n# print(print(p1.get_name()))\n# class meth2(meth):\n# pass\n# p2 = meth2('ben', 59)\n\n# print(p2.get_name())\nprint(__name__, ' dunder')\nclass Parent:\n def __init__(self, name = 'dafaultName', age = 'none supplied'):\n self.name = name\n self.age = age\n \n def get_info(self):\n print(f'my name is {self.name} with age {self.age}')\n\nif __name__ == '__main__':\n p1 = Parent('Gilbert', 4090)\n print(p1.name)\n print(p1.get_info())\n\nclass Child(Parent):\n fat = True\n def __init__(self, name = 'none supplied', age = 'second noe availabele', birth_day = 'none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n def get_info(self):\n print('nothing for you')\nif __name__ == '__main__':\n p2 = Child('Angel', birth_day = '2nd of june')\n print(p2.fat)\n",
"print(__name__, ' dunder')\n\n\nclass Parent:\n\n def __init__(self, name='dafaultName', age='none supplied'):\n self.name = name\n self.age = age\n\n def get_info(self):\n print(f'my name is {self.name} with age {self.age}')\n\n\nif __name__ == '__main__':\n p1 = Parent('Gilbert', 4090)\n print(p1.name)\n print(p1.get_info())\n\n\nclass Child(Parent):\n fat = True\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\nif __name__ == '__main__':\n p2 = Child('Angel', birth_day='2nd of june')\n print(p2.fat)\n",
"<code token>\n\n\nclass Parent:\n\n def __init__(self, name='dafaultName', age='none supplied'):\n self.name = name\n self.age = age\n\n def get_info(self):\n print(f'my name is {self.name} with age {self.age}')\n\n\n<code token>\n\n\nclass Child(Parent):\n fat = True\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n\n\nclass Parent:\n\n def __init__(self, name='dafaultName', age='none supplied'):\n self.name = name\n self.age = age\n <function token>\n\n\n<code token>\n\n\nclass Child(Parent):\n fat = True\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n\n\nclass Parent:\n <function token>\n <function token>\n\n\n<code token>\n\n\nclass Child(Parent):\n fat = True\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n<class token>\n<code token>\n\n\nclass Child(Parent):\n fat = True\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n<class token>\n<code token>\n\n\nclass Child(Parent):\n <assignment token>\n\n def __init__(self, name='none supplied', age='second noe availabele',\n birth_day='none supplied'):\n super().__init__(name, age)\n self.birth_day = birth_day\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n<class token>\n<code token>\n\n\nclass Child(Parent):\n <assignment token>\n <function token>\n\n def get_info(self):\n print('nothing for you')\n\n\n<code token>\n",
"<code token>\n<class token>\n<code token>\n\n\nclass Child(Parent):\n <assignment token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<code token>\n<class token>\n<code token>\n<class token>\n<code token>\n"
] | false |
99,975 | 83e2fe37bdc51475c914af611b671b6995efe890 | # 手机号规则
REGEX_MOBILE = "^1[3578]\d{9}$|^147\d{8}$|^176\d{8}$"
# 代拿费
AGENCY_FEE = 2.0
#退货服务费
SERVER_FEE = 2.0
# 首重件数 2
FIRST_WEIGHT = 2
# 发件人姓名
sender_name = ""
# 发件人手机
sender_phone = ""
# 发件人地址
sender_address = ""
| [
"# 手机号规则\nREGEX_MOBILE = \"^1[3578]\\d{9}$|^147\\d{8}$|^176\\d{8}$\"\n\n# 代拿费\nAGENCY_FEE = 2.0\n#退货服务费\nSERVER_FEE = 2.0\n\n# 首重件数 2\nFIRST_WEIGHT = 2\n\n# 发件人姓名\nsender_name = \"\"\n\n# 发件人手机\nsender_phone = \"\"\n\n# 发件人地址\n\nsender_address = \"\"\n",
"REGEX_MOBILE = '^1[3578]\\\\d{9}$|^147\\\\d{8}$|^176\\\\d{8}$'\nAGENCY_FEE = 2.0\nSERVER_FEE = 2.0\nFIRST_WEIGHT = 2\nsender_name = ''\nsender_phone = ''\nsender_address = ''\n",
"<assignment token>\n"
] | false |
99,976 | afab7a1a1d16c3af1bbdb8cf3a9e4c9c91f95cdb | #!/usr/bin/env python
import socket
import struct
class KongsbergEM:
def __init__(self,port=16112):
self.insock = socket.socket(type=socket.SOCK_DGRAM)
self.insock.bind(('',port))
def getPacket(self):
data,addr = self.insock.recvfrom(10000)
start,dgram_type = struct.unpack('<BB',data[:2])
if start == 2: #start identifier
if dgram_type == 80:
#print 'position datagram'
date,time = struct.unpack('<II',data[4:12])
time = time/1000.0 # ms to s
latitude,longitude = struct.unpack('<ii',data[16:24])
latitude/=20000000.0
longitude/=10000000.0
heading, = struct.unpack('<H',data[30:32])
heading/=100.0
return {'type':'position', 'date':date, 'time_of_day':time, 'latitude':latitude, 'longitude':longitude, 'heading':heading}
if dgram_type == 88:
date,time = struct.unpack('<II',data[4:12])
time = time/1000.0 # ms to s
#print 'date:',date,'time of day (s):',time
beam_count,valid_count = struct.unpack('<HH',data[24:28])
#print 'beam count:',beam_count,'valid count:',valid_count
beams = []
for n in range(beam_count):
# From em_datagram_formats.pdf, P.125
#The coordinates are given in the Vessel Coordinate System, where x is forward, y is starboard and z is downward.
z,y,x,qf,detect_info = struct.unpack('<fff2xBxB',data[36+20*n:36+20*n+17])
if detect_info < 16:
beams.append((x,y,z))
#print beams
return {'type':'xyz', 'date':date, 'time_of_day':time, 'beams':beams}
if __name__ == '__main__':
em = KongsbergEM()
count = 0
while count < 10:
count += 1
print em.getPacket()
| [
"#!/usr/bin/env python\n\nimport socket\nimport struct\n\nclass KongsbergEM:\n def __init__(self,port=16112):\n self.insock = socket.socket(type=socket.SOCK_DGRAM)\n self.insock.bind(('',port))\n\n def getPacket(self):\n data,addr = self.insock.recvfrom(10000)\n start,dgram_type = struct.unpack('<BB',data[:2])\n if start == 2: #start identifier\n if dgram_type == 80:\n #print 'position datagram'\n date,time = struct.unpack('<II',data[4:12])\n time = time/1000.0 # ms to s\n latitude,longitude = struct.unpack('<ii',data[16:24])\n latitude/=20000000.0\n longitude/=10000000.0\n heading, = struct.unpack('<H',data[30:32])\n heading/=100.0\n return {'type':'position', 'date':date, 'time_of_day':time, 'latitude':latitude, 'longitude':longitude, 'heading':heading}\n if dgram_type == 88:\n date,time = struct.unpack('<II',data[4:12])\n time = time/1000.0 # ms to s\n #print 'date:',date,'time of day (s):',time\n beam_count,valid_count = struct.unpack('<HH',data[24:28])\n #print 'beam count:',beam_count,'valid count:',valid_count\n beams = []\n for n in range(beam_count):\n # From em_datagram_formats.pdf, P.125\n #The coordinates are given in the Vessel Coordinate System, where x is forward, y is starboard and z is downward.\n z,y,x,qf,detect_info = struct.unpack('<fff2xBxB',data[36+20*n:36+20*n+17])\n if detect_info < 16:\n beams.append((x,y,z))\n #print beams\n return {'type':'xyz', 'date':date, 'time_of_day':time, 'beams':beams}\n \nif __name__ == '__main__':\n em = KongsbergEM()\n count = 0\n while count < 10:\n count += 1\n print em.getPacket()\n\n\n"
] | true |
99,977 | 3c08cca562db78861ec754eb2b7caae4c8ed1eed | import os
from google.cloud import storage
from google.cloud.storage import Bucket
def connect_to_bucket(bucket_name: str) -> Bucket:
"""
@param bucket_name: name of the bucket of the save location
@return: bucket object provided by GCP
"""
storage_client = storage.Client(project='your-project-name')
bucket = storage.Bucket(client=storage_client, name=bucket_name)
return bucket
def get_available_folder(foldername: str, bucket_name: str, delimiter=None) -> str:
"""
Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.
This can be used to list all blobs in a "folder", e.g. "public/".
The delimiter argument can be used to restrict the results to only the
"files" in the given "folder". Without the delimiter, the entire tree under
the prefix is returned. For example, given these blobs:
a/1.txt
a/b/2.txt
If you specify prefix ='a/', without a delimiter, you'll get back:
a/1.txt
a/b/2.txt
However, if you specify prefix='a/' and delimiter='/', you'll get back:
a/1.txt
"""
bucket = connect_to_bucket(bucket_name)
# define prefix (bucket folder name) which is used by notifier
prefix = "model_output/" + foldername
available_folder = None
# this function checks if the last part of the name has a number, in case the input is some config file,
# and adds _0 if not if there is already a folder with that name and the last part is not a number,
# the same logic applies Note: Client.list_blobs requires at least package version 1.17.0.
while not available_folder:
# if this works, the folder exists
blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)
blobs = list(blobs)
if len(blobs) > 0:
# split in parts and try to increment, if this fails add "_0" to the name
m = foldername.split("_")
try:
m[-1] = int(m[-1]) + 1
m[-1] = str(m[-1])
foldername = "_".join(m)
prefix = "model_output/" + foldername
except:
foldername = "_".join(m)
foldername += "_0"
prefix = "model_output/" + foldername
continue
else:
# check if last part is a number, if not add _0
try:
int(prefix.split("_")[-1])
available_folder = prefix
except:
available_folder = prefix + "_0"
return available_folder
def load_checkpoint(cfg, args):
"""
Loads specified checkpoint from specified bucket.
"""
checkpoint_iteration = args.checkpoint
bucket = connect_to_bucket(args.bucket)
# load actual checkpoint
if not os.path.isdir(cfg.OUTPUT_DIR):
os.mkdir(cfg.OUTPUT_DIR)
blob = bucket.blob(cfg.OUTPUT_DIR + "/model_" + str(checkpoint_iteration) + ".pth")
blob.download_to_filename(cfg.OUTPUT_DIR + "/model_" + str(checkpoint_iteration) + ".pth")
if args.resume:
# also write last checkpoint file for when --resume statement, model gets checkpoint name from this file
with open(cfg.OUTPUT_DIR + "/last_checkpoint", "w") as file:
file.write("model_" + str(checkpoint_iteration) + ".pth")
# return statement not clean, but useful for inference code
return checkpoint_iteration, bucket
| [
"import os\n\nfrom google.cloud import storage\nfrom google.cloud.storage import Bucket\n\n\ndef connect_to_bucket(bucket_name: str) -> Bucket:\n \"\"\"\n @param bucket_name: name of the bucket of the save location\n @return: bucket object provided by GCP\n \"\"\"\n storage_client = storage.Client(project='your-project-name')\n bucket = storage.Bucket(client=storage_client, name=bucket_name)\n\n return bucket\n\n\ndef get_available_folder(foldername: str, bucket_name: str, delimiter=None) -> str:\n \"\"\"\n Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.\n\n This can be used to list all blobs in a \"folder\", e.g. \"public/\".\n\n The delimiter argument can be used to restrict the results to only the\n \"files\" in the given \"folder\". Without the delimiter, the entire tree under\n the prefix is returned. For example, given these blobs:\n\n a/1.txt\n a/b/2.txt\n\n If you specify prefix ='a/', without a delimiter, you'll get back:\n\n a/1.txt\n a/b/2.txt\n\n However, if you specify prefix='a/' and delimiter='/', you'll get back:\n\n a/1.txt\n \"\"\"\n\n bucket = connect_to_bucket(bucket_name)\n\n # define prefix (bucket folder name) which is used by notifier\n prefix = \"model_output/\" + foldername\n available_folder = None\n\n # this function checks if the last part of the name has a number, in case the input is some config file,\n # and adds _0 if not if there is already a folder with that name and the last part is not a number,\n # the same logic applies Note: Client.list_blobs requires at least package version 1.17.0.\n while not available_folder:\n # if this works, the folder exists\n blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)\n blobs = list(blobs)\n if len(blobs) > 0:\n\n # split in parts and try to increment, if this fails add \"_0\" to the name\n m = foldername.split(\"_\")\n try:\n m[-1] = int(m[-1]) + 1\n m[-1] = str(m[-1])\n foldername = \"_\".join(m)\n prefix = \"model_output/\" + foldername\n except:\n foldername = \"_\".join(m)\n foldername += \"_0\"\n prefix = \"model_output/\" + foldername\n continue\n else:\n # check if last part is a number, if not add _0\n try:\n int(prefix.split(\"_\")[-1])\n available_folder = prefix\n except:\n available_folder = prefix + \"_0\"\n\n return available_folder\n\n\ndef load_checkpoint(cfg, args):\n \"\"\"\n Loads specified checkpoint from specified bucket.\n \"\"\"\n checkpoint_iteration = args.checkpoint\n bucket = connect_to_bucket(args.bucket)\n # load actual checkpoint\n if not os.path.isdir(cfg.OUTPUT_DIR):\n os.mkdir(cfg.OUTPUT_DIR)\n blob = bucket.blob(cfg.OUTPUT_DIR + \"/model_\" + str(checkpoint_iteration) + \".pth\")\n blob.download_to_filename(cfg.OUTPUT_DIR + \"/model_\" + str(checkpoint_iteration) + \".pth\")\n if args.resume:\n # also write last checkpoint file for when --resume statement, model gets checkpoint name from this file\n with open(cfg.OUTPUT_DIR + \"/last_checkpoint\", \"w\") as file:\n file.write(\"model_\" + str(checkpoint_iteration) + \".pth\")\n # return statement not clean, but useful for inference code\n return checkpoint_iteration, bucket\n\n\n\n",
"import os\nfrom google.cloud import storage\nfrom google.cloud.storage import Bucket\n\n\ndef connect_to_bucket(bucket_name: str) ->Bucket:\n \"\"\"\n @param bucket_name: name of the bucket of the save location\n @return: bucket object provided by GCP\n \"\"\"\n storage_client = storage.Client(project='your-project-name')\n bucket = storage.Bucket(client=storage_client, name=bucket_name)\n return bucket\n\n\ndef get_available_folder(foldername: str, bucket_name: str, delimiter=None\n ) ->str:\n \"\"\"\n Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.\n\n This can be used to list all blobs in a \"folder\", e.g. \"public/\".\n\n The delimiter argument can be used to restrict the results to only the\n \"files\" in the given \"folder\". Without the delimiter, the entire tree under\n the prefix is returned. For example, given these blobs:\n\n a/1.txt\n a/b/2.txt\n\n If you specify prefix ='a/', without a delimiter, you'll get back:\n\n a/1.txt\n a/b/2.txt\n\n However, if you specify prefix='a/' and delimiter='/', you'll get back:\n\n a/1.txt\n \"\"\"\n bucket = connect_to_bucket(bucket_name)\n prefix = 'model_output/' + foldername\n available_folder = None\n while not available_folder:\n blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)\n blobs = list(blobs)\n if len(blobs) > 0:\n m = foldername.split('_')\n try:\n m[-1] = int(m[-1]) + 1\n m[-1] = str(m[-1])\n foldername = '_'.join(m)\n prefix = 'model_output/' + foldername\n except:\n foldername = '_'.join(m)\n foldername += '_0'\n prefix = 'model_output/' + foldername\n continue\n else:\n try:\n int(prefix.split('_')[-1])\n available_folder = prefix\n except:\n available_folder = prefix + '_0'\n return available_folder\n\n\ndef load_checkpoint(cfg, args):\n \"\"\"\n Loads specified checkpoint from specified bucket.\n \"\"\"\n checkpoint_iteration = args.checkpoint\n bucket = connect_to_bucket(args.bucket)\n if not os.path.isdir(cfg.OUTPUT_DIR):\n os.mkdir(cfg.OUTPUT_DIR)\n blob = bucket.blob(cfg.OUTPUT_DIR + '/model_' + str(\n checkpoint_iteration) + '.pth')\n blob.download_to_filename(cfg.OUTPUT_DIR + '/model_' + str(\n checkpoint_iteration) + '.pth')\n if args.resume:\n with open(cfg.OUTPUT_DIR + '/last_checkpoint', 'w') as file:\n file.write('model_' + str(checkpoint_iteration) + '.pth')\n return checkpoint_iteration, bucket\n",
"<import token>\n\n\ndef connect_to_bucket(bucket_name: str) ->Bucket:\n \"\"\"\n @param bucket_name: name of the bucket of the save location\n @return: bucket object provided by GCP\n \"\"\"\n storage_client = storage.Client(project='your-project-name')\n bucket = storage.Bucket(client=storage_client, name=bucket_name)\n return bucket\n\n\ndef get_available_folder(foldername: str, bucket_name: str, delimiter=None\n ) ->str:\n \"\"\"\n Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.\n\n This can be used to list all blobs in a \"folder\", e.g. \"public/\".\n\n The delimiter argument can be used to restrict the results to only the\n \"files\" in the given \"folder\". Without the delimiter, the entire tree under\n the prefix is returned. For example, given these blobs:\n\n a/1.txt\n a/b/2.txt\n\n If you specify prefix ='a/', without a delimiter, you'll get back:\n\n a/1.txt\n a/b/2.txt\n\n However, if you specify prefix='a/' and delimiter='/', you'll get back:\n\n a/1.txt\n \"\"\"\n bucket = connect_to_bucket(bucket_name)\n prefix = 'model_output/' + foldername\n available_folder = None\n while not available_folder:\n blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)\n blobs = list(blobs)\n if len(blobs) > 0:\n m = foldername.split('_')\n try:\n m[-1] = int(m[-1]) + 1\n m[-1] = str(m[-1])\n foldername = '_'.join(m)\n prefix = 'model_output/' + foldername\n except:\n foldername = '_'.join(m)\n foldername += '_0'\n prefix = 'model_output/' + foldername\n continue\n else:\n try:\n int(prefix.split('_')[-1])\n available_folder = prefix\n except:\n available_folder = prefix + '_0'\n return available_folder\n\n\ndef load_checkpoint(cfg, args):\n \"\"\"\n Loads specified checkpoint from specified bucket.\n \"\"\"\n checkpoint_iteration = args.checkpoint\n bucket = connect_to_bucket(args.bucket)\n if not os.path.isdir(cfg.OUTPUT_DIR):\n os.mkdir(cfg.OUTPUT_DIR)\n blob = bucket.blob(cfg.OUTPUT_DIR + '/model_' + str(\n checkpoint_iteration) + '.pth')\n blob.download_to_filename(cfg.OUTPUT_DIR + '/model_' + str(\n checkpoint_iteration) + '.pth')\n if args.resume:\n with open(cfg.OUTPUT_DIR + '/last_checkpoint', 'w') as file:\n file.write('model_' + str(checkpoint_iteration) + '.pth')\n return checkpoint_iteration, bucket\n",
"<import token>\n\n\ndef connect_to_bucket(bucket_name: str) ->Bucket:\n \"\"\"\n @param bucket_name: name of the bucket of the save location\n @return: bucket object provided by GCP\n \"\"\"\n storage_client = storage.Client(project='your-project-name')\n bucket = storage.Bucket(client=storage_client, name=bucket_name)\n return bucket\n\n\ndef get_available_folder(foldername: str, bucket_name: str, delimiter=None\n ) ->str:\n \"\"\"\n Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.\n\n This can be used to list all blobs in a \"folder\", e.g. \"public/\".\n\n The delimiter argument can be used to restrict the results to only the\n \"files\" in the given \"folder\". Without the delimiter, the entire tree under\n the prefix is returned. For example, given these blobs:\n\n a/1.txt\n a/b/2.txt\n\n If you specify prefix ='a/', without a delimiter, you'll get back:\n\n a/1.txt\n a/b/2.txt\n\n However, if you specify prefix='a/' and delimiter='/', you'll get back:\n\n a/1.txt\n \"\"\"\n bucket = connect_to_bucket(bucket_name)\n prefix = 'model_output/' + foldername\n available_folder = None\n while not available_folder:\n blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)\n blobs = list(blobs)\n if len(blobs) > 0:\n m = foldername.split('_')\n try:\n m[-1] = int(m[-1]) + 1\n m[-1] = str(m[-1])\n foldername = '_'.join(m)\n prefix = 'model_output/' + foldername\n except:\n foldername = '_'.join(m)\n foldername += '_0'\n prefix = 'model_output/' + foldername\n continue\n else:\n try:\n int(prefix.split('_')[-1])\n available_folder = prefix\n except:\n available_folder = prefix + '_0'\n return available_folder\n\n\n<function token>\n",
"<import token>\n<function token>\n\n\ndef get_available_folder(foldername: str, bucket_name: str, delimiter=None\n ) ->str:\n \"\"\"\n Looks for all the blobs in the bucket that begin with the prefix and returns the available folder.\n\n This can be used to list all blobs in a \"folder\", e.g. \"public/\".\n\n The delimiter argument can be used to restrict the results to only the\n \"files\" in the given \"folder\". Without the delimiter, the entire tree under\n the prefix is returned. For example, given these blobs:\n\n a/1.txt\n a/b/2.txt\n\n If you specify prefix ='a/', without a delimiter, you'll get back:\n\n a/1.txt\n a/b/2.txt\n\n However, if you specify prefix='a/' and delimiter='/', you'll get back:\n\n a/1.txt\n \"\"\"\n bucket = connect_to_bucket(bucket_name)\n prefix = 'model_output/' + foldername\n available_folder = None\n while not available_folder:\n blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)\n blobs = list(blobs)\n if len(blobs) > 0:\n m = foldername.split('_')\n try:\n m[-1] = int(m[-1]) + 1\n m[-1] = str(m[-1])\n foldername = '_'.join(m)\n prefix = 'model_output/' + foldername\n except:\n foldername = '_'.join(m)\n foldername += '_0'\n prefix = 'model_output/' + foldername\n continue\n else:\n try:\n int(prefix.split('_')[-1])\n available_folder = prefix\n except:\n available_folder = prefix + '_0'\n return available_folder\n\n\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,978 | 1e8adf8bc9b96b3e32cd95ca0a739125c72dc17e | import unittest
class TestAbs(unittest.TestCase):
def test_abs1(self):
self.assertEqual(abs(-42), 42, "Should be absolute value of a number")
def test_abs2(self):
self.assertEqual(abs(-15), 15, "Should be absolute value of a number")
def test_abs3(self):
self.assertEqual(abs(-8), 8, "Should be absolute value of a number")
def test_abs4(self):
self.assertEqual(abs(-99), 99, "Should be absolute value of a number")
if __name__ == "__main__":
unittest.main()
| [
"import unittest\n\n\nclass TestAbs(unittest.TestCase):\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, \"Should be absolute value of a number\")\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, \"Should be absolute value of a number\")\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, \"Should be absolute value of a number\")\n\n def test_abs4(self):\n self.assertEqual(abs(-99), 99, \"Should be absolute value of a number\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"import unittest\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, 'Should be absolute value of a number')\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, 'Should be absolute value of a number')\n\n def test_abs4(self):\n self.assertEqual(abs(-99), 99, 'Should be absolute value of a number')\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, 'Should be absolute value of a number')\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, 'Should be absolute value of a number')\n\n def test_abs4(self):\n self.assertEqual(abs(-99), 99, 'Should be absolute value of a number')\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, 'Should be absolute value of a number')\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, 'Should be absolute value of a number')\n\n def test_abs4(self):\n self.assertEqual(abs(-99), 99, 'Should be absolute value of a number')\n\n\n<code token>\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, 'Should be absolute value of a number')\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, 'Should be absolute value of a number')\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n <function token>\n\n def test_abs3(self):\n self.assertEqual(abs(-8), 8, 'Should be absolute value of a number')\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\n\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, 'Should be absolute value of a number')\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n",
"<import token>\n\n\nclass TestAbs(unittest.TestCase):\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,979 | 8975603a891221ec894f5616bfb377a4f87fb13a | from flask import Flask
from config import Configuration
from routes import myMainRouter
app = Flask(__name__)
app.config.from_object(Configuration)
app.register_blueprint(myMainRouter.bp)
| [
"from flask import Flask\nfrom config import Configuration\nfrom routes import myMainRouter\n\napp = Flask(__name__)\napp.config.from_object(Configuration)\napp.register_blueprint(myMainRouter.bp)\n",
"from flask import Flask\nfrom config import Configuration\nfrom routes import myMainRouter\napp = Flask(__name__)\napp.config.from_object(Configuration)\napp.register_blueprint(myMainRouter.bp)\n",
"<import token>\napp = Flask(__name__)\napp.config.from_object(Configuration)\napp.register_blueprint(myMainRouter.bp)\n",
"<import token>\n<assignment token>\napp.config.from_object(Configuration)\napp.register_blueprint(myMainRouter.bp)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,980 | 214a6862dc0b1d7822a34ad1c8a1b0381f8f7c6b | import os
from motor import MotorClient
from tornado.options import define, options
from tornado.web import Application
from app.api.urls import urls
def is_debug():
try:
debug = os.environ['DEBUG']
return debug.lower() in ("true", "t", "1")
except KeyError:
return False
def load_conf():
define("debug", default=is_debug())
define("db_name", default=os.getenv("DB_NAME", "pnu_schedule"))
define("db_user", default=os.getenv("DB_USER", "user"))
define("db_password", default=os.getenv("DB_PASSWORD", "password"))
define("db_host", default=os.getenv("DB_HOST", "localhost"))
define("db_port", default=os.getenv("DB_PORT", 27017))
define("app_port", default=os.getenv("APP_PORT", 8888))
define("secret", default=os.getenv("SECRET", "ABCDEFG!@#$%#"))
define("auth_token", default=os.getenv("AUTH_KEY", "123456"))
define("db_uri", default=os.getenv("DB_URI", ("mongodb://{}:{}@{}:{}/".
format(options.db_user,
options.db_password,
options.db_host,
options.db_port))))
def make_app():
db = MotorClient(options.db_uri)[options.db_name]
return Application(handlers=urls, db=db, debug=options.debug)
| [
"import os\n\nfrom motor import MotorClient\nfrom tornado.options import define, options\nfrom tornado.web import Application\n\nfrom app.api.urls import urls\n\n\ndef is_debug():\n try:\n debug = os.environ['DEBUG']\n return debug.lower() in (\"true\", \"t\", \"1\")\n except KeyError:\n return False\n\n\ndef load_conf():\n define(\"debug\", default=is_debug())\n define(\"db_name\", default=os.getenv(\"DB_NAME\", \"pnu_schedule\"))\n define(\"db_user\", default=os.getenv(\"DB_USER\", \"user\"))\n define(\"db_password\", default=os.getenv(\"DB_PASSWORD\", \"password\"))\n define(\"db_host\", default=os.getenv(\"DB_HOST\", \"localhost\"))\n define(\"db_port\", default=os.getenv(\"DB_PORT\", 27017))\n\n define(\"app_port\", default=os.getenv(\"APP_PORT\", 8888))\n define(\"secret\", default=os.getenv(\"SECRET\", \"ABCDEFG!@#$%#\"))\n define(\"auth_token\", default=os.getenv(\"AUTH_KEY\", \"123456\"))\n\n define(\"db_uri\", default=os.getenv(\"DB_URI\", (\"mongodb://{}:{}@{}:{}/\".\n format(options.db_user,\n options.db_password,\n options.db_host,\n options.db_port))))\n\n\ndef make_app():\n db = MotorClient(options.db_uri)[options.db_name]\n return Application(handlers=urls, db=db, debug=options.debug)\n",
"import os\nfrom motor import MotorClient\nfrom tornado.options import define, options\nfrom tornado.web import Application\nfrom app.api.urls import urls\n\n\ndef is_debug():\n try:\n debug = os.environ['DEBUG']\n return debug.lower() in ('true', 't', '1')\n except KeyError:\n return False\n\n\ndef load_conf():\n define('debug', default=is_debug())\n define('db_name', default=os.getenv('DB_NAME', 'pnu_schedule'))\n define('db_user', default=os.getenv('DB_USER', 'user'))\n define('db_password', default=os.getenv('DB_PASSWORD', 'password'))\n define('db_host', default=os.getenv('DB_HOST', 'localhost'))\n define('db_port', default=os.getenv('DB_PORT', 27017))\n define('app_port', default=os.getenv('APP_PORT', 8888))\n define('secret', default=os.getenv('SECRET', 'ABCDEFG!@#$%#'))\n define('auth_token', default=os.getenv('AUTH_KEY', '123456'))\n define('db_uri', default=os.getenv('DB_URI', 'mongodb://{}:{}@{}:{}/'.\n format(options.db_user, options.db_password, options.db_host,\n options.db_port)))\n\n\ndef make_app():\n db = MotorClient(options.db_uri)[options.db_name]\n return Application(handlers=urls, db=db, debug=options.debug)\n",
"<import token>\n\n\ndef is_debug():\n try:\n debug = os.environ['DEBUG']\n return debug.lower() in ('true', 't', '1')\n except KeyError:\n return False\n\n\ndef load_conf():\n define('debug', default=is_debug())\n define('db_name', default=os.getenv('DB_NAME', 'pnu_schedule'))\n define('db_user', default=os.getenv('DB_USER', 'user'))\n define('db_password', default=os.getenv('DB_PASSWORD', 'password'))\n define('db_host', default=os.getenv('DB_HOST', 'localhost'))\n define('db_port', default=os.getenv('DB_PORT', 27017))\n define('app_port', default=os.getenv('APP_PORT', 8888))\n define('secret', default=os.getenv('SECRET', 'ABCDEFG!@#$%#'))\n define('auth_token', default=os.getenv('AUTH_KEY', '123456'))\n define('db_uri', default=os.getenv('DB_URI', 'mongodb://{}:{}@{}:{}/'.\n format(options.db_user, options.db_password, options.db_host,\n options.db_port)))\n\n\ndef make_app():\n db = MotorClient(options.db_uri)[options.db_name]\n return Application(handlers=urls, db=db, debug=options.debug)\n",
"<import token>\n<function token>\n\n\ndef load_conf():\n define('debug', default=is_debug())\n define('db_name', default=os.getenv('DB_NAME', 'pnu_schedule'))\n define('db_user', default=os.getenv('DB_USER', 'user'))\n define('db_password', default=os.getenv('DB_PASSWORD', 'password'))\n define('db_host', default=os.getenv('DB_HOST', 'localhost'))\n define('db_port', default=os.getenv('DB_PORT', 27017))\n define('app_port', default=os.getenv('APP_PORT', 8888))\n define('secret', default=os.getenv('SECRET', 'ABCDEFG!@#$%#'))\n define('auth_token', default=os.getenv('AUTH_KEY', '123456'))\n define('db_uri', default=os.getenv('DB_URI', 'mongodb://{}:{}@{}:{}/'.\n format(options.db_user, options.db_password, options.db_host,\n options.db_port)))\n\n\ndef make_app():\n db = MotorClient(options.db_uri)[options.db_name]\n return Application(handlers=urls, db=db, debug=options.debug)\n",
"<import token>\n<function token>\n\n\ndef load_conf():\n define('debug', default=is_debug())\n define('db_name', default=os.getenv('DB_NAME', 'pnu_schedule'))\n define('db_user', default=os.getenv('DB_USER', 'user'))\n define('db_password', default=os.getenv('DB_PASSWORD', 'password'))\n define('db_host', default=os.getenv('DB_HOST', 'localhost'))\n define('db_port', default=os.getenv('DB_PORT', 27017))\n define('app_port', default=os.getenv('APP_PORT', 8888))\n define('secret', default=os.getenv('SECRET', 'ABCDEFG!@#$%#'))\n define('auth_token', default=os.getenv('AUTH_KEY', '123456'))\n define('db_uri', default=os.getenv('DB_URI', 'mongodb://{}:{}@{}:{}/'.\n format(options.db_user, options.db_password, options.db_host,\n options.db_port)))\n\n\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,981 | f66069ad599747f10ba260f0062d271cf2c0d5a4 | from __future__ import print_function
for col in range(8):
for row in range(col):
for left in range(col - row):
print (' ', end='')
print('#')
| [
"from __future__ import print_function\n\nfor col in range(8):\n for row in range(col):\n for left in range(col - row):\n print (' ', end='')\n print('#')\n",
"from __future__ import print_function\nfor col in range(8):\n for row in range(col):\n for left in range(col - row):\n print(' ', end='')\n print('#')\n",
"<import token>\nfor col in range(8):\n for row in range(col):\n for left in range(col - row):\n print(' ', end='')\n print('#')\n",
"<import token>\n<code token>\n"
] | false |
99,982 | 62f85ea9566ba2ebacb3dddcb746bb287ad8b54d | import torch
def to_categorical(in_content, num_classes=None):
if num_classes is None:
num_classes = int(in_content.max()) + 1
shape = in_content.shape[0], num_classes, *in_content.shape[2:]
temp = torch.zeros(shape).transpose(0, 1)
for i in range(num_classes):
temp[i, (in_content == i).transpose(0, 1).squeeze(0)] = 1
return temp.transpose(0, 1)
__all__ = [
"to_categorical",
]
| [
"import torch\n\n\ndef to_categorical(in_content, num_classes=None):\n if num_classes is None:\n num_classes = int(in_content.max()) + 1\n \n shape = in_content.shape[0], num_classes, *in_content.shape[2:]\n \n temp = torch.zeros(shape).transpose(0, 1)\n \n for i in range(num_classes):\n temp[i, (in_content == i).transpose(0, 1).squeeze(0)] = 1\n \n return temp.transpose(0, 1)\n\n\n__all__ = [\n \"to_categorical\",\n]\n",
"import torch\n\n\ndef to_categorical(in_content, num_classes=None):\n if num_classes is None:\n num_classes = int(in_content.max()) + 1\n shape = in_content.shape[0], num_classes, *in_content.shape[2:]\n temp = torch.zeros(shape).transpose(0, 1)\n for i in range(num_classes):\n temp[i, (in_content == i).transpose(0, 1).squeeze(0)] = 1\n return temp.transpose(0, 1)\n\n\n__all__ = ['to_categorical']\n",
"<import token>\n\n\ndef to_categorical(in_content, num_classes=None):\n if num_classes is None:\n num_classes = int(in_content.max()) + 1\n shape = in_content.shape[0], num_classes, *in_content.shape[2:]\n temp = torch.zeros(shape).transpose(0, 1)\n for i in range(num_classes):\n temp[i, (in_content == i).transpose(0, 1).squeeze(0)] = 1\n return temp.transpose(0, 1)\n\n\n__all__ = ['to_categorical']\n",
"<import token>\n\n\ndef to_categorical(in_content, num_classes=None):\n if num_classes is None:\n num_classes = int(in_content.max()) + 1\n shape = in_content.shape[0], num_classes, *in_content.shape[2:]\n temp = torch.zeros(shape).transpose(0, 1)\n for i in range(num_classes):\n temp[i, (in_content == i).transpose(0, 1).squeeze(0)] = 1\n return temp.transpose(0, 1)\n\n\n<assignment token>\n",
"<import token>\n<function token>\n<assignment token>\n"
] | false |
99,983 | dc72077499ff0254bca3244a8a5cef8d72016ef8 | from .pulsesms import PulseCrypt, PulseSMSAPI
| [
"from .pulsesms import PulseCrypt, PulseSMSAPI\n",
"<import token>\n"
] | false |
99,984 | ee7c3dbe415b89a834f9023426e9a6dd026f1021 | import json
import requests
with open('config.json') as config_file:
es_config = json.load(config_file)
def saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField="timestamp", verify=True):
chart_json = json.loads(altairChart.to_json())
chart_json['data']['url'] = {
"%context%": True,
"index": index,
"body": {
"size": resultSize
}
}
if timeField:
chart_json['data']['url']['%timefield%'] = timeField
visState = {
"type": "vega",
"aggs": [],
"params": {
"spec": json.dumps(chart_json, sort_keys=True, indent=4, separators=(',', ': ')),
},
"title": visName
}
visSavedObject={
"attributes" : {
"title" : visName,
"visState" : json.dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),
"uiStateJSON" : "{}",
"description" : "",
"version" : 1,
"kibanaSavedObjectMeta" : {
"searchSourceJSON" : json.dumps({
"query": {
"language": "kuery",
"query": ""
},
"filter": []
}),
}
}
}
return requests.post(
es_config['kibana_client'] + '/api/saved_objects/visualization/' + visName,
json=visSavedObject,
auth=(es_config['user'], es_config['password']),
headers={"kbn-xsrf":"jupyter2kibana"},
verify=verify
)
def saveVegaVis(index, visName, altairChart, resultSize=100, timeField="timestamp", verify=True):
chart_json = json.loads(altairChart.to_json())
chart_json['spec']['data']['url'] = {
"%context%": True,
"index": index,
"body": {
"size": resultSize
}
}
if timeField:
chart_json['spec']['data']['url']['%timefield%'] = timeField
visState = {
"type": "vega",
"aggs": [],
"params": {
"spec": json.dumps(chart_json, sort_keys=True, indent=4, separators=(',', ': ')),
},
"title": visName
}
visSavedObject={
"attributes" : {
"title" : visName,
"visState" : json.dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),
"uiStateJSON" : "{}",
"description" : "",
"version" : 1,
"kibanaSavedObjectMeta" : {
"searchSourceJSON" : json.dumps({
"query": {
"language": "kuery",
"query": ""
},
"filter": []
}),
}
},
}
return requests.post(
es_config['kibana_client'] + '/api/saved_objects/visualization/' + visName,
json=visSavedObject,
auth=(es_config['user'], es_config['password']),
headers={"kbn-xsrf":"jupyter2kibana"},
verify=verify
)
| [
"import json\nimport requests\n\nwith open('config.json') as config_file:\n es_config = json.load(config_file)\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\"timestamp\", verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {\n \"%context%\": True,\n \"index\": index,\n \"body\": {\n \"size\": resultSize\n }\n }\n\n if timeField:\n chart_json['data']['url']['%timefield%'] = timeField\n\n visState = {\n \"type\": \"vega\",\n \"aggs\": [],\n \"params\": {\n \"spec\": json.dumps(chart_json, sort_keys=True, indent=4, separators=(',', ': ')),\n },\n \"title\": visName\n }\n\n visSavedObject={\n \"attributes\" : {\n \"title\" : visName,\n \"visState\" : json.dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n \"uiStateJSON\" : \"{}\",\n \"description\" : \"\",\n \"version\" : 1,\n \"kibanaSavedObjectMeta\" : {\n \"searchSourceJSON\" : json.dumps({\n \"query\": {\n \"language\": \"kuery\",\n \"query\": \"\"\n },\n \"filter\": []\n }),\n }\n }\n }\n\n return requests.post(\n es_config['kibana_client'] + '/api/saved_objects/visualization/' + visName,\n json=visSavedObject,\n auth=(es_config['user'], es_config['password']),\n headers={\"kbn-xsrf\":\"jupyter2kibana\"},\n verify=verify\n )\n\ndef saveVegaVis(index, visName, altairChart, resultSize=100, timeField=\"timestamp\", verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['spec']['data']['url'] = {\n \"%context%\": True,\n \"index\": index,\n \"body\": {\n \"size\": resultSize\n }\n }\n\n if timeField:\n chart_json['spec']['data']['url']['%timefield%'] = timeField\n\n visState = {\n \"type\": \"vega\",\n \"aggs\": [],\n \"params\": {\n \"spec\": json.dumps(chart_json, sort_keys=True, indent=4, separators=(',', ': ')),\n },\n \"title\": visName\n }\n\n visSavedObject={\n \"attributes\" : {\n \"title\" : visName,\n \"visState\" : json.dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n \"uiStateJSON\" : \"{}\",\n \"description\" : \"\",\n \"version\" : 1,\n \"kibanaSavedObjectMeta\" : {\n \"searchSourceJSON\" : json.dumps({\n \"query\": {\n \"language\": \"kuery\",\n \"query\": \"\"\n },\n \"filter\": []\n }),\n }\n },\n }\n\n return requests.post(\n es_config['kibana_client'] + '/api/saved_objects/visualization/' + visName,\n json=visSavedObject,\n auth=(es_config['user'], es_config['password']),\n headers={\"kbn-xsrf\":\"jupyter2kibana\"},\n verify=verify\n )\n\n",
"import json\nimport requests\nwith open('config.json') as config_file:\n es_config = json.load(config_file)\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {'%context%': True, 'index': index, 'body':\n {'size': resultSize}}\n if timeField:\n chart_json['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n\n\ndef saveVegaVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['spec']['data']['url'] = {'%context%': True, 'index': index,\n 'body': {'size': resultSize}}\n if timeField:\n chart_json['spec']['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n",
"<import token>\nwith open('config.json') as config_file:\n es_config = json.load(config_file)\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {'%context%': True, 'index': index, 'body':\n {'size': resultSize}}\n if timeField:\n chart_json['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n\n\ndef saveVegaVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['spec']['data']['url'] = {'%context%': True, 'index': index,\n 'body': {'size': resultSize}}\n if timeField:\n chart_json['spec']['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n",
"<import token>\n<code token>\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {'%context%': True, 'index': index, 'body':\n {'size': resultSize}}\n if timeField:\n chart_json['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n\n\ndef saveVegaVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['spec']['data']['url'] = {'%context%': True, 'index': index,\n 'body': {'size': resultSize}}\n if timeField:\n chart_json['spec']['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n",
"<import token>\n<code token>\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\n 'timestamp', verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {'%context%': True, 'index': index, 'body':\n {'size': resultSize}}\n if timeField:\n chart_json['data']['url']['%timefield%'] = timeField\n visState = {'type': 'vega', 'aggs': [], 'params': {'spec': json.dumps(\n chart_json, sort_keys=True, indent=4, separators=(',', ': '))},\n 'title': visName}\n visSavedObject = {'attributes': {'title': visName, 'visState': json.\n dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),\n 'uiStateJSON': '{}', 'description': '', 'version': 1,\n 'kibanaSavedObjectMeta': {'searchSourceJSON': json.dumps({'query':\n {'language': 'kuery', 'query': ''}, 'filter': []})}}}\n return requests.post(es_config['kibana_client'] +\n '/api/saved_objects/visualization/' + visName, json=visSavedObject,\n auth=(es_config['user'], es_config['password']), headers={\n 'kbn-xsrf': 'jupyter2kibana'}, verify=verify)\n\n\n<function token>\n",
"<import token>\n<code token>\n<function token>\n<function token>\n"
] | false |
99,985 | 398200b8e922a026827c981e4f14b16bea7eb366 | from django.urls import include, path
from . import views
urlpatterns = [
path('',include("lenus_app.urls")),
path("signup/",views.signup,name="signup" ),
path("logout/",views.logout_request,name="logout" ),
path("login/",views.user_login,name="login" ),
path("profile/",views.profile,name="profile" ),
path("edit_profile/", views.user_change, name="edit_profile"),
path("profile_picture/", views.add_pro_pic, name="add_pro_pic"),
path("change_profile_picture/", views.change_pro_pic, name="change_pro_pic"),
]
| [
"from django.urls import include, path\nfrom . import views\n\nurlpatterns = [\n path('',include(\"lenus_app.urls\")),\n path(\"signup/\",views.signup,name=\"signup\" ),\n path(\"logout/\",views.logout_request,name=\"logout\" ),\n path(\"login/\",views.user_login,name=\"login\" ),\n path(\"profile/\",views.profile,name=\"profile\" ),\n path(\"edit_profile/\", views.user_change, name=\"edit_profile\"),\n path(\"profile_picture/\", views.add_pro_pic, name=\"add_pro_pic\"),\n path(\"change_profile_picture/\", views.change_pro_pic, name=\"change_pro_pic\"),\n]\n",
"from django.urls import include, path\nfrom . import views\nurlpatterns = [path('', include('lenus_app.urls')), path('signup/', views.\n signup, name='signup'), path('logout/', views.logout_request, name=\n 'logout'), path('login/', views.user_login, name='login'), path(\n 'profile/', views.profile, name='profile'), path('edit_profile/', views\n .user_change, name='edit_profile'), path('profile_picture/', views.\n add_pro_pic, name='add_pro_pic'), path('change_profile_picture/', views\n .change_pro_pic, name='change_pro_pic')]\n",
"<import token>\nurlpatterns = [path('', include('lenus_app.urls')), path('signup/', views.\n signup, name='signup'), path('logout/', views.logout_request, name=\n 'logout'), path('login/', views.user_login, name='login'), path(\n 'profile/', views.profile, name='profile'), path('edit_profile/', views\n .user_change, name='edit_profile'), path('profile_picture/', views.\n add_pro_pic, name='add_pro_pic'), path('change_profile_picture/', views\n .change_pro_pic, name='change_pro_pic')]\n",
"<import token>\n<assignment token>\n"
] | false |
99,986 | 04c6a30f1065d5ca42507121d89d73b73d846bc5 | """
Module: DMS Project Wide Context Processors
Project: Adlibre DMS
Copyright: Adlibre Pty Ltd 2012
License: See LICENSE for license information
"""
import os
from django.conf import settings
from core.models import CoreConfiguration
def theme_template_base(context):
""" Returns Global Theme Base Template """
template_path = os.path.join(settings.THEME_NAME, 'theme.html')
return {'THEME_TEMPLATE': template_path}
def theme_name(context):
""" Returns Global Theme Name """
return {'THEME_NAME': settings.THEME_NAME}
def demo(context):
""" Returns Demo Mode Boolean Context Variable """
return {'DEMO': settings.DEMO}
def product_version(context):
""" Returns Context Variable Containing Product version """
return {'PRODUCT_VERSION': settings.PRODUCT_VERSION}
def uncategorized(context):
"""Returns uncategorized DMS model pk and AUI_URL"""
uid = ''
dmid = ''
aui_url = False
configs = CoreConfiguration.objects.filter()
if configs.count():
conf = configs[0]
aui_url = conf.aui_url
uid = str(conf.uncategorized.pk)
dmid = str(conf.uncategorized.doccodepluginmapping.pk)
return {'UNCATEGORIZED_ID': uid,
'UNCATEGORIZED_MAPPING_ID': dmid,
'AUI_URL': aui_url}
def date_format(context):
""" Returns Context Variable Containing Date format currently used """
return {'DATE_FORMAT': settings.DATE_FORMAT.replace('%', '')}
def datetime_format(context):
""" Returns Context Variable Containing Datetime format currently used """
return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}
def stage_variable(context):
""" Determine if we currently running on stage production """
return {'STAGE': settings.STAGE_KEYWORD}
| [
"\"\"\"\nModule: DMS Project Wide Context Processors\nProject: Adlibre DMS\nCopyright: Adlibre Pty Ltd 2012\nLicense: See LICENSE for license information\n\"\"\"\n\nimport os\n\nfrom django.conf import settings\nfrom core.models import CoreConfiguration\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\ndef product_version(context):\n \"\"\" Returns Context Variable Containing Product version \"\"\"\n return {'PRODUCT_VERSION': settings.PRODUCT_VERSION}\n\ndef uncategorized(context):\n \"\"\"Returns uncategorized DMS model pk and AUI_URL\"\"\"\n uid = ''\n dmid = ''\n aui_url = False\n configs = CoreConfiguration.objects.filter()\n if configs.count():\n conf = configs[0]\n aui_url = conf.aui_url\n uid = str(conf.uncategorized.pk)\n dmid = str(conf.uncategorized.doccodepluginmapping.pk)\n return {'UNCATEGORIZED_ID': uid,\n 'UNCATEGORIZED_MAPPING_ID': dmid,\n 'AUI_URL': aui_url}\n\ndef date_format(context):\n \"\"\" Returns Context Variable Containing Date format currently used \"\"\"\n return {'DATE_FORMAT': settings.DATE_FORMAT.replace('%', '')}\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n\n\n",
"<docstring token>\nimport os\nfrom django.conf import settings\nfrom core.models import CoreConfiguration\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\ndef product_version(context):\n \"\"\" Returns Context Variable Containing Product version \"\"\"\n return {'PRODUCT_VERSION': settings.PRODUCT_VERSION}\n\n\ndef uncategorized(context):\n \"\"\"Returns uncategorized DMS model pk and AUI_URL\"\"\"\n uid = ''\n dmid = ''\n aui_url = False\n configs = CoreConfiguration.objects.filter()\n if configs.count():\n conf = configs[0]\n aui_url = conf.aui_url\n uid = str(conf.uncategorized.pk)\n dmid = str(conf.uncategorized.doccodepluginmapping.pk)\n return {'UNCATEGORIZED_ID': uid, 'UNCATEGORIZED_MAPPING_ID': dmid,\n 'AUI_URL': aui_url}\n\n\ndef date_format(context):\n \"\"\" Returns Context Variable Containing Date format currently used \"\"\"\n return {'DATE_FORMAT': settings.DATE_FORMAT.replace('%', '')}\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\ndef product_version(context):\n \"\"\" Returns Context Variable Containing Product version \"\"\"\n return {'PRODUCT_VERSION': settings.PRODUCT_VERSION}\n\n\ndef uncategorized(context):\n \"\"\"Returns uncategorized DMS model pk and AUI_URL\"\"\"\n uid = ''\n dmid = ''\n aui_url = False\n configs = CoreConfiguration.objects.filter()\n if configs.count():\n conf = configs[0]\n aui_url = conf.aui_url\n uid = str(conf.uncategorized.pk)\n dmid = str(conf.uncategorized.doccodepluginmapping.pk)\n return {'UNCATEGORIZED_ID': uid, 'UNCATEGORIZED_MAPPING_ID': dmid,\n 'AUI_URL': aui_url}\n\n\ndef date_format(context):\n \"\"\" Returns Context Variable Containing Date format currently used \"\"\"\n return {'DATE_FORMAT': settings.DATE_FORMAT.replace('%', '')}\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n\n\ndef uncategorized(context):\n \"\"\"Returns uncategorized DMS model pk and AUI_URL\"\"\"\n uid = ''\n dmid = ''\n aui_url = False\n configs = CoreConfiguration.objects.filter()\n if configs.count():\n conf = configs[0]\n aui_url = conf.aui_url\n uid = str(conf.uncategorized.pk)\n dmid = str(conf.uncategorized.doccodepluginmapping.pk)\n return {'UNCATEGORIZED_ID': uid, 'UNCATEGORIZED_MAPPING_ID': dmid,\n 'AUI_URL': aui_url}\n\n\ndef date_format(context):\n \"\"\" Returns Context Variable Containing Date format currently used \"\"\"\n return {'DATE_FORMAT': settings.DATE_FORMAT.replace('%', '')}\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n\n\ndef uncategorized(context):\n \"\"\"Returns uncategorized DMS model pk and AUI_URL\"\"\"\n uid = ''\n dmid = ''\n aui_url = False\n configs = CoreConfiguration.objects.filter()\n if configs.count():\n conf = configs[0]\n aui_url = conf.aui_url\n uid = str(conf.uncategorized.pk)\n dmid = str(conf.uncategorized.doccodepluginmapping.pk)\n return {'UNCATEGORIZED_ID': uid, 'UNCATEGORIZED_MAPPING_ID': dmid,\n 'AUI_URL': aui_url}\n\n\n<function token>\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\ndef stage_variable(context):\n \"\"\" Determine if we currently running on stage production \"\"\"\n return {'STAGE': settings.STAGE_KEYWORD}\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef datetime_format(context):\n \"\"\" Returns Context Variable Containing Datetime format currently used \"\"\"\n return {'DATETIME_FORMAT': settings.DATETIME_FORMAT.replace('%', '')}\n\n\n<function token>\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\ndef theme_name(context):\n \"\"\" Returns Global Theme Name \"\"\"\n return {'THEME_NAME': settings.THEME_NAME}\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n",
"<docstring token>\n<import token>\n\n\ndef theme_template_base(context):\n \"\"\" Returns Global Theme Base Template \"\"\"\n template_path = os.path.join(settings.THEME_NAME, 'theme.html')\n return {'THEME_TEMPLATE': template_path}\n\n\n<function token>\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n",
"<docstring token>\n<import token>\n<function token>\n<function token>\n\n\ndef demo(context):\n \"\"\" Returns Demo Mode Boolean Context Variable \"\"\"\n return {'DEMO': settings.DEMO}\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n",
"<docstring 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"
] | false |
99,987 | cb6d64a8495022b4962c51eae9bef5adf47dc6fa | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 12:44:18 2021
@author: tai
"""
'''
Evaluate Object Detection Model:
1. Get all bounding box prediction on our test set
Table:
Image_name Confidence_value TP_or_FP
image1 0.3 FP
image3
2. Sort by descending confidence score:
The largest confidence value at top of the table
3. Calculate Precision and Recall:
Precision: Dự Đoán đúng / (tất cả dự đoán)
Recall: Dự đoán đúng / (Label_đúng)
NOTE: ???????????????/ Bước này Biết cách làm nhưng không hiểu ý nghĩa
4. Plot the Precision-Recall graph
5. Calculate Area Under PR curve
Dog AP = 0.533
6. Do all classes
Dog AP = 0.533
Cat AP = 0.74
mAP = (0.533 + 0.74) / 2 = 0.6365
7. Average for IoU_Threshold
mAP @ 0.5: 0.05 : 0.95
That mean
mAP @ 0.5 =
mAP @ 0.55 =
0.6 =
.
.
.
mAP @ 0.95 =
Sum all of them and take average
'''
import torch
from collection import Counter
from IOU import intersection_over_union
'''
For single Iou_Threshold
For Testing Phase, not training Because, we do not have loss function
'''
def mean_average_precision(
pred_boxes, true_boxes, iou_threshold=0.5, box_format="corners",
num_classes = 20):
# pred_boxes (list) : [[train_idx, class_pred, prob_score, x1, y1, x2, y2], ...]
average_precisions = [] # mAP
epsilon = 1e-6
for c in range(num_classes): # For each class, Dog and Cat
detections = []
ground_truths = []
# Step 1: Get all bounding box prediction on our test set
# Summarise all Dog bboxs predicted in test set image
for detection in pred_boxes:
if detection[1] == c:
detections.append(detection) #
# Summarise all Dog bboxs label/ground_truth in test set image
for true_box in true_boxes:
if true_box[1] == c:
ground_truths.append(true_box)
'''
Theo dõi trường hợp 2 bbox cho cùng 1 vật thể, Trừng phạt trường hợp bbox có confidence nhỏ hơn
# img 0 has 3 bboxes
# img 1 has 5 bboxes
# amount_bboxes = {0:3 , 1:5}
'''
amount_bboxes = Counter([gt[0] for gt in ground_truths])
for key, val in amount_bboxes.items():
amount_bboxes[key] = torch.zeros(val)
# amount_boxes = {0: torch.tensor([0, 0, 0]), 1: torch.tensor([0, 0, 0, 0, 0])}
# Use this to calculate Precision and Recall
# Step 2: Sort by descending confidence score:
detection.sort(key = lambda x: x[2], reverse = True)
# Step 3: Calculate Precision and Recall:
TP = torch.zeros((len(detections))) # Create column for TP and FP
FP = torch.zeros((len(detections)))
total_true_bboxes = len(ground_truths)
'''
After sorting, each row have
[train_idx, class_pred, prob_score, x1, y1, x2, y2]
we only use:
[train_idx, prob_score, x1, y1, x2, y2]
1. For each bbox in detection
compare to all bbox in Ground_Truth
-> find best_iou
2. best_iou > 0.5 : TP = 1, FP = 0
best_iou < 0.5 : FP = 1, TP = 0
NOTE: detection in confidence order
Tại đây, Chúng ta sau đi loại bỏ bbox có confidence < confidence_threshold
và loại bỏ bbox có Non-Max Suppresion, thì vẫn còn trường hợp 2 bbox cùng thể hiện 1 vât thể
Nên, chúng ta chọn bbox với confidence lớn hơn
Set TP = 1, FP = 0
và, bbox với confidence nhỏ hơn:
Set TP = 0, FP = 1
Summary: Trừng phạt mAP
1. một vật thể có 2 bbox (1 trong 2, với confidence nhỏ hơn)
2. iou of bbox_predict and bbox_label quá thấp
'''
for detection_idx, detection in enumerate(detections):
ground_truth_img = [bbox for bbox in ground_truths if bbox[0] == detection[0]]
num_gts = len(ground_truth_img)
best_iou = 0
'''
'''
for idx, gt in enumerate(ground_truth_img):
iou = intersection_over_union(
torch.tensor(detection[3:]), torch.tensor(gt[3:]),
box_format_box = box_format,
)
# NOTE: pred_boxes (list) : [[train_idx, class_pred, prob_score, x1, y1, x2, y2], ...]
if iou > best_iou:
best_iou = iou
best_gt_idx = idx
if best_iou > iou_threshold: # Larger than 0.5, TP = 1, FP = 0, ver vice
# Trường hợp 2 bboxes cho một vật thể, dư bbox sẽ bị trừng phạt
if amount_bboxes[detection[0]][best_gt_idx] == 0:
TP[detection_idx] = 1
amount_bboxes[detection[0]][best_gt_idx] = 1
else:
FP[detection_idx] = 1
else:
FP[detection_idx] = 1
# [1, 1, 0, 1, 0] -> [1, 2, 2, 3, 3]
# Tạo phần tử số cho TP và FP
TP_cumsum = torch.cumsum(TP, dim = 0)
FP_cumsum = torch.cumsum(FP, dim = 0)
# Final value for Precisions and Recalls
'''
Mẫu số của recalls luôn cố định (= total bbox_label in test set)
Mẫu số của precision tăng theo số lượng bbox_prediction trong test set
Tử số của recalls và precision tăng theo TP, có giá trị nhu nhau
'''
recalls = TP_cumsum / (total_true_bboxes + epsilon)
precisions = torch.divide(TP_cumsum, (TP_cumsum + FP_cumsum + epsilon))
# Step 4. Plot the Precision-Recall graph
'''
vì Graph bắt đầu tại
x = 0 = recall[0]
y = 1 = precision[0]
Xem trong hình vẽ
'''
precisions = torch.cat((torch.tensor[1], precisions))
recalls = torch.cat((torch.tensor([0]), recalls))
# Step 5: Calculate Area Under PR curve, Tính diện tích
average_precisions.append(torch.trapz(precisions, recalls)) # ????????????//
return sum(average_precisions) / len(average_precisions) # (mAP of Dog + mAP of Cat) / 2
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 29 12:44:18 2021\n\n@author: tai\n\"\"\"\n\n'''\nEvaluate Object Detection Model:\n1. Get all bounding box prediction on our test set\nTable:\n Image_name Confidence_value TP_or_FP\n image1 0.3 FP\n image3\n \n2. Sort by descending confidence score:\n The largest confidence value at top of the table\n\n3. Calculate Precision and Recall:\n Precision: Dự Đoán đúng / (tất cả dự đoán)\n Recall: Dự đoán đúng / (Label_đúng)\n\nNOTE: ???????????????/ Bước này Biết cách làm nhưng không hiểu ý nghĩa\n4. Plot the Precision-Recall graph\n\n5. Calculate Area Under PR curve \n\nDog AP = 0.533\n\n6. Do all classes\n\nDog AP = 0.533\nCat AP = 0.74\n\nmAP = (0.533 + 0.74) / 2 = 0.6365\n\n7. Average for IoU_Threshold \nmAP @ 0.5: 0.05 : 0.95\nThat mean\nmAP @ 0.5 = \nmAP @ 0.55 = \n0.6 =\n.\n.\n.\nmAP @ 0.95 = \n\nSum all of them and take average\n'''\n\nimport torch\nfrom collection import Counter\nfrom IOU import intersection_over_union\n\n'''\nFor single Iou_Threshold\nFor Testing Phase, not training Because, we do not have loss function\n'''\ndef mean_average_precision(\n pred_boxes, true_boxes, iou_threshold=0.5, box_format=\"corners\",\n num_classes = 20):\n \n # pred_boxes (list) : [[train_idx, class_pred, prob_score, x1, y1, x2, y2], ...]\n average_precisions = [] # mAP\n epsilon = 1e-6\n \n for c in range(num_classes): # For each class, Dog and Cat\n detections = []\n ground_truths = []\n \n # Step 1: Get all bounding box prediction on our test set\n # Summarise all Dog bboxs predicted in test set image\n for detection in pred_boxes:\n if detection[1] == c:\n detections.append(detection) # \n \n # Summarise all Dog bboxs label/ground_truth in test set image\n for true_box in true_boxes:\n if true_box[1] == c:\n ground_truths.append(true_box)\n \n '''\n Theo dõi trường hợp 2 bbox cho cùng 1 vật thể, Trừng phạt trường hợp bbox có confidence nhỏ hơn\n # img 0 has 3 bboxes\n # img 1 has 5 bboxes\n # amount_bboxes = {0:3 , 1:5}\n '''\n amount_bboxes = Counter([gt[0] for gt in ground_truths])\n \n for key, val in amount_bboxes.items():\n amount_bboxes[key] = torch.zeros(val) \n # amount_boxes = {0: torch.tensor([0, 0, 0]), 1: torch.tensor([0, 0, 0, 0, 0])}\n # Use this to calculate Precision and Recall\n \n # Step 2: Sort by descending confidence score:\n detection.sort(key = lambda x: x[2], reverse = True)\n \n # Step 3: Calculate Precision and Recall:\n TP = torch.zeros((len(detections))) # Create column for TP and FP\n FP = torch.zeros((len(detections)))\n total_true_bboxes = len(ground_truths)\n \n '''\n After sorting, each row have \n [train_idx, class_pred, prob_score, x1, y1, x2, y2]\n we only use:\n [train_idx, prob_score, x1, y1, x2, y2] \n 1. For each bbox in detection\n compare to all bbox in Ground_Truth\n -> find best_iou\n \n 2. best_iou > 0.5 : TP = 1, FP = 0\n best_iou < 0.5 : FP = 1, TP = 0\n \n NOTE: detection in confidence order\n \n Tại đây, Chúng ta sau đi loại bỏ bbox có confidence < confidence_threshold\n và loại bỏ bbox có Non-Max Suppresion, thì vẫn còn trường hợp 2 bbox cùng thể hiện 1 vât thể\n \n Nên, chúng ta chọn bbox với confidence lớn hơn\n Set TP = 1, FP = 0\n và, bbox với confidence nhỏ hơn:\n Set TP = 0, FP = 1 \n \n Summary: Trừng phạt mAP\n 1. một vật thể có 2 bbox (1 trong 2, với confidence nhỏ hơn)\n 2. iou of bbox_predict and bbox_label quá thấp \n \n \n '''\n for detection_idx, detection in enumerate(detections):\n ground_truth_img = [bbox for bbox in ground_truths if bbox[0] == detection[0]]\n \n num_gts = len(ground_truth_img)\n best_iou = 0\n \n '''\n\n '''\n for idx, gt in enumerate(ground_truth_img):\n iou = intersection_over_union(\n torch.tensor(detection[3:]), torch.tensor(gt[3:]),\n box_format_box = box_format, \n )\n # NOTE: pred_boxes (list) : [[train_idx, class_pred, prob_score, x1, y1, x2, y2], ...]\n if iou > best_iou:\n best_iou = iou\n best_gt_idx = idx\n \n if best_iou > iou_threshold: # Larger than 0.5, TP = 1, FP = 0, ver vice\n # Trường hợp 2 bboxes cho một vật thể, dư bbox sẽ bị trừng phạt \n if amount_bboxes[detection[0]][best_gt_idx] == 0:\n TP[detection_idx] = 1\n amount_bboxes[detection[0]][best_gt_idx] = 1\n else:\n FP[detection_idx] = 1\n else:\n FP[detection_idx] = 1\n \n # [1, 1, 0, 1, 0] -> [1, 2, 2, 3, 3]\n # Tạo phần tử số cho TP và FP \n TP_cumsum = torch.cumsum(TP, dim = 0)\n FP_cumsum = torch.cumsum(FP, dim = 0)\n \n # Final value for Precisions and Recalls\n '''\n Mẫu số của recalls luôn cố định (= total bbox_label in test set)\n Mẫu số của precision tăng theo số lượng bbox_prediction trong test set\n \n Tử số của recalls và precision tăng theo TP, có giá trị nhu nhau\n '''\n recalls = TP_cumsum / (total_true_bboxes + epsilon)\n precisions = torch.divide(TP_cumsum, (TP_cumsum + FP_cumsum + epsilon))\n \n # Step 4. Plot the Precision-Recall graph\n '''\n vì Graph bắt đầu tại\n x = 0 = recall[0]\n y = 1 = precision[0]\n \n Xem trong hình vẽ\n '''\n precisions = torch.cat((torch.tensor[1], precisions))\n recalls = torch.cat((torch.tensor([0]), recalls))\n \n # Step 5: Calculate Area Under PR curve, Tính diện tích\n average_precisions.append(torch.trapz(precisions, recalls)) # ????????????//\n \n return sum(average_precisions) / len(average_precisions) # (mAP of Dog + mAP of Cat) / 2\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"<docstring token>\nimport torch\nfrom collection import Counter\nfrom IOU import intersection_over_union\n<docstring token>\n\n\ndef mean_average_precision(pred_boxes, true_boxes, iou_threshold=0.5,\n box_format='corners', num_classes=20):\n average_precisions = []\n epsilon = 1e-06\n for c in range(num_classes):\n detections = []\n ground_truths = []\n for detection in pred_boxes:\n if detection[1] == c:\n detections.append(detection)\n for true_box in true_boxes:\n if true_box[1] == c:\n ground_truths.append(true_box)\n \"\"\"\n Theo dõi trường hợp 2 bbox cho cùng 1 vật thể, Trừng phạt trường hợp bbox có confidence nhỏ hơn\n # img 0 has 3 bboxes\n # img 1 has 5 bboxes\n # amount_bboxes = {0:3 , 1:5}\n \"\"\"\n amount_bboxes = Counter([gt[0] for gt in ground_truths])\n for key, val in amount_bboxes.items():\n amount_bboxes[key] = torch.zeros(val)\n detection.sort(key=lambda x: x[2], reverse=True)\n TP = torch.zeros(len(detections))\n FP = torch.zeros(len(detections))\n total_true_bboxes = len(ground_truths)\n \"\"\"\n After sorting, each row have \n [train_idx, class_pred, prob_score, x1, y1, x2, y2]\n we only use:\n [train_idx, prob_score, x1, y1, x2, y2] \n 1. For each bbox in detection\n compare to all bbox in Ground_Truth\n -> find best_iou\n \n 2. best_iou > 0.5 : TP = 1, FP = 0\n best_iou < 0.5 : FP = 1, TP = 0\n \n NOTE: detection in confidence order\n \n Tại đây, Chúng ta sau đi loại bỏ bbox có confidence < confidence_threshold\n và loại bỏ bbox có Non-Max Suppresion, thì vẫn còn trường hợp 2 bbox cùng thể hiện 1 vât thể\n \n Nên, chúng ta chọn bbox với confidence lớn hơn\n Set TP = 1, FP = 0\n và, bbox với confidence nhỏ hơn:\n Set TP = 0, FP = 1 \n \n Summary: Trừng phạt mAP\n 1. một vật thể có 2 bbox (1 trong 2, với confidence nhỏ hơn)\n 2. iou of bbox_predict and bbox_label quá thấp \n \n \n \"\"\"\n for detection_idx, detection in enumerate(detections):\n ground_truth_img = [bbox for bbox in ground_truths if bbox[0] ==\n detection[0]]\n num_gts = len(ground_truth_img)\n best_iou = 0\n \"\"\"\n\n \"\"\"\n for idx, gt in enumerate(ground_truth_img):\n iou = intersection_over_union(torch.tensor(detection[3:]),\n torch.tensor(gt[3:]), box_format_box=box_format)\n if iou > best_iou:\n best_iou = iou\n best_gt_idx = idx\n if best_iou > iou_threshold:\n if amount_bboxes[detection[0]][best_gt_idx] == 0:\n TP[detection_idx] = 1\n amount_bboxes[detection[0]][best_gt_idx] = 1\n else:\n FP[detection_idx] = 1\n else:\n FP[detection_idx] = 1\n TP_cumsum = torch.cumsum(TP, dim=0)\n FP_cumsum = torch.cumsum(FP, dim=0)\n \"\"\"\n Mẫu số của recalls luôn cố định (= total bbox_label in test set)\n Mẫu số của precision tăng theo số lượng bbox_prediction trong test set\n \n Tử số của recalls và precision tăng theo TP, có giá trị nhu nhau\n \"\"\"\n recalls = TP_cumsum / (total_true_bboxes + epsilon)\n precisions = torch.divide(TP_cumsum, TP_cumsum + FP_cumsum + epsilon)\n \"\"\"\n vì Graph bắt đầu tại\n x = 0 = recall[0]\n y = 1 = precision[0]\n \n Xem trong hình vẽ\n \"\"\"\n precisions = torch.cat((torch.tensor[1], precisions))\n recalls = torch.cat((torch.tensor([0]), recalls))\n average_precisions.append(torch.trapz(precisions, recalls))\n return sum(average_precisions) / len(average_precisions)\n",
"<docstring token>\n<import token>\n<docstring token>\n\n\ndef mean_average_precision(pred_boxes, true_boxes, iou_threshold=0.5,\n box_format='corners', num_classes=20):\n average_precisions = []\n epsilon = 1e-06\n for c in range(num_classes):\n detections = []\n ground_truths = []\n for detection in pred_boxes:\n if detection[1] == c:\n detections.append(detection)\n for true_box in true_boxes:\n if true_box[1] == c:\n ground_truths.append(true_box)\n \"\"\"\n Theo dõi trường hợp 2 bbox cho cùng 1 vật thể, Trừng phạt trường hợp bbox có confidence nhỏ hơn\n # img 0 has 3 bboxes\n # img 1 has 5 bboxes\n # amount_bboxes = {0:3 , 1:5}\n \"\"\"\n amount_bboxes = Counter([gt[0] for gt in ground_truths])\n for key, val in amount_bboxes.items():\n amount_bboxes[key] = torch.zeros(val)\n detection.sort(key=lambda x: x[2], reverse=True)\n TP = torch.zeros(len(detections))\n FP = torch.zeros(len(detections))\n total_true_bboxes = len(ground_truths)\n \"\"\"\n After sorting, each row have \n [train_idx, class_pred, prob_score, x1, y1, x2, y2]\n we only use:\n [train_idx, prob_score, x1, y1, x2, y2] \n 1. For each bbox in detection\n compare to all bbox in Ground_Truth\n -> find best_iou\n \n 2. best_iou > 0.5 : TP = 1, FP = 0\n best_iou < 0.5 : FP = 1, TP = 0\n \n NOTE: detection in confidence order\n \n Tại đây, Chúng ta sau đi loại bỏ bbox có confidence < confidence_threshold\n và loại bỏ bbox có Non-Max Suppresion, thì vẫn còn trường hợp 2 bbox cùng thể hiện 1 vât thể\n \n Nên, chúng ta chọn bbox với confidence lớn hơn\n Set TP = 1, FP = 0\n và, bbox với confidence nhỏ hơn:\n Set TP = 0, FP = 1 \n \n Summary: Trừng phạt mAP\n 1. một vật thể có 2 bbox (1 trong 2, với confidence nhỏ hơn)\n 2. iou of bbox_predict and bbox_label quá thấp \n \n \n \"\"\"\n for detection_idx, detection in enumerate(detections):\n ground_truth_img = [bbox for bbox in ground_truths if bbox[0] ==\n detection[0]]\n num_gts = len(ground_truth_img)\n best_iou = 0\n \"\"\"\n\n \"\"\"\n for idx, gt in enumerate(ground_truth_img):\n iou = intersection_over_union(torch.tensor(detection[3:]),\n torch.tensor(gt[3:]), box_format_box=box_format)\n if iou > best_iou:\n best_iou = iou\n best_gt_idx = idx\n if best_iou > iou_threshold:\n if amount_bboxes[detection[0]][best_gt_idx] == 0:\n TP[detection_idx] = 1\n amount_bboxes[detection[0]][best_gt_idx] = 1\n else:\n FP[detection_idx] = 1\n else:\n FP[detection_idx] = 1\n TP_cumsum = torch.cumsum(TP, dim=0)\n FP_cumsum = torch.cumsum(FP, dim=0)\n \"\"\"\n Mẫu số của recalls luôn cố định (= total bbox_label in test set)\n Mẫu số của precision tăng theo số lượng bbox_prediction trong test set\n \n Tử số của recalls và precision tăng theo TP, có giá trị nhu nhau\n \"\"\"\n recalls = TP_cumsum / (total_true_bboxes + epsilon)\n precisions = torch.divide(TP_cumsum, TP_cumsum + FP_cumsum + epsilon)\n \"\"\"\n vì Graph bắt đầu tại\n x = 0 = recall[0]\n y = 1 = precision[0]\n \n Xem trong hình vẽ\n \"\"\"\n precisions = torch.cat((torch.tensor[1], precisions))\n recalls = torch.cat((torch.tensor([0]), recalls))\n average_precisions.append(torch.trapz(precisions, recalls))\n return sum(average_precisions) / len(average_precisions)\n",
"<docstring token>\n<import token>\n<docstring token>\n<function token>\n"
] | false |
99,988 | 32d715dbe1764e86f9d5c2bee93bbbda2ec3515f | import pulumi_aws as aws
import pulumi
import os
import mimetypes
config = pulumi.Config()
site_dir = config.get("site")
bucket = aws.s3.Bucket(resource_name="pulumi-demo",
bucket="pulumi-demo",
tags={
"Owner": "pulumi-demo",
"Purpose": "demo",
"Place": "atlas"
},
website={"indexDocument": "index.html"})
filepath = os.path.join(site_dir, "index.html")
mimetype,_=mimetypes.guess_type(filepath)
bucket_object = aws.s3.BucketObject(
"index.html",
bucket=bucket.bucket,
acl="public-read",
source=filepath,
content_type=mimetype)
pulumi.export('bucket_name', bucket.bucket)
pulumi.export('bucket_endpoint', bucket.website_endpoint)
| [
"import pulumi_aws as aws\nimport pulumi\nimport os\nimport mimetypes\n\nconfig = pulumi.Config()\nsite_dir = config.get(\"site\")\n\nbucket = aws.s3.Bucket(resource_name=\"pulumi-demo\",\n bucket=\"pulumi-demo\",\n tags={\n \"Owner\": \"pulumi-demo\",\n \"Purpose\": \"demo\",\n \"Place\": \"atlas\"\n },\n website={\"indexDocument\": \"index.html\"})\nfilepath = os.path.join(site_dir, \"index.html\")\nmimetype,_=mimetypes.guess_type(filepath)\nbucket_object = aws.s3.BucketObject(\n \"index.html\",\n bucket=bucket.bucket,\n acl=\"public-read\",\n source=filepath,\n content_type=mimetype)\n\npulumi.export('bucket_name', bucket.bucket)\npulumi.export('bucket_endpoint', bucket.website_endpoint)\n",
"import pulumi_aws as aws\nimport pulumi\nimport os\nimport mimetypes\nconfig = pulumi.Config()\nsite_dir = config.get('site')\nbucket = aws.s3.Bucket(resource_name='pulumi-demo', bucket='pulumi-demo',\n tags={'Owner': 'pulumi-demo', 'Purpose': 'demo', 'Place': 'atlas'},\n website={'indexDocument': 'index.html'})\nfilepath = os.path.join(site_dir, 'index.html')\nmimetype, _ = mimetypes.guess_type(filepath)\nbucket_object = aws.s3.BucketObject('index.html', bucket=bucket.bucket, acl\n ='public-read', source=filepath, content_type=mimetype)\npulumi.export('bucket_name', bucket.bucket)\npulumi.export('bucket_endpoint', bucket.website_endpoint)\n",
"<import token>\nconfig = pulumi.Config()\nsite_dir = config.get('site')\nbucket = aws.s3.Bucket(resource_name='pulumi-demo', bucket='pulumi-demo',\n tags={'Owner': 'pulumi-demo', 'Purpose': 'demo', 'Place': 'atlas'},\n website={'indexDocument': 'index.html'})\nfilepath = os.path.join(site_dir, 'index.html')\nmimetype, _ = mimetypes.guess_type(filepath)\nbucket_object = aws.s3.BucketObject('index.html', bucket=bucket.bucket, acl\n ='public-read', source=filepath, content_type=mimetype)\npulumi.export('bucket_name', bucket.bucket)\npulumi.export('bucket_endpoint', bucket.website_endpoint)\n",
"<import token>\n<assignment token>\npulumi.export('bucket_name', bucket.bucket)\npulumi.export('bucket_endpoint', bucket.website_endpoint)\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
99,989 | 0b67714bf9b60e63e48586ac2a1e50468a918752 | import pprint
import re
from collections import defaultdict
__author__ = 'ronanbrady2'
# Prints all street suffixes, e.g. Lane, Avenue, to allow audit analysis
def printAllStreetSuffixes(db):
pipeline = [
{ "$group" : {
"_id" : "$address.street" ,
"count" : { "$sum" : 1 } }},
{ "$sort" : { "_id" : 1 }}]
result = db.openmap.aggregate(pipeline)
valsfound = defaultdict(int)
regx = re.compile("\s(\w+)$", re.IGNORECASE)
for r in result:
val = r['_id']
if(not val is None):
i = regx.finditer(val)
for match in i:
streettype = match.group(0).strip()
valsfound[streettype] += 1
pprint.pprint(valsfound)
# Prints all addresses with Postcode
def printAllWithPostcodes(db):
result = db.openmap.find({"address.postcode" : { "$exists" : "true"} })
pprint.pprint(result)
# Prints all addresses with County
def printAllWithCounty(db):
result = db.openmap.find({ "address.county" : { "$exists" : "true" } }).count()
pprint.pprint(result)
def printAllAmenities(db):
result = db.openmap.find({ "amenity" : { "$exists" : "true" } }).count()
pprint.pprint(result)
def capacityOfAllCarparks(db):
pipeline = [ { "$match" : { "amenity" : "parking"} }]
# turns out none of the car parks have capacity in the listing
# { "$group" : { "_id" : None , "total_capacity" : {"$sum" : "capacity"}} } ]
result = db.openmap.aggregate(pipeline)
for r in result:
pprint.pprint(r)
def pubsByContributor(db):
pipeline = [ { "$match" : { "amenity" : "pub"} },
{ "$group" : { "_id" : "$created.user", "count" : { "$sum" : 1 }}},
{ "$sort" : { "count" : -1 }}]
result = db.openmap.aggregate(pipeline)
for r in result:
pprint.pprint(r)
def pubsWithBeerGardens(db):
pipeline = [ { "$match" : { "amenity" : "pub"} },
{ "$match" : { "beer_garden" : "yes"} },
{ "$group" : { "_id" : None, "count" : { "$sum" : 1 }}}]
result = db.openmap.aggregate(pipeline)
for r in result:
pprint.pprint(r)
def fastFoodByCuisine(db):
pipeline = [ { "$match" : { "amenity" : "fast_food"} },
{ "$group" : { "_id" : "$cuisine", "count" : { "$sum" : 1 }}},
{ "$sort" : { "count" : -1 }}]
result = db.openmap.aggregate(pipeline)
for r in result:
pprint.pprint(r)
def printTop10AppearingAmenities(db):
pipeline = [{"$match": {"amenity": {"$exists": "true"}}},
{"$group":{"_id":"$amenity", "count": {"$sum":1}}},
{"$sort":{"count": -1}}, {"$limit":10}]
result = db.openmap.aggregate(pipeline)
for r in result:
pprint.pprint(r)
# Connects to 'udwrangle' DB and returns DB object
def connectDB() :
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client.udwrangle
return db
if __name__ == "__main__":
db = connectDB()
#printAllStreetSuffixes(db)
#printAllWithPostcodes(db)
#printAllWithCounty(db)
#printTop10AppearingAmenities(db)
#printAllAmenities(db)
#capacityOfAllCarparks(db)
#pubsByContributor(db)
#pubsWithBeerGardens(db)
fastFoodByCuisine(db)
| [
"import pprint\nimport re\nfrom collections import defaultdict\n\n__author__ = 'ronanbrady2'\n\n# Prints all street suffixes, e.g. Lane, Avenue, to allow audit analysis\ndef printAllStreetSuffixes(db):\n pipeline = [\n { \"$group\" : {\n \"_id\" : \"$address.street\" ,\n \"count\" : { \"$sum\" : 1 } }},\n { \"$sort\" : { \"_id\" : 1 }}]\n\n result = db.openmap.aggregate(pipeline)\n\n valsfound = defaultdict(int)\n regx = re.compile(\"\\s(\\w+)$\", re.IGNORECASE)\n for r in result:\n val = r['_id']\n\n\n if(not val is None):\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n# Prints all addresses with Postcode\ndef printAllWithPostcodes(db):\n result = db.openmap.find({\"address.postcode\" : { \"$exists\" : \"true\"} })\n pprint.pprint(result)\n\n# Prints all addresses with County\ndef printAllWithCounty(db):\n result = db.openmap.find({ \"address.county\" : { \"$exists\" : \"true\" } }).count()\n pprint.pprint(result)\n\ndef printAllAmenities(db):\n result = db.openmap.find({ \"amenity\" : { \"$exists\" : \"true\" } }).count()\n pprint.pprint(result)\n\ndef capacityOfAllCarparks(db):\n pipeline = [ { \"$match\" : { \"amenity\" : \"parking\"} }]\n # turns out none of the car parks have capacity in the listing\n # { \"$group\" : { \"_id\" : None , \"total_capacity\" : {\"$sum\" : \"capacity\"}} } ]\n\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\ndef pubsByContributor(db):\n pipeline = [ { \"$match\" : { \"amenity\" : \"pub\"} },\n { \"$group\" : { \"_id\" : \"$created.user\", \"count\" : { \"$sum\" : 1 }}},\n { \"$sort\" : { \"count\" : -1 }}]\n\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\ndef pubsWithBeerGardens(db):\n pipeline = [ { \"$match\" : { \"amenity\" : \"pub\"} },\n { \"$match\" : { \"beer_garden\" : \"yes\"} },\n { \"$group\" : { \"_id\" : None, \"count\" : { \"$sum\" : 1 }}}]\n\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\ndef fastFoodByCuisine(db):\n pipeline = [ { \"$match\" : { \"amenity\" : \"fast_food\"} },\n { \"$group\" : { \"_id\" : \"$cuisine\", \"count\" : { \"$sum\" : 1 }}},\n { \"$sort\" : { \"count\" : -1 }}]\n\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{\"$match\": {\"amenity\": {\"$exists\": \"true\"}}},\n {\"$group\":{\"_id\":\"$amenity\", \"count\": {\"$sum\":1}}},\n {\"$sort\":{\"count\": -1}}, {\"$limit\":10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n# Connects to 'udwrangle' DB and returns DB object\ndef connectDB() :\n from pymongo import MongoClient\n client = MongoClient(\"mongodb://localhost:27017\")\n db = client.udwrangle\n return db\n\nif __name__ == \"__main__\":\n db = connectDB()\n #printAllStreetSuffixes(db)\n #printAllWithPostcodes(db)\n #printAllWithCounty(db)\n #printTop10AppearingAmenities(db)\n #printAllAmenities(db)\n #capacityOfAllCarparks(db)\n #pubsByContributor(db)\n #pubsWithBeerGardens(db)\n fastFoodByCuisine(db)\n\n\n",
"import pprint\nimport re\nfrom collections import defaultdict\n__author__ = 'ronanbrady2'\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef capacityOfAllCarparks(db):\n pipeline = [{'$match': {'amenity': 'parking'}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsWithBeerGardens(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$match': {'beer_garden':\n 'yes'}}, {'$group': {'_id': None, 'count': {'$sum': 1}}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\nif __name__ == '__main__':\n db = connectDB()\n fastFoodByCuisine(db)\n",
"<import token>\n__author__ = 'ronanbrady2'\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef capacityOfAllCarparks(db):\n pipeline = [{'$match': {'amenity': 'parking'}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsWithBeerGardens(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$match': {'beer_garden':\n 'yes'}}, {'$group': {'_id': None, 'count': {'$sum': 1}}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\nif __name__ == '__main__':\n db = connectDB()\n fastFoodByCuisine(db)\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef capacityOfAllCarparks(db):\n pipeline = [{'$match': {'amenity': 'parking'}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsWithBeerGardens(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$match': {'beer_garden':\n 'yes'}}, {'$group': {'_id': None, 'count': {'$sum': 1}}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\nif __name__ == '__main__':\n db = connectDB()\n fastFoodByCuisine(db)\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef capacityOfAllCarparks(db):\n pipeline = [{'$match': {'amenity': 'parking'}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsWithBeerGardens(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$match': {'beer_garden':\n 'yes'}}, {'$group': {'_id': None, 'count': {'$sum': 1}}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\n<function token>\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef pubsWithBeerGardens(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$match': {'beer_garden':\n 'yes'}}, {'$group': {'_id': None, 'count': {'$sum': 1}}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\ndef printAllAmenities(db):\n result = db.openmap.find({'amenity': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\n<function token>\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\ndef printAllWithCounty(db):\n result = db.openmap.find({'address.county': {'$exists': 'true'}}).count()\n pprint.pprint(result)\n\n\n<function token>\n<function token>\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\ndef printAllStreetSuffixes(db):\n pipeline = [{'$group': {'_id': '$address.street', 'count': {'$sum': 1}}\n }, {'$sort': {'_id': 1}}]\n result = db.openmap.aggregate(pipeline)\n valsfound = defaultdict(int)\n regx = re.compile('\\\\s(\\\\w+)$', re.IGNORECASE)\n for r in result:\n val = r['_id']\n if not val is None:\n i = regx.finditer(val)\n for match in i:\n streettype = match.group(0).strip()\n valsfound[streettype] += 1\n pprint.pprint(valsfound)\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\n<code token>\n",
"<import token>\n<assignment token>\n<function token>\n\n\ndef printAllWithPostcodes(db):\n result = db.openmap.find({'address.postcode': {'$exists': 'true'}})\n pprint.pprint(result)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\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\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n\n\ndef fastFoodByCuisine(db):\n pipeline = [{'$match': {'amenity': 'fast_food'}}, {'$group': {'_id':\n '$cuisine', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\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\n\ndef pubsByContributor(db):\n pipeline = [{'$match': {'amenity': 'pub'}}, {'$group': {'_id':\n '$created.user', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function token>\n<function token>\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\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<function token>\n<function token>\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\ndef connectDB():\n from pymongo import MongoClient\n client = MongoClient('mongodb://localhost:27017')\n db = client.udwrangle\n return db\n\n\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<function token>\n<function token>\n\n\ndef printTop10AppearingAmenities(db):\n pipeline = [{'$match': {'amenity': {'$exists': 'true'}}}, {'$group': {\n '_id': '$amenity', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}},\n {'$limit': 10}]\n result = db.openmap.aggregate(pipeline)\n for r in result:\n pprint.pprint(r)\n\n\n<function 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<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,990 | 9a75c2b9fed227b660a688bd3adf5b837e85af9e | class node():
def __init__(self):
self.child = [None]*26
self.flag = False
class trie():
def __init__(self):
self.root = node()
def gethash(self, key):
return ord(key)-ord("a")
def add(self, key):
nex = self.root
for char in list(key):
index = self.gethash(char)
#if index is none, create new node inside current node
if nex.child[index] == None:
nex.child[index] = node()
#if there is then a node, the focus move on to that node
nex = nex.child[index]
nex.flag = True
def search(self, key):
nex = self.root
for char in list(key):
index = self.gethash(char)
#if index is none, no node found
if nex.child[index] == None:
return False
#if there is then a node, the focus move on to that node
nex = nex.child[index]
return nex != None and nex.flag
def delete(self, key):
nex = self.root
for char in list(key):
index = self.gethash(char)
#if index is none, no node found
if nex.child[index] == None:
return False
#if there is then a node, the focus move on to that node
nex = nex.child[index]
nex.flag = False
return nex != None and nex.flag
def main():
# Input keys (use only 'a' through 'z' and lower case)
keys = ["the","a","there","answer","any",
"by","their"]
output = ["Not present in trie",
"Present in trie"]
# Trie object
t = trie()
# Construct trie
for key in keys:
t.add(key)
# Delete "the"
t.delete("the")
# Search for different keys
print("{} ---- {}".format("the",output[t.search("the")]))
print("{} ---- {}".format("these",output[t.search("these")]))
print("{} ---- {}".format("their",output[t.search("their")]))
print("{} ---- {}".format("thaw",output[t.search("thaw")]))
if __name__ == '__main__':
main() | [
"class node():\n\tdef __init__(self):\n\t\tself.child = [None]*26\n\t\tself.flag = False\n\nclass trie():\n\tdef __init__(self):\n\t\tself.root = node()\n\t\n\tdef gethash(self, key):\n\t\treturn ord(key)-ord(\"a\")\n\n\tdef add(self, key):\n\t\tnex = self.root\n\t\tfor char in list(key):\n\t\t\tindex = self.gethash(char)\n\t\t\t#if index is none, create new node inside current node\n\t\t\tif nex.child[index] == None:\n\t\t\t\tnex.child[index] = node()\n\t\t\t#if there is then a node, the focus move on to that node\n\t\t\tnex = nex.child[index]\n\t\tnex.flag = True\n\n\tdef search(self, key):\n\t\tnex = self.root\n\t\tfor char in list(key):\n\t\t\tindex = self.gethash(char)\n\t\t\t#if index is none, no node found\n\t\t\tif nex.child[index] == None:\n\t\t\t\treturn False\n\t\t\t#if there is then a node, the focus move on to that node\n\t\t\tnex = nex.child[index]\n\t\treturn nex != None and nex.flag\n\n\tdef delete(self, key):\n\t\tnex = self.root\n\t\tfor char in list(key):\n\t\t\tindex = self.gethash(char)\n\t\t\t#if index is none, no node found\n\t\t\tif nex.child[index] == None:\n\t\t\t\treturn False\n\t\t\t#if there is then a node, the focus move on to that node\n\t\t\tnex = nex.child[index]\n\t\tnex.flag = False\n\t\treturn nex != None and nex.flag\n\ndef main():\n\t# Input keys (use only 'a' through 'z' and lower case)\n\tkeys = [\"the\",\"a\",\"there\",\"answer\",\"any\",\n\t \"by\",\"their\"]\n\toutput = [\"Not present in trie\",\n\t \"Present in trie\"]\n\n\t# Trie object\n\tt = trie()\n\t\t\n\t# Construct trie\n\tfor key in keys:\n\t\tt.add(key)\n\t# Delete \"the\"\n\tt.delete(\"the\")\n\t\n\t# Search for different keys\n\tprint(\"{} ---- {}\".format(\"the\",output[t.search(\"the\")]))\n\tprint(\"{} ---- {}\".format(\"these\",output[t.search(\"these\")]))\n\tprint(\"{} ---- {}\".format(\"their\",output[t.search(\"their\")]))\n\tprint(\"{} ---- {}\".format(\"thaw\",output[t.search(\"thaw\")])) \n\nif __name__ == '__main__':\n\tmain()",
"class node:\n\n def __init__(self):\n self.child = [None] * 26\n self.flag = False\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n\n def delete(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n nex.flag = False\n return nex != None and nex.flag\n\n\ndef main():\n keys = ['the', 'a', 'there', 'answer', 'any', 'by', 'their']\n output = ['Not present in trie', 'Present in trie']\n t = trie()\n for key in keys:\n t.add(key)\n t.delete('the')\n print('{} ---- {}'.format('the', output[t.search('the')]))\n print('{} ---- {}'.format('these', output[t.search('these')]))\n print('{} ---- {}'.format('their', output[t.search('their')]))\n print('{} ---- {}'.format('thaw', output[t.search('thaw')]))\n\n\nif __name__ == '__main__':\n main()\n",
"class node:\n\n def __init__(self):\n self.child = [None] * 26\n self.flag = False\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n\n def delete(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n nex.flag = False\n return nex != None and nex.flag\n\n\ndef main():\n keys = ['the', 'a', 'there', 'answer', 'any', 'by', 'their']\n output = ['Not present in trie', 'Present in trie']\n t = trie()\n for key in keys:\n t.add(key)\n t.delete('the')\n print('{} ---- {}'.format('the', output[t.search('the')]))\n print('{} ---- {}'.format('these', output[t.search('these')]))\n print('{} ---- {}'.format('their', output[t.search('their')]))\n print('{} ---- {}'.format('thaw', output[t.search('thaw')]))\n\n\n<code token>\n",
"class node:\n\n def __init__(self):\n self.child = [None] * 26\n self.flag = False\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n\n def delete(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n nex.flag = False\n return nex != None and nex.flag\n\n\n<function token>\n<code token>\n",
"class node:\n <function token>\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n\n def delete(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n nex.flag = False\n return nex != None and nex.flag\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n\n def delete(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n nex.flag = False\n return nex != None and nex.flag\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n\n def add(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n nex.child[index] = node()\n nex = nex.child[index]\n nex.flag = True\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n <function token>\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n\n def __init__(self):\n self.root = node()\n\n def gethash(self, key):\n return ord(key) - ord('a')\n <function token>\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n <function token>\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n <function token>\n\n def gethash(self, key):\n return ord(key) - ord('a')\n <function token>\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n <function token>\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n <function token>\n <function token>\n <function token>\n\n def search(self, key):\n nex = self.root\n for char in list(key):\n index = self.gethash(char)\n if nex.child[index] == None:\n return False\n nex = nex.child[index]\n return nex != None and nex.flag\n <function token>\n\n\n<function token>\n<code token>\n",
"<class token>\n\n\nclass trie:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n",
"<class token>\n<class token>\n<function token>\n<code token>\n"
] | false |
99,991 | 07191eaf858d411c733666dea85de3400d32ca6d | taille = int(input("Saisir la taille du triangle: "))
for i in range (taille,0,-1):
print("*"*i)
| [
"taille = int(input(\"Saisir la taille du triangle: \"))\r\nfor i in range (taille,0,-1):\r\n print(\"*\"*i)\r\n ",
"taille = int(input('Saisir la taille du triangle: '))\nfor i in range(taille, 0, -1):\n print('*' * i)\n",
"<assignment token>\nfor i in range(taille, 0, -1):\n print('*' * i)\n",
"<assignment token>\n<code token>\n"
] | false |
99,992 | edcf3b16203c006e5bd9382593a8584de26114d5 | import common
import edify_generator
def AddAssertions(info):
edify = info.script
for i in xrange(len(edify.script)):
if ");" in edify.script[i] and ("ro.product.device" in edify.script[i] or "ro.build.product" in edify.script[i]):
edify.script[i] = edify.script[i].replace(");", ' || getprop("ro.product.device") == "C5303" || getprop("ro.build.product") == "c5303");')
return
def FullOTA_InstallEnd(info):
AddAssertions(info)
def IncrementalOTA_InstallEnd(info):
AddAssertions(info)
| [
"import common\nimport edify_generator\n\ndef AddAssertions(info):\n edify = info.script\n for i in xrange(len(edify.script)):\n if \");\" in edify.script[i] and (\"ro.product.device\" in edify.script[i] or \"ro.build.product\" in edify.script[i]):\n edify.script[i] = edify.script[i].replace(\");\", ' || getprop(\"ro.product.device\") == \"C5303\" || getprop(\"ro.build.product\") == \"c5303\");')\n return\n\ndef FullOTA_InstallEnd(info):\n AddAssertions(info)\n\ndef IncrementalOTA_InstallEnd(info):\n AddAssertions(info)\n",
"import common\nimport edify_generator\n\n\ndef AddAssertions(info):\n edify = info.script\n for i in xrange(len(edify.script)):\n if ');' in edify.script[i] and ('ro.product.device' in edify.script\n [i] or 'ro.build.product' in edify.script[i]):\n edify.script[i] = edify.script[i].replace(');',\n ' || getprop(\"ro.product.device\") == \"C5303\" || getprop(\"ro.build.product\") == \"c5303\");'\n )\n return\n\n\ndef FullOTA_InstallEnd(info):\n AddAssertions(info)\n\n\ndef IncrementalOTA_InstallEnd(info):\n AddAssertions(info)\n",
"<import token>\n\n\ndef AddAssertions(info):\n edify = info.script\n for i in xrange(len(edify.script)):\n if ');' in edify.script[i] and ('ro.product.device' in edify.script\n [i] or 'ro.build.product' in edify.script[i]):\n edify.script[i] = edify.script[i].replace(');',\n ' || getprop(\"ro.product.device\") == \"C5303\" || getprop(\"ro.build.product\") == \"c5303\");'\n )\n return\n\n\ndef FullOTA_InstallEnd(info):\n AddAssertions(info)\n\n\ndef IncrementalOTA_InstallEnd(info):\n AddAssertions(info)\n",
"<import token>\n<function token>\n\n\ndef FullOTA_InstallEnd(info):\n AddAssertions(info)\n\n\ndef IncrementalOTA_InstallEnd(info):\n AddAssertions(info)\n",
"<import token>\n<function token>\n\n\ndef FullOTA_InstallEnd(info):\n AddAssertions(info)\n\n\n<function token>\n",
"<import token>\n<function token>\n<function token>\n<function token>\n"
] | false |
99,993 | 4d5f8cb419277b87cad42a09632e81d63367fdcb | """Using datetime to make an app that will ask us math questions
and time our answers.
"""
from quiz import Quiz
# create class to keep track of quiz scores over time?
def main():
while True:
quiz_prompt = input('Do you want a math quiz? y/n')
if quiz_prompt.lower()[0] == 'y':
quiz1 = Quiz()
quiz1.take_quiz() # start quiz
elif quiz_prompt.lower()[0] == 'n':
print('Ok. Goodbye')
break
else:
print('Enter a valid input: y/n')
main()
| [
"\"\"\"Using datetime to make an app that will ask us math questions\nand time our answers.\n\"\"\"\nfrom quiz import Quiz\n \n \n# create class to keep track of quiz scores over time?\ndef main():\n while True:\n quiz_prompt = input('Do you want a math quiz? y/n')\n if quiz_prompt.lower()[0] == 'y':\n quiz1 = Quiz() \n quiz1.take_quiz() # start quiz\n elif quiz_prompt.lower()[0] == 'n':\n print('Ok. Goodbye')\n break\n else:\n print('Enter a valid input: y/n')\nmain()\n",
"<docstring token>\nfrom quiz import Quiz\n\n\ndef main():\n while True:\n quiz_prompt = input('Do you want a math quiz? y/n')\n if quiz_prompt.lower()[0] == 'y':\n quiz1 = Quiz()\n quiz1.take_quiz()\n elif quiz_prompt.lower()[0] == 'n':\n print('Ok. Goodbye')\n break\n else:\n print('Enter a valid input: y/n')\n\n\nmain()\n",
"<docstring token>\n<import token>\n\n\ndef main():\n while True:\n quiz_prompt = input('Do you want a math quiz? y/n')\n if quiz_prompt.lower()[0] == 'y':\n quiz1 = Quiz()\n quiz1.take_quiz()\n elif quiz_prompt.lower()[0] == 'n':\n print('Ok. Goodbye')\n break\n else:\n print('Enter a valid input: y/n')\n\n\nmain()\n",
"<docstring token>\n<import token>\n\n\ndef main():\n while True:\n quiz_prompt = input('Do you want a math quiz? y/n')\n if quiz_prompt.lower()[0] == 'y':\n quiz1 = Quiz()\n quiz1.take_quiz()\n elif quiz_prompt.lower()[0] == 'n':\n print('Ok. Goodbye')\n break\n else:\n print('Enter a valid input: y/n')\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<function token>\n<code token>\n"
] | false |
99,994 | c3b34cf17b04a9611e348363537371ead6cefe2a | # koomar is a simple IRC bot written for fun.
# Grab your updates from: http://github.com/anandkunal/koomar/
# Peep the IRC RFC: http://www.irchelp.org/irchelp/rfc/rfc.html
import datetime
import random
import socket
import re
import time
import lib
from lib import Message, flatten
server = "irc.freenode.net"
channel = "whatspop"
nickname = "koomar"
port = 6667
command = "koomar"
# Used to send admin commands to koomar
password = "test"
quotes = ["Stop exploding, you cowards!", "Take a dip!"]
class Koomar:
def __init__(self, server, channel, nickname, password, port, command, auto_connect = False):
"""Establish beginning variables and start the socket."""
self.server = server
self.channel = channel
self.nickname = nickname
self.password = password
self.port = port
self.command = command
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# List of functions to call when processing a post
self.functions = []
if auto_connect:
self.connect()
def __del__(self):
self.disconnect()
def connect(self):
self.irc.connect((self.server, self.port))
self.buffer = self.irc.recv(4096)
self.irc.send("NICK %s\r\n" % self.nickname)
self.irc.send("USER %s %s %s :%s\r\n" % \
(self.nickname, self.nickname, self.nickname, self.nickname))
self.irc.send("JOIN #%s\r\n" % self.channel)
self.send_message("%s is in the house!" % (self.nickname))
self.loop()
def add_function(self, function):
"""Add a processing function."""
self.functions.append(function)
def loop(self):
while 1:
self.buffer += self.irc.recv(4096)
temp_buffer = self.buffer.split("\n")
self.buffer = temp_buffer.pop()
for line in temp_buffer:
responses = []
# Stubbing out functionality for custom functions. Eventually the big block below will be gone.
for function in flatten(self.functions):
try:
responses.append(function(self, line))
except IndexError:
# I put this in here just to be safe. (Dirk)
pass
# Standard control library
try:
message = Message(line)
except IndexError:
pass
line = line.strip().split()
if line[0] == "PING":
self.irc.send("PONG %s\r\n" % line[1])
else:
try:
# Disconnect functionality (revisited)
command = message.command(self.command)
if command.__str__() == 'disconnect':
if not message.argv(self.command) == self.password:
if message.is_public():
koomar.send_message('Incorrect password.')
else:
koomar.send_private_message("Dear %s, you gave an invalid password." % message.sender, message.sender)
else:
koomar.send_message('Correct password. Disconnecting...')
self.disconnect()
return
if line[3] == ":%s" % (self.command):
if len(line) <= 4:
self.send_message("Type `%s quote`" % (self.command))
else:
pass
#if line[4] == "disconnect":
# if line[5] == self.password:
# self.disconnect()
# return
# else:
# if not line[2].startswith('#'):
# matches = re.match(':([A-Za-z0-9_-]+)!', line[0])
# sender = matches.groups()[0]
# self.send_private_message("Dear %s, you gave an invalid password." % sender, sender)
# else:
# self.send_message("Invalid password.")
#if not responses.__contains__(True):
#self.send_message("I don't know that command!")
except IndexError:
pass # Each line may not be a conversation
def disconnect(self):
self.irc.close()
def send_message(self, message):
self.irc.send("PRIVMSG #%s :%s\r\n" % (self.channel, message))
def send_private_message(self, message, recipient):
self.irc.send("PRIVMSG %s :%s\r\n" % (recipient, message))
koomar = Koomar(server, channel, nickname, password, port, command)
def quote_parser(koomar, line):
message = Message(line)
command = message.command(koomar.command)
if command == 'quote':
rand = random.randint(0, len(quotes)-1)
quote = quotes[rand]
if message.is_public():
koomar.send_message("\"%s\"" % quote)
else:
koomar.send_private_message("\"%s\"" % quote, message.sender)
return True
def help_parser(koomar, line):
message = Message(line)
command = message.command(koomar.command)
help = \
"""Koomar is a currently in development IRC bot.
Type in 'koomar quote' to get a random Futurama quote."""
if command == 'help':
if message.is_public():
for line in help.split('\n'):
koomar.send_message(line)
else:
for line in help.split('\n'):
koomar.send_private_message(line, message.sender)
return True
koomar.add_function([quote_parser, help_parser])
koomar.connect()
| [
"# koomar is a simple IRC bot written for fun.\n# Grab your updates from: http://github.com/anandkunal/koomar/\n# Peep the IRC RFC: http://www.irchelp.org/irchelp/rfc/rfc.html\n\nimport datetime\nimport random\nimport socket\nimport re\nimport time\n\nimport lib\nfrom lib import Message, flatten\n\nserver = \"irc.freenode.net\"\nchannel = \"whatspop\"\nnickname = \"koomar\"\nport = 6667\ncommand = \"koomar\"\n# Used to send admin commands to koomar\npassword = \"test\"\n\nquotes = [\"Stop exploding, you cowards!\", \"Take a dip!\"]\n\nclass Koomar:\n def __init__(self, server, channel, nickname, password, port, command, auto_connect = False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # List of functions to call when processing a post\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send(\"NICK %s\\r\\n\" % self.nickname)\n self.irc.send(\"USER %s %s %s :%s\\r\\n\" % \\\n (self.nickname, self.nickname, self.nickname, self.nickname))\n self.irc.send(\"JOIN #%s\\r\\n\" % self.channel)\n self.send_message(\"%s is in the house!\" % (self.nickname))\n self.loop()\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split(\"\\n\")\n self.buffer = temp_buffer.pop()\n\n for line in temp_buffer:\n responses = []\n # Stubbing out functionality for custom functions. Eventually the big block below will be gone.\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n # I put this in here just to be safe. (Dirk)\n pass\n # Standard control library\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == \"PING\":\n self.irc.send(\"PONG %s\\r\\n\" % line[1])\n else:\n try:\n # Disconnect functionality (revisited)\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\"Dear %s, you gave an invalid password.\" % message.sender, message.sender)\n else:\n koomar.send_message('Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == \":%s\" % (self.command):\n if len(line) <= 4:\n self.send_message(\"Type `%s quote`\" % (self.command))\n else:\n pass\n #if line[4] == \"disconnect\":\n # if line[5] == self.password:\n # self.disconnect()\n # return\n # else:\n # if not line[2].startswith('#'):\n # matches = re.match(':([A-Za-z0-9_-]+)!', line[0])\n # sender = matches.groups()[0]\n # self.send_private_message(\"Dear %s, you gave an invalid password.\" % sender, sender)\n # else:\n # self.send_message(\"Invalid password.\")\n #if not responses.__contains__(True):\n #self.send_message(\"I don't know that command!\")\n except IndexError:\n pass # Each line may not be a conversation \n def disconnect(self):\n self.irc.close()\n def send_message(self, message):\n self.irc.send(\"PRIVMSG #%s :%s\\r\\n\" % (self.channel, message))\n def send_private_message(self, message, recipient):\n self.irc.send(\"PRIVMSG %s :%s\\r\\n\" % (recipient, message))\n \nkoomar = Koomar(server, channel, nickname, password, port, command)\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes)-1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message(\"\\\"%s\\\"\" % quote)\n else:\n koomar.send_private_message(\"\\\"%s\\\"\" % quote, message.sender)\n return True\ndef help_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n help = \\\n\"\"\"Koomar is a currently in development IRC bot.\nType in 'koomar quote' to get a random Futurama quote.\"\"\"\n if command == 'help':\n if message.is_public():\n for line in help.split('\\n'):\n koomar.send_message(line)\n else:\n for line in help.split('\\n'):\n koomar.send_private_message(line, message.sender)\n return True\nkoomar.add_function([quote_parser, help_parser])\nkoomar.connect()\n\n\n\n",
"import datetime\nimport random\nimport socket\nimport re\nimport time\nimport lib\nfrom lib import Message, flatten\nserver = 'irc.freenode.net'\nchannel = 'whatspop'\nnickname = 'koomar'\nport = 6667\ncommand = 'koomar'\npassword = 'test'\nquotes = ['Stop exploding, you cowards!', 'Take a dip!']\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\nkoomar = Koomar(server, channel, nickname, password, port, command)\n\n\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes) - 1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message('\"%s\"' % quote)\n else:\n koomar.send_private_message('\"%s\"' % quote, message.sender)\n return True\n\n\ndef help_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n help = \"\"\"Koomar is a currently in development IRC bot.\nType in 'koomar quote' to get a random Futurama quote.\"\"\"\n if command == 'help':\n if message.is_public():\n for line in help.split('\\n'):\n koomar.send_message(line)\n else:\n for line in help.split('\\n'):\n koomar.send_private_message(line, message.sender)\n return True\n\n\nkoomar.add_function([quote_parser, help_parser])\nkoomar.connect()\n",
"<import token>\nserver = 'irc.freenode.net'\nchannel = 'whatspop'\nnickname = 'koomar'\nport = 6667\ncommand = 'koomar'\npassword = 'test'\nquotes = ['Stop exploding, you cowards!', 'Take a dip!']\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\nkoomar = Koomar(server, channel, nickname, password, port, command)\n\n\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes) - 1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message('\"%s\"' % quote)\n else:\n koomar.send_private_message('\"%s\"' % quote, message.sender)\n return True\n\n\ndef help_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n help = \"\"\"Koomar is a currently in development IRC bot.\nType in 'koomar quote' to get a random Futurama quote.\"\"\"\n if command == 'help':\n if message.is_public():\n for line in help.split('\\n'):\n koomar.send_message(line)\n else:\n for line in help.split('\\n'):\n koomar.send_private_message(line, message.sender)\n return True\n\n\nkoomar.add_function([quote_parser, help_parser])\nkoomar.connect()\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\n<assignment token>\n\n\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes) - 1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message('\"%s\"' % quote)\n else:\n koomar.send_private_message('\"%s\"' % quote, message.sender)\n return True\n\n\ndef help_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n help = \"\"\"Koomar is a currently in development IRC bot.\nType in 'koomar quote' to get a random Futurama quote.\"\"\"\n if command == 'help':\n if message.is_public():\n for line in help.split('\\n'):\n koomar.send_message(line)\n else:\n for line in help.split('\\n'):\n koomar.send_private_message(line, message.sender)\n return True\n\n\nkoomar.add_function([quote_parser, help_parser])\nkoomar.connect()\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\n<assignment token>\n\n\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes) - 1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message('\"%s\"' % quote)\n else:\n koomar.send_private_message('\"%s\"' % quote, message.sender)\n return True\n\n\ndef help_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n help = \"\"\"Koomar is a currently in development IRC bot.\nType in 'koomar quote' to get a random Futurama quote.\"\"\"\n if command == 'help':\n if message.is_public():\n for line in help.split('\\n'):\n koomar.send_message(line)\n else:\n for line in help.split('\\n'):\n koomar.send_private_message(line, message.sender)\n return True\n\n\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\n<assignment token>\n\n\ndef quote_parser(koomar, line):\n message = Message(line)\n command = message.command(koomar.command)\n if command == 'quote':\n rand = random.randint(0, len(quotes) - 1)\n quote = quotes[rand]\n if message.is_public():\n koomar.send_message('\"%s\"' % quote)\n else:\n koomar.send_private_message('\"%s\"' % quote, message.sender)\n return True\n\n\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n\n def __init__(self, server, channel, nickname, password, port, command,\n auto_connect=False):\n \"\"\"Establish beginning variables and start the socket.\"\"\"\n self.server = server\n self.channel = channel\n self.nickname = nickname\n self.password = password\n self.port = port\n self.command = command\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.functions = []\n if auto_connect:\n self.connect()\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n\n def send_private_message(self, message, recipient):\n self.irc.send('PRIVMSG %s :%s\\r\\n' % (recipient, message))\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n\n def __del__(self):\n self.disconnect()\n\n def connect(self):\n self.irc.connect((self.server, self.port))\n self.buffer = self.irc.recv(4096)\n self.irc.send('NICK %s\\r\\n' % self.nickname)\n self.irc.send('USER %s %s %s :%s\\r\\n' % (self.nickname, self.\n nickname, self.nickname, self.nickname))\n self.irc.send('JOIN #%s\\r\\n' % self.channel)\n self.send_message('%s is in the house!' % self.nickname)\n self.loop()\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n\n def __del__(self):\n self.disconnect()\n <function token>\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n\n def disconnect(self):\n self.irc.close()\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n\n def __del__(self):\n self.disconnect()\n <function token>\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n <function token>\n\n def send_message(self, message):\n self.irc.send('PRIVMSG #%s :%s\\r\\n' % (self.channel, message))\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n\n def __del__(self):\n self.disconnect()\n <function token>\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n <function token>\n <function token>\n\n def add_function(self, function):\n \"\"\"Add a processing function.\"\"\"\n self.functions.append(function)\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\n <function token>\n <function token>\n <function token>\n <function token>\n\n def loop(self):\n while 1:\n self.buffer += self.irc.recv(4096)\n temp_buffer = self.buffer.split('\\n')\n self.buffer = temp_buffer.pop()\n for line in temp_buffer:\n responses = []\n for function in flatten(self.functions):\n try:\n responses.append(function(self, line))\n except IndexError:\n pass\n try:\n message = Message(line)\n except IndexError:\n pass\n line = line.strip().split()\n if line[0] == 'PING':\n self.irc.send('PONG %s\\r\\n' % line[1])\n else:\n try:\n command = message.command(self.command)\n if command.__str__() == 'disconnect':\n if not message.argv(self.command) == self.password:\n if message.is_public():\n koomar.send_message('Incorrect password.')\n else:\n koomar.send_private_message(\n 'Dear %s, you gave an invalid password.'\n % message.sender, message.sender)\n else:\n koomar.send_message(\n 'Correct password. Disconnecting...')\n self.disconnect()\n return\n if line[3] == ':%s' % self.command:\n if len(line) <= 4:\n self.send_message('Type `%s quote`' % self.\n command)\n else:\n pass\n except IndexError:\n pass\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n\n\nclass Koomar:\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<assignment token>\n<function token>\n<function token>\n<code token>\n",
"<import token>\n<assignment token>\n<class token>\n<assignment token>\n<function token>\n<function token>\n<code token>\n"
] | false |
99,995 | c11fd5bcba3242216a26bba364888ca95160da35 | # -*- coding: utf-8 -*-
# encoding=utf8
import sys
from flask import Flask, render_template, request, redirect, url_for, session
import sqlite3
import datetime
import os
import random
import re
##burasi hacky. py3 de gerekmiyor ve bu da onerilmiyor
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__)
myDatabase = 'sozluk.db'
app.secret_key = os.urandom(24)
#reading is done here
@app.route('/')
def index():
return redirect(url_for('rastgele'))
@app.route('/logg')
def logg():
if 'user' in session:
return 'already logged in'
else:
return render_template('login.html')
#login
@app.route('/login', methods=['POST'])
def login():
user = request.form['username']
password = request.form['password']
if (user == 'badi' and password == '123456'):
session['user'] = 'badi'
#return 'username %s - password %s' % (user, password)
return redirect(url_for('index'))
else:
return 'gtfo'
#create
@app.route('/create', methods=['POST'])
def create():
if 'user' in session:
icerik = request.form['icerik']
baslik = request.form['baslik']
#baslik = baslik.replace('\n', '<br>')
tarih = str(datetime.datetime.now())
tarih = tarih[0:10]
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('insert into data(baslik, icerik, tarih) values(?,?,?)', (baslik, icerik, tarih))
conn.commit()
#return redirect(url_for('index'))
return redirect(url_for('read', baslik=baslik))
else:
return 'gtfo'
#update
@app.route('/update/<int:entry_id>')
def update(entry_id):
#take from database
if 'user' in session:
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select * from data where id = ?', [entry_id])
result = c.fetchone()
return render_template('edit.html', icerik=result)
else:
return 'gtfo'
#edit
@app.route('/edit', methods=['POST'])
def edit():
if 'user' in session:
icerik = request.form['icerik']
entry_id = request.form['entry_id']
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('update data set icerik = ? where id = ?', (icerik, entry_id))
conn.commit()
c.execute('select baslik from data where id = ?', [entry_id])
baslik = c.fetchone()
#return redirect(url_for('index'))
return redirect(url_for('read', baslik=baslik[0]))
else:
return 'gtfo'
#read
@app.route('/read/<baslik>')
def read(baslik):
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select * from data where baslik = ?', [baslik])
result = list(c.fetchall())
result = map(lambda x:list(x), result) #result=[list(x) for x in result]
for record in result:
record[2] = record[2].replace('\r\n','<br>')
#mylist = re.findall(r'\(bkz: ([^\).]*)\)', record[2])
mylist = re.findall(r'\(bkz: ([^\)]*)\)', record[2])
for element in mylist:
#print element
toReplace = "(bkz: " + element + ")"
newtext = "(bkz: <a href='/read/" + element.encode('utf-8') + "'>" + element.encode('utf-8')+ "</a>)"
record[2] = record[2].replace(toReplace, newtext)
#bu yukarida yapilan islem aslinda su once bkz lari buluyorum ve bi yere atiyorum. sonra o attigim yer icinde donerken onu neyle replace
#edecegimi de olusturup orada on the fly replace yapiyorum
#asagida da aynisi gizli bkz icin yapiliyor
mylist = re.findall(r'[^[]*\[([^]]*)\]', record[2])
for element in mylist:
toReplace = "[" + element + "]"
newtext = "<a href='/read/" + element.encode('utf-8') + "'>" + element.encode('utf-8') + "</a>"
record[2] = record[2].replace(toReplace, newtext)
#simdi linkler icin
mylist = re.findall(r'\(link: ([^\)]*)\)', record[2])
for element in mylist:
print element
toReplace = "(link: " + element + ")"
newtext = "<a href='" + element.encode('utf-8') + "'>link!</a>"
record[2] = record[2].replace(toReplace, newtext)
return render_template('read.html', data=baslik, icerik=result)
#yukarıda read de list ekledim. list ekledim ki icinde degisiklik yapayim yoksa tuple diyip hata veriyodu - immutable
#read id
@app.route('/oku/<entry_id>')
def oku(entry_id):
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select baslik from data where id = ?', [entry_id])
baslik = c.fetchone()
c.execute('select * from data where id = ?', [entry_id])
result = c.fetchall()
#c.execute('select * from data where baslik = ?', [baslik])
#result = list(c.fetchall())
result = map(lambda x:list(x), result) #result=[list(x) for x in result]
for record in result:
record[2] = record[2].replace('\r\n','<br>')
#mylist = re.findall(r'\(bkz: ([^\).]*)\)', record[2])
mylist = re.findall(r'\(bkz: ([^\)]*)\)', record[2])
for element in mylist:
#print element
toReplace = "(bkz: " + element + ")"
newtext = "(bkz: <a href='/read/" + element.encode('utf-8') + "'>" + element.encode('utf-8')+ "</a>)"
record[2] = record[2].replace(toReplace, newtext)
#bu yukarida yapilan islem aslinda su once bkz lari buluyorum ve bi yere atiyorum. sonra o attigim yer icinde donerken onu neyle replace
#edecegimi de olusturup orada on the fly replace yapiyorum
#asagida da aynisi gizli bkz icin yapiliyor
mylist = re.findall(r'[^[]*\[([^]]*)\]', record[2])
for element in mylist:
toReplace = "[" + element + "]"
newtext = "<a href='/read/" + element.encode('utf-8') + "'>" + element.encode('utf-8') + "</a>"
record[2] = record[2].replace(toReplace, newtext)
#simdi linkler icin
mylist = re.findall(r'\(link: ([^\)]*)\)', record[2])
for element in mylist:
print element
toReplace = "(link: " + element + ")"
newtext = "<a href='http://" + element.encode('utf-8') + "'>link!</a>"
record[2] = record[2].replace(toReplace, newtext)
return render_template('oku.html', data=baslik, icerik=result)
#return render_template('oku.html', icerik=result, data=baslik)
#delete
@app.route('/delete/<int:entry_id>')
def delete(entry_id):
#connect db
if 'user' in session:
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select baslik from data where id = ?', [entry_id])
baslik = c.fetchone()
c.execute('delete from data where id = ?', [entry_id])
conn.commit()
return redirect(url_for('read', baslik=baslik[0])) #cunku fetchone gelince unicode falan geliyorud
else:
return 'gtfo'
#tum basliklar
@app.route('/tumu')
def tumu():
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select * from data group by baslik order by tarih desc')
result = c.fetchall()
return render_template('tumu.html', icerik=result)
#basit arama
@app.route('/ara', methods=['POST'])
def ara():
baslik = request.form['arama']
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
#c.execute('select * from data where baslik = ?', [baslik])
#baslik_out = baslik
#result = c.fetchall()
#return render_template('read.html', data=baslik_out, icerik=result)
#return redirect(url_for(read(baslik))
return redirect(url_for('read', baslik=baslik)) #cunku fetchone gelince unicode falan geliyorud
#rastgele baslik
@app.route('/rastgele')
def rastgele():
conn = sqlite3.connect(myDatabase)
c = conn.cursor()
c.execute('select baslik from data group by baslik order by random()')
baslik_out = c.fetchone()
baslik_out = baslik_out[0]
return redirect(url_for('read', baslik=baslik_out))
#logout
@app.route('/logout')
def logout():
session.pop('user', None)
return 'logged out, bye'
if __name__ == "__main__":
app.run(debug=True)
| [
"# -*- coding: utf-8 -*-\r\n# encoding=utf8 \r\nimport sys\r\nfrom flask import Flask, render_template, request, redirect, url_for, session\r\nimport sqlite3\r\nimport datetime\r\nimport os\r\nimport random\r\nimport re\r\n\r\n##burasi hacky. py3 de gerekmiyor ve bu da onerilmiyor\r\nreload(sys) \r\nsys.setdefaultencoding('utf8')\r\n\r\napp = Flask(__name__)\r\nmyDatabase = 'sozluk.db'\r\napp.secret_key = os.urandom(24)\r\n\r\n\r\n#reading is done here\r\n@app.route('/')\r\ndef index():\r\n\treturn redirect(url_for('rastgele'))\r\n\r\n\r\n@app.route('/logg')\r\ndef logg():\r\n\tif 'user' in session:\r\n\t\treturn 'already logged in'\r\n\telse:\r\n\t\treturn render_template('login.html')\r\n\r\n\r\n#login\r\n@app.route('/login', methods=['POST'])\r\ndef login():\r\n\tuser = request.form['username']\r\n\tpassword = request.form['password']\r\n\tif (user == 'badi' and password == '123456'):\r\n\t\tsession['user'] = 'badi'\r\n\t\t#return 'username %s - password %s' % (user, password)\r\n\t\treturn redirect(url_for('index'))\r\n\telse:\r\n\t\treturn 'gtfo'\r\n\r\n\r\n#create\r\n@app.route('/create', methods=['POST'])\r\ndef create():\r\n\tif 'user' in session:\r\n\t\ticerik = request.form['icerik']\r\n\t\tbaslik = request.form['baslik']\r\n\t\t#baslik = baslik.replace('\\n', '<br>')\r\n\t\ttarih = str(datetime.datetime.now())\r\n\t\ttarih = tarih[0:10]\r\n\t\tconn = sqlite3.connect(myDatabase)\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('insert into data(baslik, icerik, tarih) values(?,?,?)', (baslik, icerik, tarih))\r\n\t\tconn.commit()\r\n\t\t#return redirect(url_for('index'))\r\n\t\treturn redirect(url_for('read', baslik=baslik))\r\n\telse:\r\n\t\treturn 'gtfo'\r\n\r\n\r\n#update\r\n@app.route('/update/<int:entry_id>')\r\ndef update(entry_id):\r\n\t#take from database\r\n\tif 'user' in session:\r\n\t\tconn = sqlite3.connect(myDatabase)\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('select * from data where id = ?', [entry_id])\r\n\t\tresult = c.fetchone()\r\n\t\treturn render_template('edit.html', icerik=result)\r\n\telse:\r\n\t\treturn 'gtfo'\r\n\r\n\r\n#edit\r\n@app.route('/edit', methods=['POST'])\r\ndef edit():\r\n\tif 'user' in session:\r\n\t\ticerik = request.form['icerik']\r\n\t\tentry_id = request.form['entry_id']\r\n\t\tconn = sqlite3.connect(myDatabase)\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('update data set icerik = ? where id = ?', (icerik, entry_id))\r\n\t\tconn.commit()\r\n\t\tc.execute('select baslik from data where id = ?', [entry_id])\r\n\t\tbaslik = c.fetchone()\r\n\t\t#return redirect(url_for('index'))\r\n\t\treturn redirect(url_for('read', baslik=baslik[0]))\r\n\r\n\telse:\r\n\t\treturn 'gtfo'\r\n\r\n#read\r\n@app.route('/read/<baslik>')\r\ndef read(baslik):\r\n\tconn = sqlite3.connect(myDatabase)\r\n\tc = conn.cursor()\r\n\tc.execute('select * from data where baslik = ?', [baslik])\r\n\tresult = list(c.fetchall())\r\n\tresult = map(lambda x:list(x), result) #result=[list(x) for x in result]\r\n\tfor record in result:\r\n\t\trecord[2] = record[2].replace('\\r\\n','<br>')\r\n\r\n\t\t#mylist = re.findall(r'\\(bkz: ([^\\).]*)\\)', record[2])\r\n\t\tmylist = re.findall(r'\\(bkz: ([^\\)]*)\\)', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\t#print element\r\n\t\t\ttoReplace = \"(bkz: \" + element + \")\"\r\n\t\t\tnewtext = \"(bkz: <a href='/read/\" + element.encode('utf-8') + \"'>\" + element.encode('utf-8')+ \"</a>)\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\t\t#bu yukarida yapilan islem aslinda su once bkz lari buluyorum ve bi yere atiyorum. sonra o attigim yer icinde donerken onu neyle replace\r\n\t\t#edecegimi de olusturup orada on the fly replace yapiyorum\r\n\t\t#asagida da aynisi gizli bkz icin yapiliyor\r\n\t\tmylist = re.findall(r'[^[]*\\[([^]]*)\\]', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\ttoReplace = \"[\" + element + \"]\"\r\n\t\t\tnewtext = \"<a href='/read/\" + element.encode('utf-8') + \"'>\" + element.encode('utf-8') + \"</a>\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\r\n\t\t#simdi linkler icin\r\n\t\tmylist = re.findall(r'\\(link: ([^\\)]*)\\)', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\tprint element\r\n\t\t\ttoReplace = \"(link: \" + element + \")\"\r\n\t\t\tnewtext = \"<a href='\" + element.encode('utf-8') + \"'>link!</a>\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\treturn render_template('read.html', data=baslik, icerik=result)\r\n\r\n#yukarıda read de list ekledim. list ekledim ki icinde degisiklik yapayim yoksa tuple diyip hata veriyodu - immutable\r\n\r\n#read id\r\n@app.route('/oku/<entry_id>')\r\ndef oku(entry_id):\r\n\tconn = sqlite3.connect(myDatabase)\r\n\tc = conn.cursor()\r\n\tc.execute('select baslik from data where id = ?', [entry_id])\r\n\tbaslik = c.fetchone()\r\n\tc.execute('select * from data where id = ?', [entry_id])\r\n\tresult = c.fetchall()\r\n\t#c.execute('select * from data where baslik = ?', [baslik])\r\n\t#result = list(c.fetchall())\r\n\tresult = map(lambda x:list(x), result) #result=[list(x) for x in result]\r\n\tfor record in result:\r\n\t\trecord[2] = record[2].replace('\\r\\n','<br>')\r\n\r\n\t\t#mylist = re.findall(r'\\(bkz: ([^\\).]*)\\)', record[2])\r\n\t\tmylist = re.findall(r'\\(bkz: ([^\\)]*)\\)', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\t#print element\r\n\t\t\ttoReplace = \"(bkz: \" + element + \")\"\r\n\t\t\tnewtext = \"(bkz: <a href='/read/\" + element.encode('utf-8') + \"'>\" + element.encode('utf-8')+ \"</a>)\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\t\t#bu yukarida yapilan islem aslinda su once bkz lari buluyorum ve bi yere atiyorum. sonra o attigim yer icinde donerken onu neyle replace\r\n\t\t#edecegimi de olusturup orada on the fly replace yapiyorum\r\n\t\t#asagida da aynisi gizli bkz icin yapiliyor\r\n\t\tmylist = re.findall(r'[^[]*\\[([^]]*)\\]', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\ttoReplace = \"[\" + element + \"]\"\r\n\t\t\tnewtext = \"<a href='/read/\" + element.encode('utf-8') + \"'>\" + element.encode('utf-8') + \"</a>\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\r\n\t\t#simdi linkler icin\r\n\t\tmylist = re.findall(r'\\(link: ([^\\)]*)\\)', record[2])\r\n\t\tfor element in mylist:\r\n\t\t\tprint element\r\n\t\t\ttoReplace = \"(link: \" + element + \")\"\r\n\t\t\tnewtext = \"<a href='http://\" + element.encode('utf-8') + \"'>link!</a>\"\r\n\t\t\trecord[2] = record[2].replace(toReplace, newtext)\r\n\treturn render_template('oku.html', data=baslik, icerik=result)\r\n\t#return render_template('oku.html', icerik=result, data=baslik)\r\n\r\n\r\n#delete\r\n@app.route('/delete/<int:entry_id>')\r\ndef delete(entry_id):\r\n\t#connect db\r\n\tif 'user' in session:\r\n\t\tconn = sqlite3.connect(myDatabase)\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('select baslik from data where id = ?', [entry_id])\r\n\t\tbaslik = c.fetchone()\r\n\t\tc.execute('delete from data where id = ?', [entry_id])\r\n\t\tconn.commit()\r\n\t\treturn redirect(url_for('read', baslik=baslik[0])) #cunku fetchone gelince unicode falan geliyorud\r\n\telse:\r\n\t\treturn 'gtfo'\r\n\r\n\r\n#tum basliklar\r\n@app.route('/tumu')\r\ndef tumu():\r\n\tconn = sqlite3.connect(myDatabase)\r\n\tc = conn.cursor()\r\n\tc.execute('select * from data group by baslik order by tarih desc')\r\n\tresult = c.fetchall()\r\n\treturn render_template('tumu.html', icerik=result)\r\n\r\n\r\n#basit arama\r\n@app.route('/ara', methods=['POST'])\r\ndef ara():\r\n\tbaslik = request.form['arama']\r\n\tconn = sqlite3.connect(myDatabase)\r\n\tc = conn.cursor()\r\n\t#c.execute('select * from data where baslik = ?', [baslik])\r\n\t#baslik_out = baslik\r\n\t#result = c.fetchall()\t\r\n\t#return render_template('read.html', data=baslik_out, icerik=result)\r\n\t#return redirect(url_for(read(baslik))\r\n\treturn redirect(url_for('read', baslik=baslik)) #cunku fetchone gelince unicode falan geliyorud\r\n\r\n#rastgele baslik\r\n@app.route('/rastgele')\r\ndef rastgele():\r\n\tconn = sqlite3.connect(myDatabase)\r\n\tc = conn.cursor()\r\n\tc.execute('select baslik from data group by baslik order by random()')\r\n\tbaslik_out = c.fetchone()\r\n\tbaslik_out = baslik_out[0]\r\n\treturn redirect(url_for('read', baslik=baslik_out))\r\n\r\n#logout\r\n@app.route('/logout')\r\ndef logout():\r\n\tsession.pop('user', None)\r\n\treturn 'logged out, bye'\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tapp.run(debug=True)\r\n"
] | true |
99,996 | eca1c5bec2249f529d878c3b9768c4611ccb1e64 | from selenium import webdriver
import requests
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup
import urlparse, random
import argparse,os
key = "badoo.com"
driver = webdriver.PhantomJS()
driver.set_window_size(1280,800)
driver.get('https://badoo.com/')
Main_window = driver.window_handles[0]
LoginButtonID = driver.find_element_by_xpath('//*[@id="homepage-header"]/div/div[2]/div/div/div[1]/a')
LoginButtonID.click()
print 'Arrived at BADOO.com'
Popup_window = driver.window_handles[1]
driver.switch_to_window(Popup_window)
print 'Login with facebook...'
EmailID = driver.find_element_by_id('email')
PasswordID = driver.find_element_by_id('pass')
LoginPopupID = driver.find_element_by_id('u_0_2')
print 'Facebook parameters entered...'
EmailID.clear()
PasswordID.clear()
EmailID.send_keys('brianformento@hotmail.co.uk')
PasswordID.send_keys('')
LoginPopupID.click()
print 'Facebook Authorized...'
driver.switch_to_window(Main_window)
time.sleep(5)
print "###login Successful###"
driver.refresh()
driver.back()
App = driver.find_element_by_id('app_c')
var = 0
time.sleep(5)
page = BeautifulSoup(driver.page_source,"html.parser")
print 'brute force enabled...'
while var < 15:
url = driver.page_source
page = BeautifulSoup(url, "html.parser")
headis = page.h1
time.sleep(0.5)
#a = headis.span
#in_html = a.contents
#time.sleep(0.5)
### detect popup nad refresh
if page.findAll('i', {'class',('icon icon--white js-ovl-close')}) in page:
print 'ALUUHABARR'
#under_h1 = page.findAll("span",{'class': 'flex__item flex__item--dynamic ellipsis'})
#print under_h1
place = 0
for all_in_header in headis.findAll('span'):
if place == 0:
name = all_in_header.text
if place == 1:
age = all_in_header.text
place +=1
print 'likeing:', name, 'Age:', age
App.send_keys(Keys.NUMPAD1)
var +=1
if var == 14:
driver.quit()
var = 0
''' to get a content in position after header i use a LoginPopupID
should be a better way, but didnt find it, probs with contents[1]'''
#for span in all_span_elements.findAll('span'):
#print span
#driver.quit()
print "END"
driver.quit()
'''
print driver.current_url, 'likeing:'
App.send_keys(Keys.NUMPAD1)
var+=1
if var == 9:
driver.refresh()
print driver.current_url + "alukabar"
#driver.quit()
''' | [
"from selenium import webdriver\r\nimport requests\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport urlparse, random\r\nimport argparse,os\r\nkey = \"badoo.com\"\r\ndriver = webdriver.PhantomJS()\r\n\r\ndriver.set_window_size(1280,800)\r\ndriver.get('https://badoo.com/')\r\n\r\n\r\nMain_window = driver.window_handles[0]\r\nLoginButtonID = driver.find_element_by_xpath('//*[@id=\"homepage-header\"]/div/div[2]/div/div/div[1]/a')\r\nLoginButtonID.click()\r\nprint 'Arrived at BADOO.com'\r\nPopup_window = driver.window_handles[1]\r\ndriver.switch_to_window(Popup_window)\r\nprint 'Login with facebook...'\r\n\r\n\r\n\r\nEmailID = driver.find_element_by_id('email')\r\nPasswordID = driver.find_element_by_id('pass')\r\nLoginPopupID = driver.find_element_by_id('u_0_2')\r\nprint 'Facebook parameters entered...'\r\nEmailID.clear()\r\nPasswordID.clear()\r\nEmailID.send_keys('brianformento@hotmail.co.uk')\r\nPasswordID.send_keys('')\r\nLoginPopupID.click()\r\nprint 'Facebook Authorized...'\r\ndriver.switch_to_window(Main_window)\r\ntime.sleep(5)\r\nprint \"###login Successful###\"\r\n\r\ndriver.refresh()\r\ndriver.back()\r\n\r\nApp = driver.find_element_by_id('app_c')\r\nvar = 0\r\ntime.sleep(5)\r\npage = BeautifulSoup(driver.page_source,\"html.parser\")\r\n\r\nprint 'brute force enabled...'\r\nwhile var < 15:\r\n\turl = driver.page_source\r\n\tpage = BeautifulSoup(url, \"html.parser\")\r\n\theadis = page.h1\r\n\ttime.sleep(0.5)\r\n\t#a = headis.span\r\n\t#in_html = a.contents\r\n\t#time.sleep(0.5)\r\n\t### detect popup nad refresh\r\n\tif page.findAll('i', {'class',('icon icon--white js-ovl-close')}) in page:\r\n\t\tprint 'ALUUHABARR'\r\n\t#under_h1 = page.findAll(\"span\",{'class': 'flex__item flex__item--dynamic ellipsis'})\r\n\t#print under_h1\r\n\r\n\tplace = 0\r\n\tfor all_in_header in headis.findAll('span'):\r\n\t\tif place == 0:\r\n\t\t\tname = all_in_header.text\r\n\t\tif place == 1:\r\n\t\t\tage = all_in_header.text\r\n\t\tplace +=1\r\n\r\n\tprint 'likeing:', name, 'Age:', age\r\n\tApp.send_keys(Keys.NUMPAD1)\r\n\tvar +=1\r\n\tif var == 14:\r\n\t\tdriver.quit()\r\n\t\tvar = 0\r\n\r\n\r\n\r\n''' to get a content in position after header i use a LoginPopupID\r\nshould be a better way, but didnt find it, probs with contents[1]''' \r\n\r\n\r\n\r\n\t\t#for span in all_span_elements.findAll('span'):\r\n\t\t\t#print span\r\n\t\t\t#driver.quit()\r\n\r\nprint \"END\"\r\ndriver.quit()\r\n'''\r\n\tprint driver.current_url, 'likeing:'\r\n\tApp.send_keys(Keys.NUMPAD1)\r\n\tvar+=1\r\n\tif var == 9:\r\n\t\tdriver.refresh()\r\n\r\nprint driver.current_url + \"alukabar\"\r\n#driver.quit()\r\n'''"
] | true |
99,997 | 0a03e7274a1d30e2b4f509d3cab8d600eda1cf0f | def process_dict(my_dict):
for key, value in my_dict.items():
if key.startswith("melon"):
print(sorted(value))
process_dict({"elon": [3, 1, 2], "melon": 4})
| [
"def process_dict(my_dict):\n for key, value in my_dict.items():\n if key.startswith(\"melon\"):\n print(sorted(value))\n\n\nprocess_dict({\"elon\": [3, 1, 2], \"melon\": 4})\n",
"def process_dict(my_dict):\n for key, value in my_dict.items():\n if key.startswith('melon'):\n print(sorted(value))\n\n\nprocess_dict({'elon': [3, 1, 2], 'melon': 4})\n",
"def process_dict(my_dict):\n for key, value in my_dict.items():\n if key.startswith('melon'):\n print(sorted(value))\n\n\n<code token>\n",
"<function token>\n<code token>\n"
] | false |
99,998 | 455799a224a29da1b46ae3727166c3b65d08225e | # -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017 xxxx
# All rights reserved.
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ============================================================================
"""demo.py
"""
import torch
import torch.npu
loc = 'npu:0'
def build_model():
from network import ShuffleNetV2_Plus
architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]
md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')
md = md.to(loc)
md.eval()
pretrained = torch.load('trainedmodel.pth.tar', map_location=loc) # change this to the filename of the trained model!
old_dict = pretrained['state_dict']
state_dict = {}
for key, value in old_dict.items():
key = key[7:]
state_dict[key] = value
md.load_state_dict(state_dict)
return md
def get_raw_data():
from PIL import Image
from urllib.request import urlretrieve
IMAGE_URL = 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'
urlretrieve(IMAGE_URL, 'tmp.jpg')
img = Image.open("tmp.jpg")
img = img.convert('RGB')
return img
def pre_process(rd):
from torchvision import transforms
transforms_list = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
])
input_data = transforms_list(rd)
return input_data.unsqueeze(0)
def post_process(out):
return torch.argmax(out, 1)
if __name__ == '__main__':
torch.npu.set_device(loc)
# 1. 获取原始数据
raw_data = get_raw_data()
# 2. 构建模型
model = build_model()
# 3. 预处理
input_tensor = pre_process(raw_data)
input_tensor = input_tensor.to(loc)
# 4. 执行forward
output_tensor = model(input_tensor)
output_tensor = output_tensor.cpu()
# 5. 后处理
result = post_process(output_tensor)
# 6. 打印
print(result)
| [
"# -*- coding: utf-8 -*-\n# BSD 3-Clause License\n#\n# Copyright (c) 2017 xxxx\n# All rights reserved.\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# ============================================================================\n\"\"\"demo.py\n\"\"\"\n\nimport torch\nimport torch.npu\nloc = 'npu:0'\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc) # change this to the filename of the trained model!\n\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n\n md.load_state_dict(state_dict)\n return md\n\n\ndef get_raw_data():\n from PIL import Image\n from urllib.request import urlretrieve\n IMAGE_URL = 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'\n urlretrieve(IMAGE_URL, 'tmp.jpg')\n img = Image.open(\"tmp.jpg\")\n img = img.convert('RGB')\n return img\n\n\ndef pre_process(rd):\n\n from torchvision import transforms\n transforms_list = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n ])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\nif __name__ == '__main__':\n torch.npu.set_device(loc)\n # 1. 获取原始数据\n raw_data = get_raw_data()\n\n # 2. 构建模型\n model = build_model()\n\n # 3. 预处理\n input_tensor = pre_process(raw_data)\n input_tensor = input_tensor.to(loc)\n # 4. 执行forward\n output_tensor = model(input_tensor)\n output_tensor = output_tensor.cpu()\n # 5. 后处理\n result = post_process(output_tensor)\n # 6. 打印\n print(result)\n",
"<docstring token>\nimport torch\nimport torch.npu\nloc = 'npu:0'\n\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc)\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n md.load_state_dict(state_dict)\n return md\n\n\ndef get_raw_data():\n from PIL import Image\n from urllib.request import urlretrieve\n IMAGE_URL = (\n 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'\n )\n urlretrieve(IMAGE_URL, 'tmp.jpg')\n img = Image.open('tmp.jpg')\n img = img.convert('RGB')\n return img\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\nif __name__ == '__main__':\n torch.npu.set_device(loc)\n raw_data = get_raw_data()\n model = build_model()\n input_tensor = pre_process(raw_data)\n input_tensor = input_tensor.to(loc)\n output_tensor = model(input_tensor)\n output_tensor = output_tensor.cpu()\n result = post_process(output_tensor)\n print(result)\n",
"<docstring token>\n<import token>\nloc = 'npu:0'\n\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc)\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n md.load_state_dict(state_dict)\n return md\n\n\ndef get_raw_data():\n from PIL import Image\n from urllib.request import urlretrieve\n IMAGE_URL = (\n 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'\n )\n urlretrieve(IMAGE_URL, 'tmp.jpg')\n img = Image.open('tmp.jpg')\n img = img.convert('RGB')\n return img\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\nif __name__ == '__main__':\n torch.npu.set_device(loc)\n raw_data = get_raw_data()\n model = build_model()\n input_tensor = pre_process(raw_data)\n input_tensor = input_tensor.to(loc)\n output_tensor = model(input_tensor)\n output_tensor = output_tensor.cpu()\n result = post_process(output_tensor)\n print(result)\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc)\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n md.load_state_dict(state_dict)\n return md\n\n\ndef get_raw_data():\n from PIL import Image\n from urllib.request import urlretrieve\n IMAGE_URL = (\n 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'\n )\n urlretrieve(IMAGE_URL, 'tmp.jpg')\n img = Image.open('tmp.jpg')\n img = img.convert('RGB')\n return img\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\nif __name__ == '__main__':\n torch.npu.set_device(loc)\n raw_data = get_raw_data()\n model = build_model()\n input_tensor = pre_process(raw_data)\n input_tensor = input_tensor.to(loc)\n output_tensor = model(input_tensor)\n output_tensor = output_tensor.cpu()\n result = post_process(output_tensor)\n print(result)\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc)\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n md.load_state_dict(state_dict)\n return md\n\n\ndef get_raw_data():\n from PIL import Image\n from urllib.request import urlretrieve\n IMAGE_URL = (\n 'https://bbs-img.huaweicloud.com/blogs/img/thumb/1591951315139_8989_1363.png'\n )\n urlretrieve(IMAGE_URL, 'tmp.jpg')\n img = Image.open('tmp.jpg')\n img = img.convert('RGB')\n return img\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n\n\ndef build_model():\n from network import ShuffleNetV2_Plus\n architecture = [0, 0, 3, 1, 1, 1, 0, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 1, 3, 2]\n md = ShuffleNetV2_Plus(architecture=architecture, model_size='Small')\n md = md.to(loc)\n md.eval()\n pretrained = torch.load('trainedmodel.pth.tar', map_location=loc)\n old_dict = pretrained['state_dict']\n state_dict = {}\n for key, value in old_dict.items():\n key = key[7:]\n state_dict[key] = value\n md.load_state_dict(state_dict)\n return md\n\n\n<function token>\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef pre_process(rd):\n from torchvision import transforms\n transforms_list = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224), transforms.ToTensor()])\n input_data = transforms_list(rd)\n return input_data.unsqueeze(0)\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\n<code token>\n",
"<docstring token>\n<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n\n\ndef post_process(out):\n return torch.argmax(out, 1)\n\n\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<code token>\n"
] | false |
99,999 | ab30a233e125889b97c957820961dc8c749c0b0e | # RECURSION
def fact(n):
result = 1
if n > 1:
for f in range(2, n+1):
result *= f
return result
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
def fibonaci(n):
if n == 0:
result = 0
elif n == 1:
result = 1
else:
a = 0
b = 1
for f in range(1, n):
result = a + b
a = b
b = result
return result
for i in range(36):
print(i, fibonaci(i))
| [
"# RECURSION\n\ndef fact(n):\n result = 1\n if n > 1:\n for f in range(2, n+1):\n result *= f\n return result\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n-1)\n\ndef fib(n):\n if n < 2:\n return n\n else:\n return fib(n-1) + fib(n-2)\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\nfor i in range(36):\n print(i, fibonaci(i))\n\n",
"def fact(n):\n result = 1\n if n > 1:\n for f in range(2, n + 1):\n result *= f\n return result\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n - 1)\n\n\ndef fib(n):\n if n < 2:\n return n\n else:\n return fib(n - 1) + fib(n - 2)\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\n\n\nfor i in range(36):\n print(i, fibonaci(i))\n",
"def fact(n):\n result = 1\n if n > 1:\n for f in range(2, n + 1):\n result *= f\n return result\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n - 1)\n\n\ndef fib(n):\n if n < 2:\n return n\n else:\n return fib(n - 1) + fib(n - 2)\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\n\n\n<code token>\n",
"def fact(n):\n result = 1\n if n > 1:\n for f in range(2, n + 1):\n result *= f\n return result\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n - 1)\n\n\n<function token>\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\n\n\n<code token>\n",
"<function token>\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n - 1)\n\n\n<function token>\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\n\n\n<code token>\n",
"<function token>\n<function token>\n<function token>\n\n\ndef fibonaci(n):\n if n == 0:\n result = 0\n elif n == 1:\n result = 1\n else:\n a = 0\n b = 1\n for f in range(1, n):\n result = a + b\n a = b\n b = result\n return result\n\n\n<code token>\n",
"<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n"
] | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.