code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import random import datetime import userval import file from getpass import getpass #SORRY FOR THE REDUNDANT CODE, I RAN OUT OF OPTIONS def register(): global first,last,email,pin,password,accountName #prepared_user_details first=input("input firstname:") last=input("input lastname:") email=input("input email:") pin=input("input a four digit pin:") password=input("Input Password:") accountName = "{} {}".format(last,first) #prepared_user_details= first + "," + last + "," + email + "," + str(pin) + "," + password + "," + str(0) #---------------------Account number generator------------------------- def genAcc(): num= 1 y=[3,0] #all account numbers generated must start with three zero to make it unique while num <= 8: x = random.randint(0,9) y.append(x) num = num +1 accountNo=''.join([str(i)for i in y]) return accountNo #-----------------Transfer function--------------------- def transfer(tName, tNo, amount, tBankName): user[-1]= int(user[-1]) + amount newval=user[-1] newval=str(newval) try: file.update(user_acc_no,-1,newval) except FileNotFoundError: print("an issues occured due to network, try again later") return False print("Tranfer successful! \Account name {} \nAccount number : {} \nAmount transferred : {} \nBank : {}".format(tName, tNo, amount, tBankName)) print("Balance : ${}".format(user[-1])) tym =datetime.datetime.now() print(tym) #-----------------deposit function----------------------- def deposit(amount): user[-1] = int(user[-1]) + amount newval=user[-1] newval=str(newval) try: file.update(user_acc_no,-1,newval) except FileNotFoundError: print("an issues occured due to network, try again later") return False print("{} successful deposited".format(amount)) print("your balance is ${}".format(user[-1])) tym =datetime.datetime.now() print(tym) #------------------withdraw function--------------------------- def withdraw(amount): user[-1]=int(user[-1]) if user[-1] > amount: user[-1] -= amount print("successful") print("your balance is ${}".format(user[-1])) else: print("Sorry, not enough funds!") newval = user[-1] str(newval) try: file.update(user_acc_no,-1,newval) except FileNotFoundError: print("an issues occured due to network, try again later") return False tym =datetime.datetime.now() print(tym) #---------------------balance check function------------------------ def statement(): print("hi {} your balance is ${}.".format(user[1],user[-1])) #---------------------pin validation function------------------------ def pinval(val): if val == user[-3]: return True else: return False #---------------------pin reset function--------------------------- def pinReset(val,val2): if val == val2: user[-3] = val print("Pin change successful") newval = user[-3] try: file.update(user_acc_no,-3,newval) except FileNotFoundError: print("an issues occured due to network, try again later") return False else: print("oops!! The two pin are not the same") tym =datetime.datetime.now() print(tym) #-----------------password reset function------------------------- def passReset(val, val2): if val == val2: user[-2]= val print("Password change successful") newval = user[-2] try: file.update(user_acc_no,-2,newval) except FileNotFoundError: print("an issues occured due to network, try again later") return False else: print("Passwords not Matched") tym =datetime.datetime.now() print(tym) #----------------------login function--------------------- def login(): global user_acc_no, user_password,user print("===================LOGIN PAGE=================") print("Enter your login details") user_acc_no = int(input("Enter username:")) user_password = getpass("Enter password:") user= file.authentication(user_acc_no, user_password) if user: operation(user) else: print("invalid account and password") login() def welcome(): #---------------------------------main prompt--------------- opt= input("Hello!, Welcome to Zuri Bank \n1. Register\n2.Login \n==>") #-----------------------------Registration Prompt-------------------------- if opt == '1': print("============================ZURI BANK========================") print("Welcome please carefully follow the prompt and register your details\n Note please only input 1 or 2 ") register() accountNo = "" accountNo=genAcc() is_user_created = file.create(accountNo,first,last,email,pin,password) if is_user_created: try: print("Registration Successful!!!\n your details are:\n Account name is {} \n Account number is {}".format(accountName,accountNo)) login() tym =datetime.datetime.now() print(tym) except FileExistsError: print("sorry there was a issue in network connection, please try again") register() except ValueError: print("sorry there was a issue in network connection, please try again") register() elif opt == '2': login() else: print("Wrong input. Note: enter 1 or 2 to select") def operation(user): print("==========================ZURI BANK===================") print("welcome {}".format(user[1] + ' ' + user[0])) print("Balance : ${}".format(user[-1])) print("Please input only 1,2,3,4,5,6, or 7") mainOpt=input("select an option: \n1. Transfer \n2. Withdrawal \n3. Deposit \n4. Change Pin \n5. Reset Password \n6. Account Statment\n7. Complaint\n8. Logout\n0. Exit \n==>") if mainOpt == '1': print("Balance = ${}".format(user[-1])) amount=int(input("Enter amount:")) tName=input("Enter account name:") tNo=input("Enter account Number:") tBankName=input("Enter Bank:") val=input("Enter PIN") if (pinval(val) == True): if len(tNo) != 10: print("wrong account number, Note Account number must be 10 digit") else: transfer(tName,tNo,amount,tBankName) operation(user) else: print("wrong pin") elif mainOpt == '2': print("Balance = ${}".format(user[-1])) amount=int(input("Enter Amount:")) val=int(input("Enter transaction Pin:")) pinval(val) if pinval(val) == True: withdraw(amount) operation(user) else: print("oop!! wrong pin") elif mainOpt == '3': print("Balance = ${}".format(user[-1])) amount=int(input("Enter Amount:")) deposit(amount) operation(user) elif mainOpt == '4': val=input("Enter new pin:") val2=input("Confirm new pin:") pinReset(val,val2) operation(user) elif mainOpt == '5': val=input("Enter new password:") val2=input("Confirm new password:") passReset(val,val2) operation(user) elif mainOpt == '6': statement() operation(user) elif mainOpt == '7': comp=input("Enter complaint:") print("Thanks {} for reaching to us, we will get back to you shortly via your email:{}".format(user[1],user[3])) operation(user) elif mainOpt == '8': login() else: print("Thank you for banking with us!!!") exit() welcome()
normal
{ "blob_id": "a8106c8f14e15706b12e6d157b889288b85bc277", "index": 6789, "step-1": "<mask token>\n\n\ndef genAcc():\n num = 1\n y = [3, 0]\n while num <= 8:\n x = random.randint(0, 9)\n y.append(x)\n num = num + 1\n accountNo = ''.join([str(i) for i in y])\n return accountNo\n\n\ndef transfer(tName, tNo, amount, tBankName):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print(\n \"\"\"Tranfer successful! \\\\Account name {} \nAccount number : {} \nAmount transferred : {} \nBank : {}\"\"\"\n .format(tName, tNo, amount, tBankName))\n print('Balance : ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef statement():\n print('hi {} your balance is ${}.'.format(user[1], user[-1]))\n\n\ndef pinval(val):\n if val == user[-3]:\n return True\n else:\n return False\n\n\ndef pinReset(val, val2):\n if val == val2:\n user[-3] = val\n print('Pin change successful')\n newval = user[-3]\n try:\n file.update(user_acc_no, -3, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('oops!! The two pin are not the same')\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef passReset(val, val2):\n if val == val2:\n user[-2] = val\n print('Password change successful')\n newval = user[-2]\n try:\n file.update(user_acc_no, -2, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('Passwords not Matched')\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef operation(user):\n print('==========================ZURI BANK===================')\n print('welcome {}'.format(user[1] + ' ' + user[0]))\n print('Balance : ${}'.format(user[-1]))\n print('Please input only 1,2,3,4,5,6, or 7')\n mainOpt = input(\n \"\"\"select an option: \n1. Transfer \n2. Withdrawal \n3. Deposit \n4. Change Pin \n5. Reset Password \n6. Account Statment\n7. Complaint\n8. Logout\n0. Exit \n==>\"\"\"\n )\n if mainOpt == '1':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter amount:'))\n tName = input('Enter account name:')\n tNo = input('Enter account Number:')\n tBankName = input('Enter Bank:')\n val = input('Enter PIN')\n if pinval(val) == True:\n if len(tNo) != 10:\n print(\n 'wrong account number, Note Account number must be 10 digit'\n )\n else:\n transfer(tName, tNo, amount, tBankName)\n operation(user)\n else:\n print('wrong pin')\n elif mainOpt == '2':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n val = int(input('Enter transaction Pin:'))\n pinval(val)\n if pinval(val) == True:\n withdraw(amount)\n operation(user)\n else:\n print('oop!! wrong pin')\n elif mainOpt == '3':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n deposit(amount)\n operation(user)\n elif mainOpt == '4':\n val = input('Enter new pin:')\n val2 = input('Confirm new pin:')\n pinReset(val, val2)\n operation(user)\n elif mainOpt == '5':\n val = input('Enter new password:')\n val2 = input('Confirm new password:')\n passReset(val, val2)\n operation(user)\n elif mainOpt == '6':\n statement()\n operation(user)\n elif mainOpt == '7':\n comp = input('Enter complaint:')\n print(\n 'Thanks {} for reaching to us, we will get back to you shortly via your email:{}'\n .format(user[1], user[3]))\n operation(user)\n elif mainOpt == '8':\n login()\n else:\n print('Thank you for banking with us!!!')\n exit()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef genAcc():\n num = 1\n y = [3, 0]\n while num <= 8:\n x = random.randint(0, 9)\n y.append(x)\n num = num + 1\n accountNo = ''.join([str(i) for i in y])\n return accountNo\n\n\ndef transfer(tName, tNo, amount, tBankName):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print(\n \"\"\"Tranfer successful! \\\\Account name {} \nAccount number : {} \nAmount transferred : {} \nBank : {}\"\"\"\n .format(tName, tNo, amount, tBankName))\n print('Balance : ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef deposit(amount):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print('{} successful deposited'.format(amount))\n print('your balance is ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef statement():\n print('hi {} your balance is ${}.'.format(user[1], user[-1]))\n\n\ndef pinval(val):\n if val == user[-3]:\n return True\n else:\n return False\n\n\ndef pinReset(val, val2):\n if val == val2:\n user[-3] = val\n print('Pin change successful')\n newval = user[-3]\n try:\n file.update(user_acc_no, -3, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('oops!! The two pin are not the same')\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef passReset(val, val2):\n if val == val2:\n user[-2] = val\n print('Password change successful')\n newval = user[-2]\n try:\n file.update(user_acc_no, -2, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('Passwords not Matched')\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef operation(user):\n print('==========================ZURI BANK===================')\n print('welcome {}'.format(user[1] + ' ' + user[0]))\n print('Balance : ${}'.format(user[-1]))\n print('Please input only 1,2,3,4,5,6, or 7')\n mainOpt = input(\n \"\"\"select an option: \n1. Transfer \n2. Withdrawal \n3. Deposit \n4. Change Pin \n5. Reset Password \n6. Account Statment\n7. Complaint\n8. Logout\n0. Exit \n==>\"\"\"\n )\n if mainOpt == '1':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter amount:'))\n tName = input('Enter account name:')\n tNo = input('Enter account Number:')\n tBankName = input('Enter Bank:')\n val = input('Enter PIN')\n if pinval(val) == True:\n if len(tNo) != 10:\n print(\n 'wrong account number, Note Account number must be 10 digit'\n )\n else:\n transfer(tName, tNo, amount, tBankName)\n operation(user)\n else:\n print('wrong pin')\n elif mainOpt == '2':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n val = int(input('Enter transaction Pin:'))\n pinval(val)\n if pinval(val) == True:\n withdraw(amount)\n operation(user)\n else:\n print('oop!! wrong pin')\n elif mainOpt == '3':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n deposit(amount)\n operation(user)\n elif mainOpt == '4':\n val = input('Enter new pin:')\n val2 = input('Confirm new pin:')\n pinReset(val, val2)\n operation(user)\n elif mainOpt == '5':\n val = input('Enter new password:')\n val2 = input('Confirm new password:')\n passReset(val, val2)\n operation(user)\n elif mainOpt == '6':\n statement()\n operation(user)\n elif mainOpt == '7':\n comp = input('Enter complaint:')\n print(\n 'Thanks {} for reaching to us, we will get back to you shortly via your email:{}'\n .format(user[1], user[3]))\n operation(user)\n elif mainOpt == '8':\n login()\n else:\n print('Thank you for banking with us!!!')\n exit()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef register():\n global first, last, email, pin, password, accountName\n first = input('input firstname:')\n last = input('input lastname:')\n email = input('input email:')\n pin = input('input a four digit pin:')\n password = input('Input Password:')\n accountName = '{} {}'.format(last, first)\n\n\ndef genAcc():\n num = 1\n y = [3, 0]\n while num <= 8:\n x = random.randint(0, 9)\n y.append(x)\n num = num + 1\n accountNo = ''.join([str(i) for i in y])\n return accountNo\n\n\ndef transfer(tName, tNo, amount, tBankName):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print(\n \"\"\"Tranfer successful! \\\\Account name {} \nAccount number : {} \nAmount transferred : {} \nBank : {}\"\"\"\n .format(tName, tNo, amount, tBankName))\n print('Balance : ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef deposit(amount):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print('{} successful deposited'.format(amount))\n print('your balance is ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef statement():\n print('hi {} your balance is ${}.'.format(user[1], user[-1]))\n\n\ndef pinval(val):\n if val == user[-3]:\n return True\n else:\n return False\n\n\ndef pinReset(val, val2):\n if val == val2:\n user[-3] = val\n print('Pin change successful')\n newval = user[-3]\n try:\n file.update(user_acc_no, -3, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('oops!! The two pin are not the same')\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef passReset(val, val2):\n if val == val2:\n user[-2] = val\n print('Password change successful')\n newval = user[-2]\n try:\n file.update(user_acc_no, -2, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('Passwords not Matched')\n tym = datetime.datetime.now()\n print(tym)\n\n\n<mask token>\n\n\ndef operation(user):\n print('==========================ZURI BANK===================')\n print('welcome {}'.format(user[1] + ' ' + user[0]))\n print('Balance : ${}'.format(user[-1]))\n print('Please input only 1,2,3,4,5,6, or 7')\n mainOpt = input(\n \"\"\"select an option: \n1. Transfer \n2. Withdrawal \n3. Deposit \n4. Change Pin \n5. Reset Password \n6. Account Statment\n7. Complaint\n8. Logout\n0. Exit \n==>\"\"\"\n )\n if mainOpt == '1':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter amount:'))\n tName = input('Enter account name:')\n tNo = input('Enter account Number:')\n tBankName = input('Enter Bank:')\n val = input('Enter PIN')\n if pinval(val) == True:\n if len(tNo) != 10:\n print(\n 'wrong account number, Note Account number must be 10 digit'\n )\n else:\n transfer(tName, tNo, amount, tBankName)\n operation(user)\n else:\n print('wrong pin')\n elif mainOpt == '2':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n val = int(input('Enter transaction Pin:'))\n pinval(val)\n if pinval(val) == True:\n withdraw(amount)\n operation(user)\n else:\n print('oop!! wrong pin')\n elif mainOpt == '3':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n deposit(amount)\n operation(user)\n elif mainOpt == '4':\n val = input('Enter new pin:')\n val2 = input('Confirm new pin:')\n pinReset(val, val2)\n operation(user)\n elif mainOpt == '5':\n val = input('Enter new password:')\n val2 = input('Confirm new password:')\n passReset(val, val2)\n operation(user)\n elif mainOpt == '6':\n statement()\n operation(user)\n elif mainOpt == '7':\n comp = input('Enter complaint:')\n print(\n 'Thanks {} for reaching to us, we will get back to you shortly via your email:{}'\n .format(user[1], user[3]))\n operation(user)\n elif mainOpt == '8':\n login()\n else:\n print('Thank you for banking with us!!!')\n exit()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef register():\n global first, last, email, pin, password, accountName\n first = input('input firstname:')\n last = input('input lastname:')\n email = input('input email:')\n pin = input('input a four digit pin:')\n password = input('Input Password:')\n accountName = '{} {}'.format(last, first)\n\n\ndef genAcc():\n num = 1\n y = [3, 0]\n while num <= 8:\n x = random.randint(0, 9)\n y.append(x)\n num = num + 1\n accountNo = ''.join([str(i) for i in y])\n return accountNo\n\n\ndef transfer(tName, tNo, amount, tBankName):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print(\n \"\"\"Tranfer successful! \\\\Account name {} \nAccount number : {} \nAmount transferred : {} \nBank : {}\"\"\"\n .format(tName, tNo, amount, tBankName))\n print('Balance : ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef deposit(amount):\n user[-1] = int(user[-1]) + amount\n newval = user[-1]\n newval = str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n print('{} successful deposited'.format(amount))\n print('your balance is ${}'.format(user[-1]))\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef withdraw(amount):\n user[-1] = int(user[-1])\n if user[-1] > amount:\n user[-1] -= amount\n print('successful')\n print('your balance is ${}'.format(user[-1]))\n else:\n print('Sorry, not enough funds!')\n newval = user[-1]\n str(newval)\n try:\n file.update(user_acc_no, -1, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef statement():\n print('hi {} your balance is ${}.'.format(user[1], user[-1]))\n\n\ndef pinval(val):\n if val == user[-3]:\n return True\n else:\n return False\n\n\ndef pinReset(val, val2):\n if val == val2:\n user[-3] = val\n print('Pin change successful')\n newval = user[-3]\n try:\n file.update(user_acc_no, -3, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('oops!! The two pin are not the same')\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef passReset(val, val2):\n if val == val2:\n user[-2] = val\n print('Password change successful')\n newval = user[-2]\n try:\n file.update(user_acc_no, -2, newval)\n except FileNotFoundError:\n print('an issues occured due to network, try again later')\n return False\n else:\n print('Passwords not Matched')\n tym = datetime.datetime.now()\n print(tym)\n\n\ndef login():\n global user_acc_no, user_password, user\n print('===================LOGIN PAGE=================')\n print('Enter your login details')\n user_acc_no = int(input('Enter username:'))\n user_password = getpass('Enter password:')\n user = file.authentication(user_acc_no, user_password)\n if user:\n operation(user)\n else:\n print('invalid account and password')\n login()\n\n\ndef welcome():\n opt = input('Hello!, Welcome to Zuri Bank \\n1. Register\\n2.Login \\n==>')\n if opt == '1':\n print('============================ZURI BANK========================')\n print(\n \"\"\"Welcome please carefully follow the prompt and register your details\n Note please only input 1 or 2 \"\"\"\n )\n register()\n accountNo = ''\n accountNo = genAcc()\n is_user_created = file.create(accountNo, first, last, email, pin,\n password)\n if is_user_created:\n try:\n print(\n \"\"\"Registration Successful!!!\n your details are:\n Account name is {} \n Account number is {}\"\"\"\n .format(accountName, accountNo))\n login()\n tym = datetime.datetime.now()\n print(tym)\n except FileExistsError:\n print(\n 'sorry there was a issue in network connection, please try again'\n )\n register()\n except ValueError:\n print(\n 'sorry there was a issue in network connection, please try again'\n )\n register()\n elif opt == '2':\n login()\n else:\n print('Wrong input. Note: enter 1 or 2 to select')\n\n\ndef operation(user):\n print('==========================ZURI BANK===================')\n print('welcome {}'.format(user[1] + ' ' + user[0]))\n print('Balance : ${}'.format(user[-1]))\n print('Please input only 1,2,3,4,5,6, or 7')\n mainOpt = input(\n \"\"\"select an option: \n1. Transfer \n2. Withdrawal \n3. Deposit \n4. Change Pin \n5. Reset Password \n6. Account Statment\n7. Complaint\n8. Logout\n0. Exit \n==>\"\"\"\n )\n if mainOpt == '1':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter amount:'))\n tName = input('Enter account name:')\n tNo = input('Enter account Number:')\n tBankName = input('Enter Bank:')\n val = input('Enter PIN')\n if pinval(val) == True:\n if len(tNo) != 10:\n print(\n 'wrong account number, Note Account number must be 10 digit'\n )\n else:\n transfer(tName, tNo, amount, tBankName)\n operation(user)\n else:\n print('wrong pin')\n elif mainOpt == '2':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n val = int(input('Enter transaction Pin:'))\n pinval(val)\n if pinval(val) == True:\n withdraw(amount)\n operation(user)\n else:\n print('oop!! wrong pin')\n elif mainOpt == '3':\n print('Balance = ${}'.format(user[-1]))\n amount = int(input('Enter Amount:'))\n deposit(amount)\n operation(user)\n elif mainOpt == '4':\n val = input('Enter new pin:')\n val2 = input('Confirm new pin:')\n pinReset(val, val2)\n operation(user)\n elif mainOpt == '5':\n val = input('Enter new password:')\n val2 = input('Confirm new password:')\n passReset(val, val2)\n operation(user)\n elif mainOpt == '6':\n statement()\n operation(user)\n elif mainOpt == '7':\n comp = input('Enter complaint:')\n print(\n 'Thanks {} for reaching to us, we will get back to you shortly via your email:{}'\n .format(user[1], user[3]))\n operation(user)\n elif mainOpt == '8':\n login()\n else:\n print('Thank you for banking with us!!!')\n exit()\n\n\nwelcome()\n", "step-5": "import random\nimport datetime \nimport userval\nimport file\nfrom getpass import getpass\n#SORRY FOR THE REDUNDANT CODE, I RAN OUT OF OPTIONS\n\n\ndef register():\n global first,last,email,pin,password,accountName #prepared_user_details\n first=input(\"input firstname:\")\n last=input(\"input lastname:\")\n email=input(\"input email:\")\n pin=input(\"input a four digit pin:\")\n password=input(\"Input Password:\")\n accountName = \"{} {}\".format(last,first)\n #prepared_user_details= first + \",\" + last + \",\" + email + \",\" + str(pin) + \",\" + password + \",\" + str(0)\n \n #---------------------Account number generator-------------------------\n\ndef genAcc():\n num= 1\n y=[3,0] #all account numbers generated must start with three zero to make it unique\n while num <= 8:\n x = random.randint(0,9)\n y.append(x)\n num = num +1\n accountNo=''.join([str(i)for i in y])\n return accountNo\n \n #-----------------Transfer function---------------------\n\ndef transfer(tName, tNo, amount, tBankName):\n user[-1]= int(user[-1]) + amount\n newval=user[-1]\n newval=str(newval)\n try:\n file.update(user_acc_no,-1,newval)\n except FileNotFoundError:\n print(\"an issues occured due to network, try again later\")\n return False\n print(\"Tranfer successful! \\Account name {} \\nAccount number : {} \\nAmount transferred : {} \\nBank : {}\".format(tName, tNo, amount, tBankName))\n print(\"Balance : ${}\".format(user[-1]))\n tym =datetime.datetime.now()\n print(tym)\n \n #-----------------deposit function-----------------------\n\ndef deposit(amount):\n user[-1] = int(user[-1]) + amount\n newval=user[-1]\n newval=str(newval)\n try:\n file.update(user_acc_no,-1,newval)\n except FileNotFoundError:\n print(\"an issues occured due to network, try again later\")\n return False\n print(\"{} successful deposited\".format(amount))\n print(\"your balance is ${}\".format(user[-1]))\n tym =datetime.datetime.now()\n print(tym)\n #------------------withdraw function---------------------------\n\ndef withdraw(amount):\n user[-1]=int(user[-1])\n if user[-1] > amount:\n user[-1] -= amount\n print(\"successful\")\n print(\"your balance is ${}\".format(user[-1]))\n else:\n print(\"Sorry, not enough funds!\")\n newval = user[-1]\n str(newval)\n try:\n file.update(user_acc_no,-1,newval)\n except FileNotFoundError:\n print(\"an issues occured due to network, try again later\")\n return False\n tym =datetime.datetime.now()\n print(tym)\n \n \n #---------------------balance check function------------------------\n\n\ndef statement():\n print(\"hi {} your balance is ${}.\".format(user[1],user[-1]))\n \n \n #---------------------pin validation function------------------------\n\n\ndef pinval(val):\n if val == user[-3]:\n return True\n else:\n return False\n \n \n #---------------------pin reset function---------------------------\ndef pinReset(val,val2):\n if val == val2:\n user[-3] = val\n print(\"Pin change successful\")\n newval = user[-3]\n try:\n file.update(user_acc_no,-3,newval)\n except FileNotFoundError:\n print(\"an issues occured due to network, try again later\")\n return False\n else:\n print(\"oops!! The two pin are not the same\")\n tym =datetime.datetime.now()\n print(tym)\n \n \n #-----------------password reset function------------------------- \ndef passReset(val, val2):\n if val == val2:\n user[-2]= val\n print(\"Password change successful\")\n newval = user[-2]\n try:\n file.update(user_acc_no,-2,newval)\n except FileNotFoundError:\n print(\"an issues occured due to network, try again later\")\n return False\n else:\n print(\"Passwords not Matched\")\n tym =datetime.datetime.now()\n print(tym)\n \n \n #----------------------login function---------------------\n\ndef login():\n global user_acc_no, user_password,user\n print(\"===================LOGIN PAGE=================\") \n print(\"Enter your login details\")\n user_acc_no = int(input(\"Enter username:\"))\n user_password = getpass(\"Enter password:\")\n\n user= file.authentication(user_acc_no, user_password)\n \n if user:\n operation(user)\n else:\n print(\"invalid account and password\")\n login()\n \n \n\n\n\ndef welcome(): \n #---------------------------------main prompt---------------\n opt= input(\"Hello!, Welcome to Zuri Bank \\n1. Register\\n2.Login \\n==>\")\n #-----------------------------Registration Prompt--------------------------\n if opt == '1':\n print(\"============================ZURI BANK========================\")\n print(\"Welcome please carefully follow the prompt and register your details\\n Note please only input 1 or 2 \")\n \n register()\n accountNo = \"\"\n accountNo=genAcc()\n is_user_created = file.create(accountNo,first,last,email,pin,password)\n if is_user_created:\n try:\n print(\"Registration Successful!!!\\n your details are:\\n Account name is {} \\n Account number is {}\".format(accountName,accountNo))\n login()\n \n tym =datetime.datetime.now()\n print(tym)\n except FileExistsError:\n print(\"sorry there was a issue in network connection, please try again\")\n register()\n\n except ValueError:\n print(\"sorry there was a issue in network connection, please try again\")\n register()\n \n\n\n elif opt == '2':\n \n login()\n \n\n\n\n else:\n print(\"Wrong input. Note: enter 1 or 2 to select\")\n\n \ndef operation(user): \n \n print(\"==========================ZURI BANK===================\")\n print(\"welcome {}\".format(user[1] + ' ' + user[0]))\n print(\"Balance : ${}\".format(user[-1]))\n print(\"Please input only 1,2,3,4,5,6, or 7\")\n mainOpt=input(\"select an option: \\n1. Transfer \\n2. Withdrawal \\n3. Deposit \\n4. Change Pin \\n5. Reset Password \\n6. Account Statment\\n7. Complaint\\n8. Logout\\n0. Exit \\n==>\")\n \n \n if mainOpt == '1':\n print(\"Balance = ${}\".format(user[-1]))\n amount=int(input(\"Enter amount:\"))\n tName=input(\"Enter account name:\")\n tNo=input(\"Enter account Number:\")\n tBankName=input(\"Enter Bank:\")\n val=input(\"Enter PIN\")\n if (pinval(val) == True):\n if len(tNo) != 10:\n print(\"wrong account number, Note Account number must be 10 digit\")\n else:\n transfer(tName,tNo,amount,tBankName)\n operation(user)\n else:\n print(\"wrong pin\")\n \n elif mainOpt == '2':\n print(\"Balance = ${}\".format(user[-1]))\n amount=int(input(\"Enter Amount:\"))\n val=int(input(\"Enter transaction Pin:\"))\n pinval(val)\n if pinval(val) == True:\n withdraw(amount)\n operation(user)\n else:\n print(\"oop!! wrong pin\")\n \n elif mainOpt == '3':\n print(\"Balance = ${}\".format(user[-1]))\n amount=int(input(\"Enter Amount:\"))\n deposit(amount)\n operation(user)\n \n \n elif mainOpt == '4':\n val=input(\"Enter new pin:\")\n val2=input(\"Confirm new pin:\")\n pinReset(val,val2)\n operation(user)\n \n elif mainOpt == '5':\n val=input(\"Enter new password:\")\n val2=input(\"Confirm new password:\")\n passReset(val,val2)\n operation(user)\n \n elif mainOpt == '6':\n statement()\n operation(user)\n \n elif mainOpt == '7':\n comp=input(\"Enter complaint:\")\n print(\"Thanks {} for reaching to us, we will get back to you shortly via your email:{}\".format(user[1],user[3]))\n operation(user)\n \n elif mainOpt == '8':\n login()\n \n else:\n print(\"Thank you for banking with us!!!\")\n exit()\n \n\n\nwelcome()", "step-ids": [ 7, 8, 9, 13, 15 ] }
[ 7, 8, 9, 13, 15 ]
class Solution: def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n-1 found = False res = None while left <= right: mid = left + (right - left) // 2 if nums[mid] == target: found = True res = mid break elif nums[mid] >= nums[0]: if target < nums[mid] and target >= nums[0]: right = mid - 1 else: left = mid + 1 # nums[mid] > target elif nums[mid] < nums[0]: if target > nums[mid] and target <= nums[-1]: left = mid + 1 else: right = mid - 1 if found: print("res is: ", res) return res else: print("res is: ", -1) return -1 """ https://leetcode.cn/submissions/detail/320442719/ 执行用时: 36 ms , 在所有 Python3 提交中击败了 73.39% 的用户 内存消耗: 15.2 MB , 在所有 Python3 提交中击败了 62.74% 的用户 通过测试用例: 195 / 195 """
normal
{ "blob_id": "1fe6fab717a77f13ddf7059ef0a5aaef217f0fb0", "index": 5525, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n\n\n<mask token>\n", "step-3": "class Solution:\n\n def search(self, nums: List[int], target: int) ->int:\n n = len(nums)\n left, right = 0, n - 1\n found = False\n res = None\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n found = True\n res = mid\n break\n elif nums[mid] >= nums[0]:\n if target < nums[mid] and target >= nums[0]:\n right = mid - 1\n else:\n left = mid + 1\n elif nums[mid] < nums[0]:\n if target > nums[mid] and target <= nums[-1]:\n left = mid + 1\n else:\n right = mid - 1\n if found:\n print('res is: ', res)\n return res\n else:\n print('res is: ', -1)\n return -1\n\n\n<mask token>\n", "step-4": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n \n n = len(nums)\n left, right = 0, n-1\n found = False\n res = None\n\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n found = True\n res = mid\n break\n elif nums[mid] >= nums[0]:\n if target < nums[mid] and target >= nums[0]:\n right = mid - 1\n else:\n left = mid + 1\n # nums[mid] > target\n elif nums[mid] < nums[0]:\n if target > nums[mid] and target <= nums[-1]:\n left = mid + 1\n else:\n right = mid - 1\n if found:\n print(\"res is: \", res)\n return res\n else:\n print(\"res is: \", -1)\n return -1\n \n\"\"\"\nhttps://leetcode.cn/submissions/detail/320442719/\n\n执行用时:\n36 ms\n, 在所有 Python3 提交中击败了\n73.39%\n的用户\n内存消耗:\n15.2 MB\n, 在所有 Python3 提交中击败了\n62.74%\n的用户\n通过测试用例:\n195 / 195\n\"\"\"\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from rest_framework.views import APIView from rest_framework.response import Response from drf_yasg.utils import swagger_auto_schema from theme.models import UserProfile from hs_core.views import serializers class UserInfo(APIView): @swagger_auto_schema(operation_description="Get information about the logged in user", responses={200: serializers.UserInfoSerializer}) def get(self, request): ''' Get information about the logged in user :param request: :return: HttpResponse response containing **user_info** ''' if not request.user.is_authenticated: return Response({"title": "None", "organization": "None", "state": "None", "country": "None", "user_type": "None"}) user_info = {"username": request.user.username} if request.user.email: user_info['email'] = request.user.email if request.user.first_name: user_info['first_name'] = request.user.first_name if request.user.id: user_info['id'] = request.user.id if request.user.last_name: user_info['last_name'] = request.user.last_name user_profile = UserProfile.objects.filter(user=request.user).first() if user_profile.title: user_info['title'] = user_profile.title if user_profile.organization: user_info['organization'] = user_profile.organization if user_profile.state and user_profile.state.strip() and user_profile.state != 'Unspecified': user_info['state'] = user_profile.state.strip() if user_profile.country and user_profile.country != 'Unspecified': user_info['country'] = user_profile.country if user_profile.user_type and user_profile.user_type.strip() and user_profile.user_type != 'Unspecified': user_info['user_type'] = user_profile.user_type.strip() return Response(user_info)
normal
{ "blob_id": "c45ffe8cba8d152e346182252dbc43e22eaf83e2", "index": 3498, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass UserInfo(APIView):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass UserInfo(APIView):\n\n @swagger_auto_schema(operation_description=\n 'Get information about the logged in user', responses={(200):\n serializers.UserInfoSerializer})\n def get(self, request):\n \"\"\"\n Get information about the logged in user\n\n :param request:\n :return: HttpResponse response containing **user_info**\n \"\"\"\n if not request.user.is_authenticated:\n return Response({'title': 'None', 'organization': 'None',\n 'state': 'None', 'country': 'None', 'user_type': 'None'})\n user_info = {'username': request.user.username}\n if request.user.email:\n user_info['email'] = request.user.email\n if request.user.first_name:\n user_info['first_name'] = request.user.first_name\n if request.user.id:\n user_info['id'] = request.user.id\n if request.user.last_name:\n user_info['last_name'] = request.user.last_name\n user_profile = UserProfile.objects.filter(user=request.user).first()\n if user_profile.title:\n user_info['title'] = user_profile.title\n if user_profile.organization:\n user_info['organization'] = user_profile.organization\n if user_profile.state and user_profile.state.strip(\n ) and user_profile.state != 'Unspecified':\n user_info['state'] = user_profile.state.strip()\n if user_profile.country and user_profile.country != 'Unspecified':\n user_info['country'] = user_profile.country\n if user_profile.user_type and user_profile.user_type.strip(\n ) and user_profile.user_type != 'Unspecified':\n user_info['user_type'] = user_profile.user_type.strip()\n return Response(user_info)\n", "step-4": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\nfrom theme.models import UserProfile\nfrom hs_core.views import serializers\n\n\nclass UserInfo(APIView):\n\n @swagger_auto_schema(operation_description=\n 'Get information about the logged in user', responses={(200):\n serializers.UserInfoSerializer})\n def get(self, request):\n \"\"\"\n Get information about the logged in user\n\n :param request:\n :return: HttpResponse response containing **user_info**\n \"\"\"\n if not request.user.is_authenticated:\n return Response({'title': 'None', 'organization': 'None',\n 'state': 'None', 'country': 'None', 'user_type': 'None'})\n user_info = {'username': request.user.username}\n if request.user.email:\n user_info['email'] = request.user.email\n if request.user.first_name:\n user_info['first_name'] = request.user.first_name\n if request.user.id:\n user_info['id'] = request.user.id\n if request.user.last_name:\n user_info['last_name'] = request.user.last_name\n user_profile = UserProfile.objects.filter(user=request.user).first()\n if user_profile.title:\n user_info['title'] = user_profile.title\n if user_profile.organization:\n user_info['organization'] = user_profile.organization\n if user_profile.state and user_profile.state.strip(\n ) and user_profile.state != 'Unspecified':\n user_info['state'] = user_profile.state.strip()\n if user_profile.country and user_profile.country != 'Unspecified':\n user_info['country'] = user_profile.country\n if user_profile.user_type and user_profile.user_type.strip(\n ) and user_profile.user_type != 'Unspecified':\n user_info['user_type'] = user_profile.user_type.strip()\n return Response(user_info)\n", "step-5": "from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom theme.models import UserProfile\nfrom hs_core.views import serializers\n\n\nclass UserInfo(APIView):\n @swagger_auto_schema(operation_description=\"Get information about the logged in user\",\n responses={200: serializers.UserInfoSerializer})\n def get(self, request):\n '''\n Get information about the logged in user\n\n :param request:\n :return: HttpResponse response containing **user_info**\n '''\n if not request.user.is_authenticated:\n return Response({\"title\": \"None\", \"organization\": \"None\", \"state\": \"None\", \"country\": \"None\",\n \"user_type\": \"None\"})\n\n user_info = {\"username\": request.user.username}\n\n if request.user.email:\n user_info['email'] = request.user.email\n if request.user.first_name:\n user_info['first_name'] = request.user.first_name\n if request.user.id:\n user_info['id'] = request.user.id\n if request.user.last_name:\n user_info['last_name'] = request.user.last_name\n\n user_profile = UserProfile.objects.filter(user=request.user).first()\n if user_profile.title:\n user_info['title'] = user_profile.title\n if user_profile.organization:\n user_info['organization'] = user_profile.organization\n if user_profile.state and user_profile.state.strip() and user_profile.state != 'Unspecified':\n user_info['state'] = user_profile.state.strip()\n if user_profile.country and user_profile.country != 'Unspecified':\n user_info['country'] = user_profile.country\n if user_profile.user_type and user_profile.user_type.strip() and user_profile.user_type != 'Unspecified':\n user_info['user_type'] = user_profile.user_type.strip()\n return Response(user_info)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import argparse import json import os import warnings import numpy as np import pandas as pd import src.data_loaders as module_data import torch from sklearn.metrics import roc_auc_score from src.data_loaders import JigsawDataBias, JigsawDataMultilingual, JigsawDataOriginal from torch.utils.data import DataLoader from tqdm import tqdm from train import ToxicClassifier def test_classifier(config, dataset, checkpoint_path, device="cuda:0"): model = ToxicClassifier(config) checkpoint = torch.load(checkpoint_path, map_location=device) model.load_state_dict(checkpoint["state_dict"]) model.eval() model.to(device) def get_instance(module, name, config, *args, **kwargs): return getattr(module, config[name]["type"])(*args, **config[name]["args"], **kwargs) config["dataset"]["args"]["test_csv_file"] = dataset test_dataset = get_instance(module_data, "dataset", config, train=False) test_data_loader = DataLoader( test_dataset, batch_size=int(config["batch_size"]), num_workers=20, shuffle=False, ) scores = [] targets = [] ids = [] for *items, meta in tqdm(test_data_loader): if "multi_target" in meta: targets += meta["multi_target"] else: targets += meta["target"] ids += meta["text_id"] with torch.no_grad(): out = model.forward(*items) # TODO: save embeddings sm = torch.sigmoid(out).cpu().detach().numpy() scores.extend(sm) binary_scores = [s >= 0.5 for s in scores] binary_scores = np.stack(binary_scores) scores = np.stack(scores) targets = np.stack(targets) auc_scores = [] for class_idx in range(scores.shape[1]): mask = targets[:, class_idx] != -1 target_binary = targets[mask, class_idx] class_scores = scores[mask, class_idx] try: auc = roc_auc_score(target_binary, class_scores) auc_scores.append(auc) except Exception: warnings.warn( "Only one class present in y_true. ROC AUC score is not defined in that case. Set to nan for now." ) auc_scores.append(np.nan) mean_auc = np.mean(auc_scores) results = { "scores": scores.tolist(), "targets": targets.tolist(), "auc_scores": auc_scores, "mean_auc": mean_auc, "ids": [i.tolist() for i in ids], } return results if __name__ == "__main__": parser = argparse.ArgumentParser(description="PyTorch Template") parser.add_argument( "-c", "--config", default=None, type=str, help="config file path (default: None)", ) parser.add_argument( "-ckpt", "--checkpoint", type=str, help="path to a saved checkpoint", ) parser.add_argument( "-d", "--device", default="cuda:0", type=str, help="device name e.g., 'cpu' or 'cuda' (default cuda:0)", ) parser.add_argument( "-t", "--test_csv", default=None, type=str, help="path to test dataset", ) args = parser.parse_args() config = json.load(open(args.config)) if args.device is not None: config["gpus"] = args.device results = test_classifier(config, args.test_csv, args.checkpoint, args.device) test_set_name = args.test_csv.split("/")[-1:][0] with open(args.checkpoint[:-4] + f"results_{test_set_name}.json", "w") as f: json.dump(results, f)
normal
{ "blob_id": "58c7e81d1b3cf1cff7d91bf40641e5a03b9f19ac", "index": 5730, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_classifier(config, dataset, checkpoint_path, device='cuda:0'):\n model = ToxicClassifier(config)\n checkpoint = torch.load(checkpoint_path, map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n model.to(device)\n\n def get_instance(module, name, config, *args, **kwargs):\n return getattr(module, config[name]['type'])(*args, **config[name][\n 'args'], **kwargs)\n config['dataset']['args']['test_csv_file'] = dataset\n test_dataset = get_instance(module_data, 'dataset', config, train=False)\n test_data_loader = DataLoader(test_dataset, batch_size=int(config[\n 'batch_size']), num_workers=20, shuffle=False)\n scores = []\n targets = []\n ids = []\n for *items, meta in tqdm(test_data_loader):\n if 'multi_target' in meta:\n targets += meta['multi_target']\n else:\n targets += meta['target']\n ids += meta['text_id']\n with torch.no_grad():\n out = model.forward(*items)\n sm = torch.sigmoid(out).cpu().detach().numpy()\n scores.extend(sm)\n binary_scores = [(s >= 0.5) for s in scores]\n binary_scores = np.stack(binary_scores)\n scores = np.stack(scores)\n targets = np.stack(targets)\n auc_scores = []\n for class_idx in range(scores.shape[1]):\n mask = targets[:, class_idx] != -1\n target_binary = targets[mask, class_idx]\n class_scores = scores[mask, class_idx]\n try:\n auc = roc_auc_score(target_binary, class_scores)\n auc_scores.append(auc)\n except Exception:\n warnings.warn(\n 'Only one class present in y_true. ROC AUC score is not defined in that case. Set to nan for now.'\n )\n auc_scores.append(np.nan)\n mean_auc = np.mean(auc_scores)\n results = {'scores': scores.tolist(), 'targets': targets.tolist(),\n 'auc_scores': auc_scores, 'mean_auc': mean_auc, 'ids': [i.tolist() for\n i in ids]}\n return results\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef test_classifier(config, dataset, checkpoint_path, device='cuda:0'):\n model = ToxicClassifier(config)\n checkpoint = torch.load(checkpoint_path, map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n model.to(device)\n\n def get_instance(module, name, config, *args, **kwargs):\n return getattr(module, config[name]['type'])(*args, **config[name][\n 'args'], **kwargs)\n config['dataset']['args']['test_csv_file'] = dataset\n test_dataset = get_instance(module_data, 'dataset', config, train=False)\n test_data_loader = DataLoader(test_dataset, batch_size=int(config[\n 'batch_size']), num_workers=20, shuffle=False)\n scores = []\n targets = []\n ids = []\n for *items, meta in tqdm(test_data_loader):\n if 'multi_target' in meta:\n targets += meta['multi_target']\n else:\n targets += meta['target']\n ids += meta['text_id']\n with torch.no_grad():\n out = model.forward(*items)\n sm = torch.sigmoid(out).cpu().detach().numpy()\n scores.extend(sm)\n binary_scores = [(s >= 0.5) for s in scores]\n binary_scores = np.stack(binary_scores)\n scores = np.stack(scores)\n targets = np.stack(targets)\n auc_scores = []\n for class_idx in range(scores.shape[1]):\n mask = targets[:, class_idx] != -1\n target_binary = targets[mask, class_idx]\n class_scores = scores[mask, class_idx]\n try:\n auc = roc_auc_score(target_binary, class_scores)\n auc_scores.append(auc)\n except Exception:\n warnings.warn(\n 'Only one class present in y_true. ROC AUC score is not defined in that case. Set to nan for now.'\n )\n auc_scores.append(np.nan)\n mean_auc = np.mean(auc_scores)\n results = {'scores': scores.tolist(), 'targets': targets.tolist(),\n 'auc_scores': auc_scores, 'mean_auc': mean_auc, 'ids': [i.tolist() for\n i in ids]}\n return results\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch Template')\n parser.add_argument('-c', '--config', default=None, type=str, help=\n 'config file path (default: None)')\n parser.add_argument('-ckpt', '--checkpoint', type=str, help=\n 'path to a saved checkpoint')\n parser.add_argument('-d', '--device', default='cuda:0', type=str, help=\n \"device name e.g., 'cpu' or 'cuda' (default cuda:0)\")\n parser.add_argument('-t', '--test_csv', default=None, type=str, help=\n 'path to test dataset')\n args = parser.parse_args()\n config = json.load(open(args.config))\n if args.device is not None:\n config['gpus'] = args.device\n results = test_classifier(config, args.test_csv, args.checkpoint, args.\n device)\n test_set_name = args.test_csv.split('/')[-1:][0]\n with open(args.checkpoint[:-4] + f'results_{test_set_name}.json', 'w'\n ) as f:\n json.dump(results, f)\n", "step-4": "import argparse\nimport json\nimport os\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport src.data_loaders as module_data\nimport torch\nfrom sklearn.metrics import roc_auc_score\nfrom src.data_loaders import JigsawDataBias, JigsawDataMultilingual, JigsawDataOriginal\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom train import ToxicClassifier\n\n\ndef test_classifier(config, dataset, checkpoint_path, device='cuda:0'):\n model = ToxicClassifier(config)\n checkpoint = torch.load(checkpoint_path, map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n model.to(device)\n\n def get_instance(module, name, config, *args, **kwargs):\n return getattr(module, config[name]['type'])(*args, **config[name][\n 'args'], **kwargs)\n config['dataset']['args']['test_csv_file'] = dataset\n test_dataset = get_instance(module_data, 'dataset', config, train=False)\n test_data_loader = DataLoader(test_dataset, batch_size=int(config[\n 'batch_size']), num_workers=20, shuffle=False)\n scores = []\n targets = []\n ids = []\n for *items, meta in tqdm(test_data_loader):\n if 'multi_target' in meta:\n targets += meta['multi_target']\n else:\n targets += meta['target']\n ids += meta['text_id']\n with torch.no_grad():\n out = model.forward(*items)\n sm = torch.sigmoid(out).cpu().detach().numpy()\n scores.extend(sm)\n binary_scores = [(s >= 0.5) for s in scores]\n binary_scores = np.stack(binary_scores)\n scores = np.stack(scores)\n targets = np.stack(targets)\n auc_scores = []\n for class_idx in range(scores.shape[1]):\n mask = targets[:, class_idx] != -1\n target_binary = targets[mask, class_idx]\n class_scores = scores[mask, class_idx]\n try:\n auc = roc_auc_score(target_binary, class_scores)\n auc_scores.append(auc)\n except Exception:\n warnings.warn(\n 'Only one class present in y_true. ROC AUC score is not defined in that case. Set to nan for now.'\n )\n auc_scores.append(np.nan)\n mean_auc = np.mean(auc_scores)\n results = {'scores': scores.tolist(), 'targets': targets.tolist(),\n 'auc_scores': auc_scores, 'mean_auc': mean_auc, 'ids': [i.tolist() for\n i in ids]}\n return results\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch Template')\n parser.add_argument('-c', '--config', default=None, type=str, help=\n 'config file path (default: None)')\n parser.add_argument('-ckpt', '--checkpoint', type=str, help=\n 'path to a saved checkpoint')\n parser.add_argument('-d', '--device', default='cuda:0', type=str, help=\n \"device name e.g., 'cpu' or 'cuda' (default cuda:0)\")\n parser.add_argument('-t', '--test_csv', default=None, type=str, help=\n 'path to test dataset')\n args = parser.parse_args()\n config = json.load(open(args.config))\n if args.device is not None:\n config['gpus'] = args.device\n results = test_classifier(config, args.test_csv, args.checkpoint, args.\n device)\n test_set_name = args.test_csv.split('/')[-1:][0]\n with open(args.checkpoint[:-4] + f'results_{test_set_name}.json', 'w'\n ) as f:\n json.dump(results, f)\n", "step-5": "import argparse\nimport json\nimport os\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport src.data_loaders as module_data\nimport torch\nfrom sklearn.metrics import roc_auc_score\nfrom src.data_loaders import JigsawDataBias, JigsawDataMultilingual, JigsawDataOriginal\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom train import ToxicClassifier\n\n\ndef test_classifier(config, dataset, checkpoint_path, device=\"cuda:0\"):\n\n model = ToxicClassifier(config)\n checkpoint = torch.load(checkpoint_path, map_location=device)\n model.load_state_dict(checkpoint[\"state_dict\"])\n model.eval()\n model.to(device)\n\n def get_instance(module, name, config, *args, **kwargs):\n return getattr(module, config[name][\"type\"])(*args, **config[name][\"args\"], **kwargs)\n\n config[\"dataset\"][\"args\"][\"test_csv_file\"] = dataset\n\n test_dataset = get_instance(module_data, \"dataset\", config, train=False)\n\n test_data_loader = DataLoader(\n test_dataset,\n batch_size=int(config[\"batch_size\"]),\n num_workers=20,\n shuffle=False,\n )\n\n scores = []\n targets = []\n ids = []\n for *items, meta in tqdm(test_data_loader):\n if \"multi_target\" in meta:\n targets += meta[\"multi_target\"]\n else:\n targets += meta[\"target\"]\n\n ids += meta[\"text_id\"]\n with torch.no_grad():\n out = model.forward(*items)\n # TODO: save embeddings\n sm = torch.sigmoid(out).cpu().detach().numpy()\n scores.extend(sm)\n\n binary_scores = [s >= 0.5 for s in scores]\n binary_scores = np.stack(binary_scores)\n scores = np.stack(scores)\n targets = np.stack(targets)\n auc_scores = []\n\n for class_idx in range(scores.shape[1]):\n mask = targets[:, class_idx] != -1\n target_binary = targets[mask, class_idx]\n class_scores = scores[mask, class_idx]\n try:\n auc = roc_auc_score(target_binary, class_scores)\n auc_scores.append(auc)\n except Exception:\n warnings.warn(\n \"Only one class present in y_true. ROC AUC score is not defined in that case. Set to nan for now.\"\n )\n auc_scores.append(np.nan)\n\n mean_auc = np.mean(auc_scores)\n\n results = {\n \"scores\": scores.tolist(),\n \"targets\": targets.tolist(),\n \"auc_scores\": auc_scores,\n \"mean_auc\": mean_auc,\n \"ids\": [i.tolist() for i in ids],\n }\n\n return results\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"PyTorch Template\")\n parser.add_argument(\n \"-c\",\n \"--config\",\n default=None,\n type=str,\n help=\"config file path (default: None)\",\n )\n parser.add_argument(\n \"-ckpt\",\n \"--checkpoint\",\n type=str,\n help=\"path to a saved checkpoint\",\n )\n parser.add_argument(\n \"-d\",\n \"--device\",\n default=\"cuda:0\",\n type=str,\n help=\"device name e.g., 'cpu' or 'cuda' (default cuda:0)\",\n )\n parser.add_argument(\n \"-t\",\n \"--test_csv\",\n default=None,\n type=str,\n help=\"path to test dataset\",\n )\n\n args = parser.parse_args()\n config = json.load(open(args.config))\n\n if args.device is not None:\n config[\"gpus\"] = args.device\n\n results = test_classifier(config, args.test_csv, args.checkpoint, args.device)\n test_set_name = args.test_csv.split(\"/\")[-1:][0]\n\n with open(args.checkpoint[:-4] + f\"results_{test_set_name}.json\", \"w\") as f:\n json.dump(results, f)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import myThread def main(): hosts={"127.0.0.1":"carpenter"} myThread.messageListenThread(hosts) if __name__ == '__main__': main()
normal
{ "blob_id": "b0a49f5876bc3837b69a6dc274f9587a37351495", "index": 8370, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import myThread\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import myThread\r\n\r\ndef main():\r\n\thosts={\"127.0.0.1\":\"carpenter\"}\r\n\tmyThread.messageListenThread(hosts)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import networkx as nx import pytest from caldera.utils.nx import nx_copy def add_data(g): g.add_node(1) g.add_node(2, x=5) g.add_edge(1, 2, y=6) g.add_edge(2, 3, z=[]) def assert_graph_data(g1, g2): assert g1 is not g2 assert g2.nodes[1] == {} assert g2.nodes[2] == {"x": 5} assert g2.edges[(1, 2)] == {"y": 6} assert g2.edges[(2, 3)] == {"z": []} assert g2.nodes[2] is not g1.nodes[2] assert g2.edges[(2, 3)] is not g1.edges[(2, 3)] @pytest.mark.parametrize("do_deepcopy", [True, False]) def test_nx_copy_with_deepcopy(do_deepcopy): g = nx.Graph() g2 = nx.DiGraph() add_data(g) nx_copy(g, g2, deepcopy=do_deepcopy) assert_graph_data(g, g2) assert (g2.edges[(2, 3)]["z"] is g.edges[(2, 3)]["z"]) != do_deepcopy def test_nx_copy_with_none(): g = nx.Graph() add_data(g) g2 = nx_copy(g, None) assert_graph_data(g, g2) def test_nx_copy_with_class(): g = nx.Graph() add_data(g) g2 = nx_copy(g, nx.OrderedDiGraph) assert isinstance(nx.OrderedDiGraph, type) and issubclass( nx.OrderedDiGraph, nx.Graph ) assert isinstance(g2, nx.OrderedDiGraph) assert_graph_data(g, g2) def test_nx_copy_node_transform(): g = nx.Graph() g.add_node(1) g.add_node(2) g.add_edge(1, 2, f=4) g.add_edge(2, 3, f=5) def node_transform(nodes): for n, ndata in nodes: yield str(n), ndata g2 = nx_copy(g, None, node_transform=node_transform) assert g2.number_of_nodes() == 3 assert g2.number_of_edges() == 2 assert "1" in g2 assert "2" in g2 assert 1 not in g2 assert 2 not in g2 assert g2.edges[("1", "2")] == {"f": 4} assert g2.edges[("2", "3")] == {"f": 5} def test_nx_copy_edge_transform(): g = nx.Graph() g.add_node(1) g.add_node(2) g.add_edge(1, 2, f=4) g.add_edge(2, 3, f=5) g.add_edge(4, 5) assert g.number_of_edges() == 3 assert g.number_of_nodes() == 5 def edge_transform(edges): for n1, n2, edata in edges: if n1 != 4: yield n1, n2, {"f": 8} g2 = nx_copy(g, None, edge_transform=edge_transform) assert g2.number_of_nodes() == 5 assert g2.number_of_edges() == 2 assert g2.edges[(1, 2)] == {"f": 8} assert g2.edges[(2, 3)] == {"f": 8} def test_nx_copy_global_transform(): g = nx.Graph() g.add_node(1) g.add_node(2) g.add_edge(1, 2, f=4) g.add_edge(2, 3, f=5) g.add_edge(4, 5) g.get_global()["f"] = 8 assert g.number_of_edges() == 3 assert g.number_of_nodes() == 5 def global_transform(g): for _, gdata in g: gdata["x"] = 4 yield _, gdata g2 = nx_copy(g, None, global_transform=global_transform) assert g2.get_global() == {"x": 4, "f": 8}
normal
{ "blob_id": "7fe7ea89908f9d233dbdb9e46bf2d677406ab324", "index": 1050, "step-1": "<mask token>\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n assert g2.nodes[2] == {'x': 5}\n assert g2.edges[1, 2] == {'y': 6}\n assert g2.edges[2, 3] == {'z': []}\n assert g2.nodes[2] is not g1.nodes[2]\n assert g2.edges[2, 3] is not g1.edges[2, 3]\n\n\n@pytest.mark.parametrize('do_deepcopy', [True, False])\ndef test_nx_copy_with_deepcopy(do_deepcopy):\n g = nx.Graph()\n g2 = nx.DiGraph()\n add_data(g)\n nx_copy(g, g2, deepcopy=do_deepcopy)\n assert_graph_data(g, g2)\n assert (g2.edges[2, 3]['z'] is g.edges[2, 3]['z']) != do_deepcopy\n\n\ndef test_nx_copy_with_none():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, None)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_with_class():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, nx.OrderedDiGraph)\n assert isinstance(nx.OrderedDiGraph, type) and issubclass(nx.\n OrderedDiGraph, nx.Graph)\n assert isinstance(g2, nx.OrderedDiGraph)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_node_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n\n def node_transform(nodes):\n for n, ndata in nodes:\n yield str(n), ndata\n g2 = nx_copy(g, None, node_transform=node_transform)\n assert g2.number_of_nodes() == 3\n assert g2.number_of_edges() == 2\n assert '1' in g2\n assert '2' in g2\n assert 1 not in g2\n assert 2 not in g2\n assert g2.edges['1', '2'] == {'f': 4}\n assert g2.edges['2', '3'] == {'f': 5}\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n assert g2.nodes[2] == {'x': 5}\n assert g2.edges[1, 2] == {'y': 6}\n assert g2.edges[2, 3] == {'z': []}\n assert g2.nodes[2] is not g1.nodes[2]\n assert g2.edges[2, 3] is not g1.edges[2, 3]\n\n\n@pytest.mark.parametrize('do_deepcopy', [True, False])\ndef test_nx_copy_with_deepcopy(do_deepcopy):\n g = nx.Graph()\n g2 = nx.DiGraph()\n add_data(g)\n nx_copy(g, g2, deepcopy=do_deepcopy)\n assert_graph_data(g, g2)\n assert (g2.edges[2, 3]['z'] is g.edges[2, 3]['z']) != do_deepcopy\n\n\ndef test_nx_copy_with_none():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, None)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_with_class():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, nx.OrderedDiGraph)\n assert isinstance(nx.OrderedDiGraph, type) and issubclass(nx.\n OrderedDiGraph, nx.Graph)\n assert isinstance(g2, nx.OrderedDiGraph)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_node_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n\n def node_transform(nodes):\n for n, ndata in nodes:\n yield str(n), ndata\n g2 = nx_copy(g, None, node_transform=node_transform)\n assert g2.number_of_nodes() == 3\n assert g2.number_of_edges() == 2\n assert '1' in g2\n assert '2' in g2\n assert 1 not in g2\n assert 2 not in g2\n assert g2.edges['1', '2'] == {'f': 4}\n assert g2.edges['2', '3'] == {'f': 5}\n\n\ndef test_nx_copy_edge_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def edge_transform(edges):\n for n1, n2, edata in edges:\n if n1 != 4:\n yield n1, n2, {'f': 8}\n g2 = nx_copy(g, None, edge_transform=edge_transform)\n assert g2.number_of_nodes() == 5\n assert g2.number_of_edges() == 2\n assert g2.edges[1, 2] == {'f': 8}\n assert g2.edges[2, 3] == {'f': 8}\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n assert g2.nodes[2] == {'x': 5}\n assert g2.edges[1, 2] == {'y': 6}\n assert g2.edges[2, 3] == {'z': []}\n assert g2.nodes[2] is not g1.nodes[2]\n assert g2.edges[2, 3] is not g1.edges[2, 3]\n\n\n@pytest.mark.parametrize('do_deepcopy', [True, False])\ndef test_nx_copy_with_deepcopy(do_deepcopy):\n g = nx.Graph()\n g2 = nx.DiGraph()\n add_data(g)\n nx_copy(g, g2, deepcopy=do_deepcopy)\n assert_graph_data(g, g2)\n assert (g2.edges[2, 3]['z'] is g.edges[2, 3]['z']) != do_deepcopy\n\n\ndef test_nx_copy_with_none():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, None)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_with_class():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, nx.OrderedDiGraph)\n assert isinstance(nx.OrderedDiGraph, type) and issubclass(nx.\n OrderedDiGraph, nx.Graph)\n assert isinstance(g2, nx.OrderedDiGraph)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_node_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n\n def node_transform(nodes):\n for n, ndata in nodes:\n yield str(n), ndata\n g2 = nx_copy(g, None, node_transform=node_transform)\n assert g2.number_of_nodes() == 3\n assert g2.number_of_edges() == 2\n assert '1' in g2\n assert '2' in g2\n assert 1 not in g2\n assert 2 not in g2\n assert g2.edges['1', '2'] == {'f': 4}\n assert g2.edges['2', '3'] == {'f': 5}\n\n\ndef test_nx_copy_edge_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def edge_transform(edges):\n for n1, n2, edata in edges:\n if n1 != 4:\n yield n1, n2, {'f': 8}\n g2 = nx_copy(g, None, edge_transform=edge_transform)\n assert g2.number_of_nodes() == 5\n assert g2.number_of_edges() == 2\n assert g2.edges[1, 2] == {'f': 8}\n assert g2.edges[2, 3] == {'f': 8}\n\n\ndef test_nx_copy_global_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n g.get_global()['f'] = 8\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def global_transform(g):\n for _, gdata in g:\n gdata['x'] = 4\n yield _, gdata\n g2 = nx_copy(g, None, global_transform=global_transform)\n assert g2.get_global() == {'x': 4, 'f': 8}\n", "step-4": "import networkx as nx\nimport pytest\nfrom caldera.utils.nx import nx_copy\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n assert g2.nodes[2] == {'x': 5}\n assert g2.edges[1, 2] == {'y': 6}\n assert g2.edges[2, 3] == {'z': []}\n assert g2.nodes[2] is not g1.nodes[2]\n assert g2.edges[2, 3] is not g1.edges[2, 3]\n\n\n@pytest.mark.parametrize('do_deepcopy', [True, False])\ndef test_nx_copy_with_deepcopy(do_deepcopy):\n g = nx.Graph()\n g2 = nx.DiGraph()\n add_data(g)\n nx_copy(g, g2, deepcopy=do_deepcopy)\n assert_graph_data(g, g2)\n assert (g2.edges[2, 3]['z'] is g.edges[2, 3]['z']) != do_deepcopy\n\n\ndef test_nx_copy_with_none():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, None)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_with_class():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, nx.OrderedDiGraph)\n assert isinstance(nx.OrderedDiGraph, type) and issubclass(nx.\n OrderedDiGraph, nx.Graph)\n assert isinstance(g2, nx.OrderedDiGraph)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_node_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n\n def node_transform(nodes):\n for n, ndata in nodes:\n yield str(n), ndata\n g2 = nx_copy(g, None, node_transform=node_transform)\n assert g2.number_of_nodes() == 3\n assert g2.number_of_edges() == 2\n assert '1' in g2\n assert '2' in g2\n assert 1 not in g2\n assert 2 not in g2\n assert g2.edges['1', '2'] == {'f': 4}\n assert g2.edges['2', '3'] == {'f': 5}\n\n\ndef test_nx_copy_edge_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def edge_transform(edges):\n for n1, n2, edata in edges:\n if n1 != 4:\n yield n1, n2, {'f': 8}\n g2 = nx_copy(g, None, edge_transform=edge_transform)\n assert g2.number_of_nodes() == 5\n assert g2.number_of_edges() == 2\n assert g2.edges[1, 2] == {'f': 8}\n assert g2.edges[2, 3] == {'f': 8}\n\n\ndef test_nx_copy_global_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n g.get_global()['f'] = 8\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def global_transform(g):\n for _, gdata in g:\n gdata['x'] = 4\n yield _, gdata\n g2 = nx_copy(g, None, global_transform=global_transform)\n assert g2.get_global() == {'x': 4, 'f': 8}\n", "step-5": "import networkx as nx\nimport pytest\n\nfrom caldera.utils.nx import nx_copy\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n assert g2.nodes[2] == {\"x\": 5}\n assert g2.edges[(1, 2)] == {\"y\": 6}\n assert g2.edges[(2, 3)] == {\"z\": []}\n assert g2.nodes[2] is not g1.nodes[2]\n assert g2.edges[(2, 3)] is not g1.edges[(2, 3)]\n\n\n@pytest.mark.parametrize(\"do_deepcopy\", [True, False])\ndef test_nx_copy_with_deepcopy(do_deepcopy):\n g = nx.Graph()\n g2 = nx.DiGraph()\n add_data(g)\n nx_copy(g, g2, deepcopy=do_deepcopy)\n assert_graph_data(g, g2)\n assert (g2.edges[(2, 3)][\"z\"] is g.edges[(2, 3)][\"z\"]) != do_deepcopy\n\n\ndef test_nx_copy_with_none():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, None)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_with_class():\n g = nx.Graph()\n add_data(g)\n g2 = nx_copy(g, nx.OrderedDiGraph)\n assert isinstance(nx.OrderedDiGraph, type) and issubclass(\n nx.OrderedDiGraph, nx.Graph\n )\n assert isinstance(g2, nx.OrderedDiGraph)\n assert_graph_data(g, g2)\n\n\ndef test_nx_copy_node_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n\n def node_transform(nodes):\n for n, ndata in nodes:\n yield str(n), ndata\n\n g2 = nx_copy(g, None, node_transform=node_transform)\n assert g2.number_of_nodes() == 3\n assert g2.number_of_edges() == 2\n assert \"1\" in g2\n assert \"2\" in g2\n assert 1 not in g2\n assert 2 not in g2\n assert g2.edges[(\"1\", \"2\")] == {\"f\": 4}\n assert g2.edges[(\"2\", \"3\")] == {\"f\": 5}\n\n\ndef test_nx_copy_edge_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def edge_transform(edges):\n for n1, n2, edata in edges:\n if n1 != 4:\n yield n1, n2, {\"f\": 8}\n\n g2 = nx_copy(g, None, edge_transform=edge_transform)\n assert g2.number_of_nodes() == 5\n assert g2.number_of_edges() == 2\n assert g2.edges[(1, 2)] == {\"f\": 8}\n assert g2.edges[(2, 3)] == {\"f\": 8}\n\n\ndef test_nx_copy_global_transform():\n g = nx.Graph()\n g.add_node(1)\n g.add_node(2)\n g.add_edge(1, 2, f=4)\n g.add_edge(2, 3, f=5)\n g.add_edge(4, 5)\n g.get_global()[\"f\"] = 8\n assert g.number_of_edges() == 3\n assert g.number_of_nodes() == 5\n\n def global_transform(g):\n for _, gdata in g:\n gdata[\"x\"] = 4\n yield _, gdata\n\n g2 = nx_copy(g, None, global_transform=global_transform)\n assert g2.get_global() == {\"x\": 4, \"f\": 8}\n", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
import cgi from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from models.nutrient import * class SoilRecord(db.Model): year=db.DateProperty(auto_now_add=True) stats=NutrientProfile() amendments=db.StringProperty() notes=db.StringProperty() @property def plot(self): Plot.gql("Where soilrecord=:1",self.key()) def create(self, year): self.year=year class CropRecord(db.Model): year=db.DateProperty(auto_now_add=True) crops=db.ListProperty(db.Key) notes=db.StringProperty() @property def plot(self): Plot.gql("Where croprecord=:1",self.key()) def create(self, year): self.year=year def addCrop(self, crop): if addByKey(crop, self.crops): self.put()
normal
{ "blob_id": "01a6283d2331590082cdf1d409ecdb6f93459882", "index": 4861, "step-1": "<mask token>\n\n\nclass CropRecord(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass CropRecord(db.Model):\n year = db.DateProperty(auto_now_add=True)\n crops = db.ListProperty(db.Key)\n notes = db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql('Where croprecord=:1', self.key())\n\n def create(self, year):\n self.year = year\n\n def addCrop(self, crop):\n if addByKey(crop, self.crops):\n self.put()\n", "step-3": "<mask token>\n\n\nclass SoilRecord(db.Model):\n year = db.DateProperty(auto_now_add=True)\n stats = NutrientProfile()\n amendments = db.StringProperty()\n notes = db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql('Where soilrecord=:1', self.key())\n\n def create(self, year):\n self.year = year\n\n\nclass CropRecord(db.Model):\n year = db.DateProperty(auto_now_add=True)\n crops = db.ListProperty(db.Key)\n notes = db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql('Where croprecord=:1', self.key())\n\n def create(self, year):\n self.year = year\n\n def addCrop(self, crop):\n if addByKey(crop, self.crops):\n self.put()\n", "step-4": "import cgi\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom models.nutrient import *\n\n\nclass SoilRecord(db.Model):\n year = db.DateProperty(auto_now_add=True)\n stats = NutrientProfile()\n amendments = db.StringProperty()\n notes = db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql('Where soilrecord=:1', self.key())\n\n def create(self, year):\n self.year = year\n\n\nclass CropRecord(db.Model):\n year = db.DateProperty(auto_now_add=True)\n crops = db.ListProperty(db.Key)\n notes = db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql('Where croprecord=:1', self.key())\n\n def create(self, year):\n self.year = year\n\n def addCrop(self, crop):\n if addByKey(crop, self.crops):\n self.put()\n", "step-5": "import cgi\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom models.nutrient import *\nclass SoilRecord(db.Model):\n year=db.DateProperty(auto_now_add=True)\n stats=NutrientProfile()\n amendments=db.StringProperty()\n notes=db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql(\"Where soilrecord=:1\",self.key())\n\n def create(self, year):\n self.year=year\n\nclass CropRecord(db.Model):\n year=db.DateProperty(auto_now_add=True)\n crops=db.ListProperty(db.Key)\n notes=db.StringProperty()\n\n @property\n def plot(self):\n Plot.gql(\"Where croprecord=:1\",self.key())\n\n\n def create(self, year):\n self.year=year\n\n def addCrop(self, crop):\n if addByKey(crop, self.crops):\n self.put()\n\n", "step-ids": [ 1, 5, 9, 10, 11 ] }
[ 1, 5, 9, 10, 11 ]
name = input("Enter your name: ") print("Hi buddy! Today we will play a game " + name + "!") print("Are you ready?") question = input("Are you ready ? Yes or no: ") print(name + " we are starting!") liste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog '] num = input("Enter a number: ") liste1 = liste1[int(num)] liste2 = ['hates ', 'loves ', 'enjoys ', 'ridicules '] num = input("Enter a number: ") liste2 = liste2[int(num)] liste3 = ['with me ', 'with my grandma ', 'with our home staff ', 'with our money '] num = input("Enter a number: ") liste3 = liste3[int(num)] liste4 = ['in every situation ! ', 'until end of the world ! '] num = input("Enter a number: ") liste4 = liste4[int(num)] print(liste1 + liste2 + liste3 + liste4)
normal
{ "blob_id": "4ef6002480fcaa514f41227978bae76f6e02c22d", "index": 6401, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Hi buddy! Today we will play a game ' + name + '!')\nprint('Are you ready?')\n<mask token>\nprint(name + ' we are starting!')\n<mask token>\nprint(liste1 + liste2 + liste3 + liste4)\n", "step-3": "name = input('Enter your name: ')\nprint('Hi buddy! Today we will play a game ' + name + '!')\nprint('Are you ready?')\nquestion = input('Are you ready ? Yes or no: ')\nprint(name + ' we are starting!')\nliste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']\nnum = input('Enter a number: ')\nliste1 = liste1[int(num)]\nliste2 = ['hates ', 'loves ', 'enjoys ', 'ridicules ']\nnum = input('Enter a number: ')\nliste2 = liste2[int(num)]\nliste3 = ['with me ', 'with my grandma ', 'with our home staff ',\n 'with our money ']\nnum = input('Enter a number: ')\nliste3 = liste3[int(num)]\nliste4 = ['in every situation ! ', 'until end of the world ! ']\nnum = input('Enter a number: ')\nliste4 = liste4[int(num)]\nprint(liste1 + liste2 + liste3 + liste4)\n", "step-4": "name = input(\"Enter your name: \")\r\nprint(\"Hi buddy! Today we will play a game \" + name + \"!\")\r\n\r\nprint(\"Are you ready?\")\r\n\r\nquestion = input(\"Are you ready ? Yes or no: \")\r\nprint(name + \" we are starting!\")\r\n\r\n\r\nliste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']\r\nnum = input(\"Enter a number: \")\r\n\r\nliste1 = liste1[int(num)]\r\n\r\nliste2 = ['hates ', 'loves ', 'enjoys ', 'ridicules ']\r\nnum = input(\"Enter a number: \")\r\n\r\nliste2 = liste2[int(num)]\r\n\r\nliste3 = ['with me ', 'with my grandma ', 'with our home staff ', 'with our money ']\r\nnum = input(\"Enter a number: \")\r\n\r\nliste3 = liste3[int(num)]\r\n\r\nliste4 = ['in every situation ! ', 'until end of the world ! ']\r\nnum = input(\"Enter a number: \")\r\n\r\nliste4 = liste4[int(num)]\r\n\r\nprint(liste1 + liste2 + liste3 + liste4)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import heapq class Solution: #priority queue # def sortElemsByFrequency(self, arr): # if arr: # mydict = {} # for k,v in enumerate(arr): # mydict[v] = mydict.get(v, 0) + 1 # sorted_dict = sorted(mydict.items(), key = lambda x:x[1]) # return sorted_dict def sortElemsByFrequency(self, arr): if arr: x = [] res = [] mydict = {} for k,v in enumerate(arr): mydict[v] = mydict.get(v, 0) + 1 for k,v in mydict.items(): heapq.heappush(x, (v,k)) while x: res.insert(0, heapq.heappop(x)[1]) return res sol = Solution() res = sol.sortElemsByFrequency([2, 5, 2, 8, 5, 6, 8, 8]) print(res)
normal
{ "blob_id": "dcb12e282962c63f8e7de5d29c4c81ad177a387e", "index": 7775, "step-1": "<mask token>\n\n\nclass Solution:\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k, v in enumerate(arr):\n mydict[v] = mydict.get(v, 0) + 1\n for k, v in mydict.items():\n heapq.heappush(x, (v, k))\n while x:\n res.insert(0, heapq.heappop(x)[1])\n return res\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k, v in enumerate(arr):\n mydict[v] = mydict.get(v, 0) + 1\n for k, v in mydict.items():\n heapq.heappush(x, (v, k))\n while x:\n res.insert(0, heapq.heappop(x)[1])\n return res\n\n\n<mask token>\nprint(res)\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k, v in enumerate(arr):\n mydict[v] = mydict.get(v, 0) + 1\n for k, v in mydict.items():\n heapq.heappush(x, (v, k))\n while x:\n res.insert(0, heapq.heappop(x)[1])\n return res\n\n\nsol = Solution()\nres = sol.sortElemsByFrequency([2, 5, 2, 8, 5, 6, 8, 8])\nprint(res)\n", "step-4": "import heapq\n\n\nclass Solution:\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k, v in enumerate(arr):\n mydict[v] = mydict.get(v, 0) + 1\n for k, v in mydict.items():\n heapq.heappush(x, (v, k))\n while x:\n res.insert(0, heapq.heappop(x)[1])\n return res\n\n\nsol = Solution()\nres = sol.sortElemsByFrequency([2, 5, 2, 8, 5, 6, 8, 8])\nprint(res)\n", "step-5": "import heapq\nclass Solution: #priority queue\n # def sortElemsByFrequency(self, arr):\n # if arr:\n # mydict = {}\n # for k,v in enumerate(arr):\n # mydict[v] = mydict.get(v, 0) + 1\n # sorted_dict = sorted(mydict.items(), key = lambda x:x[1])\n # return sorted_dict\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k,v in enumerate(arr):\n mydict[v] = mydict.get(v, 0) + 1\n for k,v in mydict.items():\n heapq.heappush(x, (v,k))\n while x:\n res.insert(0, heapq.heappop(x)[1])\n return res\n\nsol = Solution()\nres = sol.sortElemsByFrequency([2, 5, 2, 8, 5, 6, 8, 8])\nprint(res)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
def is_prime(x): divisor = 2 while divisor <= x**(1/2.0): if x % divisor == 0: return False divisor += 1 return True for j in range(int(raw_input())): a, b = map(int, raw_input().split()) count = 0 if a == 2: a += 1 count += 1 elif a % 2 == 0: a += 1 elif a == 1: a += 2 count += 1 for i in range(a, b, 2): if is_prime(i): count += 1 print count
normal
{ "blob_id": "e3a59a1ae65dd86ff2f5dcc15d4df9e8dc451990", "index": 8587, "step-1": "def is_prime(x):\r\n divisor = 2\r\n while divisor <= x**(1/2.0):\r\n if x % divisor == 0:\r\n return False\r\n divisor += 1\r\n return True\r\n\r\nfor j in range(int(raw_input())):\r\n a, b = map(int, raw_input().split())\r\n count = 0\r\n\r\n if a == 2:\r\n a += 1\r\n count += 1\r\n elif a % 2 == 0:\r\n a += 1\r\n elif a == 1:\r\n a += 2\r\n count += 1\r\n\r\n for i in range(a, b, 2):\r\n if is_prime(i):\r\n count += 1\r\n\r\n print count\r\n \r\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#coding=utf-8 ''' find words and count By @liuxingpuu ''' import re fin= open("example","r") fout = open("reuslt.txt","w") str=fin.read() reObj = re.compile("\b?([a-zA-Z]+)\b?") words = reObj.findall(str) word_dict={} for word in words: if(word_dict.has_key(word)): word_dict[word.lower()]=max(word_dict[word.lower()],words.count(word.lower())+words.count(word.upper())+words.count(word)) else: word_dict[word.lower()]=max(0,words.count(word.lower())+words.count(word.upper())+words.count(word)) for(word,number) in word_dict.items(): fout.write(word+":%d\n"%number)
normal
{ "blob_id": "addab37cb23abead2d9f77a65336cd6026c52c68", "index": 8559, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor word in words:\n if word_dict.has_key(word):\n word_dict[word.lower()] = max(word_dict[word.lower()], words.count(\n word.lower()) + words.count(word.upper()) + words.count(word))\n else:\n word_dict[word.lower()] = max(0, words.count(word.lower()) + words.\n count(word.upper()) + words.count(word))\nfor word, number in word_dict.items():\n fout.write(word + ':%d\\n' % number)\n", "step-3": "<mask token>\nfin = open('example', 'r')\nfout = open('reuslt.txt', 'w')\nstr = fin.read()\nreObj = re.compile('\\x08?([a-zA-Z]+)\\x08?')\nwords = reObj.findall(str)\nword_dict = {}\nfor word in words:\n if word_dict.has_key(word):\n word_dict[word.lower()] = max(word_dict[word.lower()], words.count(\n word.lower()) + words.count(word.upper()) + words.count(word))\n else:\n word_dict[word.lower()] = max(0, words.count(word.lower()) + words.\n count(word.upper()) + words.count(word))\nfor word, number in word_dict.items():\n fout.write(word + ':%d\\n' % number)\n", "step-4": "<mask token>\nimport re\nfin = open('example', 'r')\nfout = open('reuslt.txt', 'w')\nstr = fin.read()\nreObj = re.compile('\\x08?([a-zA-Z]+)\\x08?')\nwords = reObj.findall(str)\nword_dict = {}\nfor word in words:\n if word_dict.has_key(word):\n word_dict[word.lower()] = max(word_dict[word.lower()], words.count(\n word.lower()) + words.count(word.upper()) + words.count(word))\n else:\n word_dict[word.lower()] = max(0, words.count(word.lower()) + words.\n count(word.upper()) + words.count(word))\nfor word, number in word_dict.items():\n fout.write(word + ':%d\\n' % number)\n", "step-5": "#coding=utf-8\n'''\nfind words and count\nBy @liuxingpuu\n'''\nimport re\n\nfin= open(\"example\",\"r\")\nfout = open(\"reuslt.txt\",\"w\")\nstr=fin.read()\nreObj = re.compile(\"\\b?([a-zA-Z]+)\\b?\")\nwords = reObj.findall(str)\nword_dict={}\nfor word in words:\n if(word_dict.has_key(word)):\n word_dict[word.lower()]=max(word_dict[word.lower()],words.count(word.lower())+words.count(word.upper())+words.count(word))\n else:\n word_dict[word.lower()]=max(0,words.count(word.lower())+words.count(word.upper())+words.count(word))\nfor(word,number) in word_dict.items():\n fout.write(word+\":%d\\n\"%number)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#pymongo and mongo DB search is like by line inside in a document then it moves to the other document from enum import unique import pymongo from pymongo import MongoClient MyClient = MongoClient() # again this is connecting to deault host and port db = MyClient.mydatabase #db is a variable to store the database my database users = db.users #this is the table db.users.create_index([("names" ,pymongo.ASCENDING)]) #to create an in dex for a whole row
normal
{ "blob_id": "31f302775ef19a07137622ef9d33495cc2a8eed2", "index": 5775, "step-1": "<mask token>\n", "step-2": "<mask token>\ndb.users.create_index([('names', pymongo.ASCENDING)])\n", "step-3": "<mask token>\nMyClient = MongoClient()\ndb = MyClient.mydatabase\nusers = db.users\ndb.users.create_index([('names', pymongo.ASCENDING)])\n", "step-4": "from enum import unique\nimport pymongo\nfrom pymongo import MongoClient\nMyClient = MongoClient()\ndb = MyClient.mydatabase\nusers = db.users\ndb.users.create_index([('names', pymongo.ASCENDING)])\n", "step-5": "#pymongo and mongo DB search is like by line inside in a document then it moves to the other document\nfrom enum import unique\n\nimport pymongo\nfrom pymongo import MongoClient\n\nMyClient = MongoClient() # again this is connecting to deault host and port\n\ndb = MyClient.mydatabase #db is a variable to store the database my database\n\nusers = db.users #this is the table\n\ndb.users.create_index([(\"names\" ,pymongo.ASCENDING)]) #to create an in dex for a whole row\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.2.2 on 2019-07-17 10:02 from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('users', '0003_delete_userprofile'), ] operations = [ migrations.CreateModel( name='Subscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=255)), ('subscribe_to', models.CharField(choices=[('jobs', 'Jobs'), ('posts', 'Posts'), ('newsletter', 'Newsletter')], max_length=100)), ('department', modelcluster.fields.ParentalKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='department_subscriptions', to='users.Department')), ], options={ 'verbose_name': 'Subscription', 'verbose_name_plural': 'Subscriptions', }, ), ]
normal
{ "blob_id": "cf2c57dbb2c1160321bcd6de98691db48634d5d6", "index": 5388, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('users', '0003_delete_userprofile')]\n operations = [migrations.CreateModel(name='Subscription', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('email', models.EmailField(max_length=\n 255)), ('subscribe_to', models.CharField(choices=[('jobs', 'Jobs'),\n ('posts', 'Posts'), ('newsletter', 'Newsletter')], max_length=100)),\n ('department', modelcluster.fields.ParentalKey(null=True, on_delete\n =django.db.models.deletion.CASCADE, related_name=\n 'department_subscriptions', to='users.Department'))], options={\n 'verbose_name': 'Subscription', 'verbose_name_plural':\n 'Subscriptions'})]\n", "step-4": "from django.db import migrations, models\nimport django.db.models.deletion\nimport modelcluster.fields\n\n\nclass Migration(migrations.Migration):\n dependencies = [('users', '0003_delete_userprofile')]\n operations = [migrations.CreateModel(name='Subscription', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('email', models.EmailField(max_length=\n 255)), ('subscribe_to', models.CharField(choices=[('jobs', 'Jobs'),\n ('posts', 'Posts'), ('newsletter', 'Newsletter')], max_length=100)),\n ('department', modelcluster.fields.ParentalKey(null=True, on_delete\n =django.db.models.deletion.CASCADE, related_name=\n 'department_subscriptions', to='users.Department'))], options={\n 'verbose_name': 'Subscription', 'verbose_name_plural':\n 'Subscriptions'})]\n", "step-5": "# Generated by Django 2.2.2 on 2019-07-17 10:02\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport modelcluster.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0003_delete_userprofile'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Subscription',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('email', models.EmailField(max_length=255)),\n ('subscribe_to', models.CharField(choices=[('jobs', 'Jobs'), ('posts', 'Posts'), ('newsletter', 'Newsletter')], max_length=100)),\n ('department', modelcluster.fields.ParentalKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='department_subscriptions', to='users.Department')),\n ],\n options={\n 'verbose_name': 'Subscription',\n 'verbose_name_plural': 'Subscriptions',\n },\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import ast import datetime from pathlib import Path from typing import Any, Dict import yaml from .lemmatizer import LemmatizerPymorphy2, Preprocessor def get_config(path_to_config: str) -> Dict[str, Any]: """Get config. Args: path_to_config (str): Path to config. Returns: Dict[str, Any]: Config. """ with open(path_to_config, mode="r") as fp: config = yaml.safe_load(fp) # backward compatibility if "experiment_name" not in config: config["experiment_name"] = "model" config["path_to_save_folder"] = ( Path(config["path_to_save_folder"]) / f"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}" ) config["path_to_config"] = path_to_config config["path_to_save_model"] = config["path_to_save_folder"] / "model.joblib" config["path_to_save_logfile"] = config["path_to_save_folder"] / "logging.txt" config["path_to_save_target_names_mapping"] = ( config["path_to_save_folder"] / "target_names.json" ) # tf-idf if ("tf-idf" not in config) or (config["tf-idf"] is None): config["tf-idf"] = {} if "ngram_range" in config["tf-idf"]: config["tf-idf"]["ngram_range"] = ast.literal_eval( config["tf-idf"]["ngram_range"] ) if "preprocessing" in config: # backward compatibility lemmatization = config["preprocessing"]["lemmatization"] if lemmatization: if lemmatization == "pymorphy2": lemmatizer = LemmatizerPymorphy2() preprocessor = Preprocessor(lemmatizer) config["tf-idf"]["preprocessor"] = preprocessor else: raise KeyError( f"Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2." ) # logreg if ("logreg" not in config) or (config["logreg"] is None): config["logreg"] = {} return config
normal
{ "blob_id": "c85d7e799a652e82bfaf58e1e8bfa9c4606a8ecb", "index": 917, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_config(path_to_config: str) ->Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n with open(path_to_config, mode='r') as fp:\n config = yaml.safe_load(fp)\n if 'experiment_name' not in config:\n config['experiment_name'] = 'model'\n config['path_to_save_folder'] = (Path(config['path_to_save_folder']) /\n f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n config['path_to_config'] = path_to_config\n config['path_to_save_model'] = config['path_to_save_folder'\n ] / 'model.joblib'\n config['path_to_save_logfile'] = config['path_to_save_folder'\n ] / 'logging.txt'\n config['path_to_save_target_names_mapping'] = config['path_to_save_folder'\n ] / 'target_names.json'\n if 'tf-idf' not in config or config['tf-idf'] is None:\n config['tf-idf'] = {}\n if 'ngram_range' in config['tf-idf']:\n config['tf-idf']['ngram_range'] = ast.literal_eval(config['tf-idf']\n ['ngram_range'])\n if 'preprocessing' in config:\n lemmatization = config['preprocessing']['lemmatization']\n if lemmatization:\n if lemmatization == 'pymorphy2':\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n config['tf-idf']['preprocessor'] = preprocessor\n else:\n raise KeyError(\n f'Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.'\n )\n if 'logreg' not in config or config['logreg'] is None:\n config['logreg'] = {}\n return config\n", "step-3": "import ast\nimport datetime\nfrom pathlib import Path\nfrom typing import Any, Dict\nimport yaml\nfrom .lemmatizer import LemmatizerPymorphy2, Preprocessor\n\n\ndef get_config(path_to_config: str) ->Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n with open(path_to_config, mode='r') as fp:\n config = yaml.safe_load(fp)\n if 'experiment_name' not in config:\n config['experiment_name'] = 'model'\n config['path_to_save_folder'] = (Path(config['path_to_save_folder']) /\n f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n config['path_to_config'] = path_to_config\n config['path_to_save_model'] = config['path_to_save_folder'\n ] / 'model.joblib'\n config['path_to_save_logfile'] = config['path_to_save_folder'\n ] / 'logging.txt'\n config['path_to_save_target_names_mapping'] = config['path_to_save_folder'\n ] / 'target_names.json'\n if 'tf-idf' not in config or config['tf-idf'] is None:\n config['tf-idf'] = {}\n if 'ngram_range' in config['tf-idf']:\n config['tf-idf']['ngram_range'] = ast.literal_eval(config['tf-idf']\n ['ngram_range'])\n if 'preprocessing' in config:\n lemmatization = config['preprocessing']['lemmatization']\n if lemmatization:\n if lemmatization == 'pymorphy2':\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n config['tf-idf']['preprocessor'] = preprocessor\n else:\n raise KeyError(\n f'Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.'\n )\n if 'logreg' not in config or config['logreg'] is None:\n config['logreg'] = {}\n return config\n", "step-4": "import ast\nimport datetime\nfrom pathlib import Path\nfrom typing import Any, Dict\n\nimport yaml\n\nfrom .lemmatizer import LemmatizerPymorphy2, Preprocessor\n\n\ndef get_config(path_to_config: str) -> Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config.\n \"\"\"\n\n with open(path_to_config, mode=\"r\") as fp:\n config = yaml.safe_load(fp)\n\n # backward compatibility\n if \"experiment_name\" not in config:\n config[\"experiment_name\"] = \"model\"\n\n config[\"path_to_save_folder\"] = (\n Path(config[\"path_to_save_folder\"])\n / f\"{config['experiment_name']}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}\"\n )\n\n config[\"path_to_config\"] = path_to_config\n config[\"path_to_save_model\"] = config[\"path_to_save_folder\"] / \"model.joblib\"\n config[\"path_to_save_logfile\"] = config[\"path_to_save_folder\"] / \"logging.txt\"\n config[\"path_to_save_target_names_mapping\"] = (\n config[\"path_to_save_folder\"] / \"target_names.json\"\n )\n\n # tf-idf\n if (\"tf-idf\" not in config) or (config[\"tf-idf\"] is None):\n config[\"tf-idf\"] = {}\n if \"ngram_range\" in config[\"tf-idf\"]:\n config[\"tf-idf\"][\"ngram_range\"] = ast.literal_eval(\n config[\"tf-idf\"][\"ngram_range\"]\n )\n\n if \"preprocessing\" in config: # backward compatibility\n lemmatization = config[\"preprocessing\"][\"lemmatization\"]\n\n if lemmatization:\n if lemmatization == \"pymorphy2\":\n lemmatizer = LemmatizerPymorphy2()\n preprocessor = Preprocessor(lemmatizer)\n\n config[\"tf-idf\"][\"preprocessor\"] = preprocessor\n\n else:\n raise KeyError(\n f\"Unknown lemmatizer {lemmatization}. Available lemmatizers: none, pymorphy2.\"\n )\n\n # logreg\n if (\"logreg\" not in config) or (config[\"logreg\"] is None):\n config[\"logreg\"] = {}\n\n return config\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.shortcuts import render, get_object_or_404, redirect #from emailupdate.forms import emailupdate_form from forms import EmailForm from django.utils import timezone def index(request): if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.signup_date = timezone.now() post.email_confirmed = True post.save() return redirect('/emailupdate/thanks/') else: form_class = EmailForm return render(request, 'emailupdate/emailupdate.html', { 'form': form_class, }) def thanks(request): return render(request, 'emailupdate/emailupdate_thanks.html')
normal
{ "blob_id": "f2cdee7e5eebaeeb784cb901c3ac6301e90ac7b9", "index": 866, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef index(request):\n if request.method == 'POST':\n form = EmailForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.signup_date = timezone.now()\n post.email_confirmed = True\n post.save()\n return redirect('/emailupdate/thanks/')\n else:\n form_class = EmailForm\n return render(request, 'emailupdate/emailupdate.html', {'form':\n form_class})\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef index(request):\n if request.method == 'POST':\n form = EmailForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.signup_date = timezone.now()\n post.email_confirmed = True\n post.save()\n return redirect('/emailupdate/thanks/')\n else:\n form_class = EmailForm\n return render(request, 'emailupdate/emailupdate.html', {'form':\n form_class})\n\n\ndef thanks(request):\n return render(request, 'emailupdate/emailupdate_thanks.html')\n", "step-4": "from django.shortcuts import render, get_object_or_404, redirect\nfrom forms import EmailForm\nfrom django.utils import timezone\n\n\ndef index(request):\n if request.method == 'POST':\n form = EmailForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.signup_date = timezone.now()\n post.email_confirmed = True\n post.save()\n return redirect('/emailupdate/thanks/')\n else:\n form_class = EmailForm\n return render(request, 'emailupdate/emailupdate.html', {'form':\n form_class})\n\n\ndef thanks(request):\n return render(request, 'emailupdate/emailupdate_thanks.html')\n", "step-5": "from django.shortcuts import render, get_object_or_404, redirect\n#from emailupdate.forms import emailupdate_form\nfrom forms import EmailForm\nfrom django.utils import timezone\n\ndef index(request):\n\tif request.method == \"POST\":\n\t\tform = EmailForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.signup_date = timezone.now()\n\t\t\tpost.email_confirmed = True\n\t\t\tpost.save()\n\t\t\treturn redirect('/emailupdate/thanks/')\n\telse:\n\t\tform_class = EmailForm\n\t\treturn render(request, 'emailupdate/emailupdate.html', {\n\t\t\t'form': form_class,\n\t\t})\t\n\ndef thanks(request):\n\treturn render(request, 'emailupdate/emailupdate_thanks.html')", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import time from helpers.handler import port_handler from helpers.functions import fetch_all class ascii_handler(port_handler): """ Serve ASCII server list """ def handle_data(self): """ Show a nicely formatted server list and immediately close connection """ self.ls.log.info("Sending ascii server list to %s" % self.ip) self.cleanup() servers = fetch_all( "SELECT * FROM servers WHERE max > 0 ORDER BY prefer DESC, private ASC, (players = max) ASC, players DESC, created ASC") asciilist = "" server_count = 0 for server in servers: try: entry = server['ip'] + ':' + str(server['port']) + ' ' # ip:port entry += 'local ' if server['remote'] == 0 else 'mirror ' # 'local' or 'mirror' entry += 'public ' if server['private'] == 0 else 'private ' # 'public' or 'private' entry += server['mode'] + ' ' # game mode entry += server['version'][:6].ljust(6, ' ') + ' ' # version entry += str(int(time.time()) - int(server['created'])) + ' ' # uptime in seconds entry += '[' + str(server['players']) + '/' + str(server['max']) + '] ' # [players/max] entry += server['name'] + "\r\n" # server name asciilist += entry server_count += 1 except TypeError: continue self.msg(asciilist) self.end()
normal
{ "blob_id": "cbf93eb96f40ff0aedc4b8d9238669da72934b27", "index": 2400, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ascii_handler(port_handler):\n <mask token>\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n \"\"\"\n self.ls.log.info('Sending ascii server list to %s' % self.ip)\n self.cleanup()\n servers = fetch_all(\n 'SELECT * FROM servers WHERE max > 0 ORDER BY prefer DESC, private ASC, (players = max) ASC, players DESC, created ASC'\n )\n asciilist = ''\n server_count = 0\n for server in servers:\n try:\n entry = server['ip'] + ':' + str(server['port']) + ' '\n entry += 'local ' if server['remote'] == 0 else 'mirror '\n entry += 'public ' if server['private'] == 0 else 'private '\n entry += server['mode'] + ' '\n entry += server['version'][:6].ljust(6, ' ') + ' '\n entry += str(int(time.time()) - int(server['created'])) + ' '\n entry += '[' + str(server['players']) + '/' + str(server['max']\n ) + '] '\n entry += server['name'] + '\\r\\n'\n asciilist += entry\n server_count += 1\n except TypeError:\n continue\n self.msg(asciilist)\n self.end()\n", "step-3": "<mask token>\n\n\nclass ascii_handler(port_handler):\n \"\"\"\n Serve ASCII server list\n \"\"\"\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n \"\"\"\n self.ls.log.info('Sending ascii server list to %s' % self.ip)\n self.cleanup()\n servers = fetch_all(\n 'SELECT * FROM servers WHERE max > 0 ORDER BY prefer DESC, private ASC, (players = max) ASC, players DESC, created ASC'\n )\n asciilist = ''\n server_count = 0\n for server in servers:\n try:\n entry = server['ip'] + ':' + str(server['port']) + ' '\n entry += 'local ' if server['remote'] == 0 else 'mirror '\n entry += 'public ' if server['private'] == 0 else 'private '\n entry += server['mode'] + ' '\n entry += server['version'][:6].ljust(6, ' ') + ' '\n entry += str(int(time.time()) - int(server['created'])) + ' '\n entry += '[' + str(server['players']) + '/' + str(server['max']\n ) + '] '\n entry += server['name'] + '\\r\\n'\n asciilist += entry\n server_count += 1\n except TypeError:\n continue\n self.msg(asciilist)\n self.end()\n", "step-4": "import time\nfrom helpers.handler import port_handler\nfrom helpers.functions import fetch_all\n\n\nclass ascii_handler(port_handler):\n \"\"\"\n Serve ASCII server list\n \"\"\"\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n \"\"\"\n self.ls.log.info('Sending ascii server list to %s' % self.ip)\n self.cleanup()\n servers = fetch_all(\n 'SELECT * FROM servers WHERE max > 0 ORDER BY prefer DESC, private ASC, (players = max) ASC, players DESC, created ASC'\n )\n asciilist = ''\n server_count = 0\n for server in servers:\n try:\n entry = server['ip'] + ':' + str(server['port']) + ' '\n entry += 'local ' if server['remote'] == 0 else 'mirror '\n entry += 'public ' if server['private'] == 0 else 'private '\n entry += server['mode'] + ' '\n entry += server['version'][:6].ljust(6, ' ') + ' '\n entry += str(int(time.time()) - int(server['created'])) + ' '\n entry += '[' + str(server['players']) + '/' + str(server['max']\n ) + '] '\n entry += server['name'] + '\\r\\n'\n asciilist += entry\n server_count += 1\n except TypeError:\n continue\n self.msg(asciilist)\n self.end()\n", "step-5": "import time\n\nfrom helpers.handler import port_handler\nfrom helpers.functions import fetch_all\n\n\nclass ascii_handler(port_handler):\n \"\"\"\n Serve ASCII server list\n \"\"\"\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n \"\"\"\n self.ls.log.info(\"Sending ascii server list to %s\" % self.ip)\n\n self.cleanup()\n servers = fetch_all(\n \"SELECT * FROM servers WHERE max > 0 ORDER BY prefer DESC, private ASC, (players = max) ASC, players DESC, created ASC\")\n\n asciilist = \"\"\n\n server_count = 0\n for server in servers:\n try:\n entry = server['ip'] + ':' + str(server['port']) + ' ' # ip:port\n entry += 'local ' if server['remote'] == 0 else 'mirror ' # 'local' or 'mirror'\n entry += 'public ' if server['private'] == 0 else 'private ' # 'public' or 'private'\n entry += server['mode'] + ' ' # game mode\n entry += server['version'][:6].ljust(6, ' ') + ' ' # version\n entry += str(int(time.time()) - int(server['created'])) + ' ' # uptime in seconds\n entry += '[' + str(server['players']) + '/' + str(server['max']) + '] ' # [players/max]\n entry += server['name'] + \"\\r\\n\" # server name\n asciilist += entry\n server_count += 1\n except TypeError:\n continue\n\n self.msg(asciilist)\n self.end()\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
from omt.gui.abstract_panel import AbstractPanel class SourcePanel(AbstractPanel): def __init__(self): super(SourcePanel, self).__init__() def packagePath(self): """ This file holds the link to the active panels. The structure is a dictionary, the key is the class name and the values is where the object is define. """ altenatives = { 'Agilent':'omt.gui.sourcepanel.alternatives.agilent', 'RodeSchwartz':'omt.gui.sourcepanel.alternatives.rodeschwartz', 'BeamScanner':'omt.gui.sourcepanel.alternatives.beam_scanner', 'PCG':'omt.gui.sourcepanel.alternatives.pcg', 'Anritsu':'omt.gui.sourcepanel.alternatives.anritsu', } return altenatives def get_name(self): return "Source" def get_configurations(self): return_dic = {} for source in self.pannels_instants: if source.is_active(): if source.do_sweep(): if 'sweep' in return_dic: raise Exception('Only one sweep') return_dic['sweep'] = source.get_source_config() else: try: return_dic['tone'].append(source.get_source_config()) except KeyError as e: return_dic['tone'] = [source.get_source_config(),] return return_dic def pass_sources(self): return self.pannels_instants
normal
{ "blob_id": "aa0a69e3286934fcfdf31bd713eca1e8dd90aeaa", "index": 6914, "step-1": "<mask token>\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n The structure is a dictionary, the key is the class name\n and the values is where the object is define.\n \"\"\"\n altenatives = {'Agilent':\n 'omt.gui.sourcepanel.alternatives.agilent', 'RodeSchwartz':\n 'omt.gui.sourcepanel.alternatives.rodeschwartz', 'BeamScanner':\n 'omt.gui.sourcepanel.alternatives.beam_scanner', 'PCG':\n 'omt.gui.sourcepanel.alternatives.pcg', 'Anritsu':\n 'omt.gui.sourcepanel.alternatives.anritsu'}\n return altenatives\n <mask token>\n <mask token>\n\n def pass_sources(self):\n return self.pannels_instants\n", "step-2": "<mask token>\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n The structure is a dictionary, the key is the class name\n and the values is where the object is define.\n \"\"\"\n altenatives = {'Agilent':\n 'omt.gui.sourcepanel.alternatives.agilent', 'RodeSchwartz':\n 'omt.gui.sourcepanel.alternatives.rodeschwartz', 'BeamScanner':\n 'omt.gui.sourcepanel.alternatives.beam_scanner', 'PCG':\n 'omt.gui.sourcepanel.alternatives.pcg', 'Anritsu':\n 'omt.gui.sourcepanel.alternatives.anritsu'}\n return altenatives\n <mask token>\n\n def get_configurations(self):\n return_dic = {}\n for source in self.pannels_instants:\n if source.is_active():\n if source.do_sweep():\n if 'sweep' in return_dic:\n raise Exception('Only one sweep')\n return_dic['sweep'] = source.get_source_config()\n else:\n try:\n return_dic['tone'].append(source.get_source_config())\n except KeyError as e:\n return_dic['tone'] = [source.get_source_config()]\n return return_dic\n\n def pass_sources(self):\n return self.pannels_instants\n", "step-3": "<mask token>\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n The structure is a dictionary, the key is the class name\n and the values is where the object is define.\n \"\"\"\n altenatives = {'Agilent':\n 'omt.gui.sourcepanel.alternatives.agilent', 'RodeSchwartz':\n 'omt.gui.sourcepanel.alternatives.rodeschwartz', 'BeamScanner':\n 'omt.gui.sourcepanel.alternatives.beam_scanner', 'PCG':\n 'omt.gui.sourcepanel.alternatives.pcg', 'Anritsu':\n 'omt.gui.sourcepanel.alternatives.anritsu'}\n return altenatives\n\n def get_name(self):\n return 'Source'\n\n def get_configurations(self):\n return_dic = {}\n for source in self.pannels_instants:\n if source.is_active():\n if source.do_sweep():\n if 'sweep' in return_dic:\n raise Exception('Only one sweep')\n return_dic['sweep'] = source.get_source_config()\n else:\n try:\n return_dic['tone'].append(source.get_source_config())\n except KeyError as e:\n return_dic['tone'] = [source.get_source_config()]\n return return_dic\n\n def pass_sources(self):\n return self.pannels_instants\n", "step-4": "from omt.gui.abstract_panel import AbstractPanel\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n The structure is a dictionary, the key is the class name\n and the values is where the object is define.\n \"\"\"\n altenatives = {'Agilent':\n 'omt.gui.sourcepanel.alternatives.agilent', 'RodeSchwartz':\n 'omt.gui.sourcepanel.alternatives.rodeschwartz', 'BeamScanner':\n 'omt.gui.sourcepanel.alternatives.beam_scanner', 'PCG':\n 'omt.gui.sourcepanel.alternatives.pcg', 'Anritsu':\n 'omt.gui.sourcepanel.alternatives.anritsu'}\n return altenatives\n\n def get_name(self):\n return 'Source'\n\n def get_configurations(self):\n return_dic = {}\n for source in self.pannels_instants:\n if source.is_active():\n if source.do_sweep():\n if 'sweep' in return_dic:\n raise Exception('Only one sweep')\n return_dic['sweep'] = source.get_source_config()\n else:\n try:\n return_dic['tone'].append(source.get_source_config())\n except KeyError as e:\n return_dic['tone'] = [source.get_source_config()]\n return return_dic\n\n def pass_sources(self):\n return self.pannels_instants\n", "step-5": "from omt.gui.abstract_panel import AbstractPanel\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n The structure is a dictionary, the key is the class name\n and the values is where the object is define.\n \"\"\"\n altenatives = {\n 'Agilent':'omt.gui.sourcepanel.alternatives.agilent',\n 'RodeSchwartz':'omt.gui.sourcepanel.alternatives.rodeschwartz',\n 'BeamScanner':'omt.gui.sourcepanel.alternatives.beam_scanner',\n 'PCG':'omt.gui.sourcepanel.alternatives.pcg',\n 'Anritsu':'omt.gui.sourcepanel.alternatives.anritsu',\n }\n\n return altenatives\n\n def get_name(self):\n return \"Source\"\n\n def get_configurations(self):\n return_dic = {}\n for source in self.pannels_instants:\n if source.is_active():\n if source.do_sweep():\n if 'sweep' in return_dic:\n raise Exception('Only one sweep')\n return_dic['sweep'] = source.get_source_config()\n else:\n try:\n return_dic['tone'].append(source.get_source_config())\n except KeyError as e:\n return_dic['tone'] = [source.get_source_config(),]\n\n return return_dic\n\n def pass_sources(self):\n return self.pannels_instants", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
#common method to delete data from a list fruits=['orange','apple','mango','grapes','banana','apple','litchi'] #l=[] #[l.append(i) for i in fruits if i not in l] #print(l) print(set(fruits)) print(fruits.count("orange")) #pop method in a list used to delete last mathod from a list #fruits.pop()#items from if we a passing arguments then its delete specified items #print(fruits) #fruits.pop(4) #print(fruits) #del fruits[4]# to delete operater items we use delete operater in a list #print(fruits) #print(enumerate(fruits)) #c=enumerate(fruits) #print(c) # remove method in list # when we dont know the position of the item inside the list #print(fruits.remove('banana')) #print(fruits) #fruits.remove('apple') #print(fruits) #print("the new {} is : ".format(l)) #print(l) #print(set(fruits))
normal
{ "blob_id": "158b39a64d725bdbfc78acc346ed8335613ae099", "index": 8367, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(set(fruits))\nprint(fruits.count('orange'))\n", "step-3": "fruits = ['orange', 'apple', 'mango', 'grapes', 'banana', 'apple', 'litchi']\nprint(set(fruits))\nprint(fruits.count('orange'))\n", "step-4": "#common method to delete data from a list\r\nfruits=['orange','apple','mango','grapes','banana','apple','litchi']\r\n#l=[]\r\n\r\n#[l.append(i) for i in fruits if i not in l]\r\n\r\n#print(l)\r\nprint(set(fruits))\r\n\r\nprint(fruits.count(\"orange\"))\r\n\r\n\r\n\r\n\r\n \r\n \r\n#pop method in a list used to delete last mathod from a list\r\n#fruits.pop()#items from if we a passing arguments then its delete specified items\r\n#print(fruits)\r\n#fruits.pop(4)\r\n#print(fruits)\r\n#del fruits[4]# to delete operater items we use delete operater in a list\r\n#print(fruits)\r\n#print(enumerate(fruits))\r\n#c=enumerate(fruits)\r\n#print(c)\r\n# remove method in list\r\n# when we dont know the position of the item inside the list\r\n#print(fruits.remove('banana'))\r\n#print(fruits)\r\n#fruits.remove('apple')\r\n#print(fruits)\r\n\r\n#print(\"the new {} is : \".format(l))\r\n#print(l)\r\n#print(set(fruits))\r\n\r\n\r\n\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.db import models from django.utils import timezone from accounts.models import AllUser from profiles.models import Profile ### MODEL HOLDING MEMBER TO CLIENT RELATIONSHIPS. ### class MemberClient(models.Model): created = models.DateTimeField(auto_now_add=timezone.now()) client = models.ForeignKey(AllUser, related_name='client', default=None, on_delete=models.CASCADE) member = models.ForeignKey(AllUser, related_name='member', default=None, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profile', default=None, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "{0}".format(self.client)
normal
{ "blob_id": "b419e26cbf5bbb746f897367ddaa829773a6860c", "index": 7742, "step-1": "<mask token>\n\n\nclass MemberClient(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass MemberClient(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return '{0}'.format(self.client)\n", "step-3": "<mask token>\n\n\nclass MemberClient(models.Model):\n created = models.DateTimeField(auto_now_add=timezone.now())\n client = models.ForeignKey(AllUser, related_name='client', default=None,\n on_delete=models.CASCADE)\n member = models.ForeignKey(AllUser, related_name='member', default=None,\n on_delete=models.CASCADE)\n profile = models.ForeignKey(Profile, related_name='profile', default=\n None, on_delete=models.CASCADE, blank=True, null=True)\n\n def __str__(self):\n return '{0}'.format(self.client)\n", "step-4": "from django.db import models\nfrom django.utils import timezone\nfrom accounts.models import AllUser\nfrom profiles.models import Profile\n\n\nclass MemberClient(models.Model):\n created = models.DateTimeField(auto_now_add=timezone.now())\n client = models.ForeignKey(AllUser, related_name='client', default=None,\n on_delete=models.CASCADE)\n member = models.ForeignKey(AllUser, related_name='member', default=None,\n on_delete=models.CASCADE)\n profile = models.ForeignKey(Profile, related_name='profile', default=\n None, on_delete=models.CASCADE, blank=True, null=True)\n\n def __str__(self):\n return '{0}'.format(self.client)\n", "step-5": "from django.db import models\nfrom django.utils import timezone\nfrom accounts.models import AllUser\nfrom profiles.models import Profile\n\n### MODEL HOLDING MEMBER TO CLIENT RELATIONSHIPS. ###\n\nclass MemberClient(models.Model):\n created = models.DateTimeField(auto_now_add=timezone.now())\n client = models.ForeignKey(AllUser, \n related_name='client', \n default=None, \n on_delete=models.CASCADE)\n member = models.ForeignKey(AllUser,\n related_name='member', \n default=None, \n on_delete=models.CASCADE)\n profile = models.ForeignKey(Profile,\n related_name='profile', \n default=None, \n on_delete=models.CASCADE,\n blank=True,\n null=True)\n \n def __str__(self):\n return \"{0}\".format(self.client)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from binary_search_tree.gen_unique_bst import gen_unique_bst # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. def max_depth(root): if not root: return 0 return max(max_depth(root.left), max_depth(root.right)) + 1 # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. def min_depth(root): if not root: return 0 left, right = min_depth(root.left), min_depth(root.right) return left + right + 1 if left == 0 or right == 0 else min(left, right) + 1 def main(): trees = gen_unique_bst(3) for root in trees: print max_depth(root), min_depth(root) if __name__ == '__main__': main()
normal
{ "blob_id": "3e54d2ddddf6f8186137e5801ca4ba40d1061987", "index": 2801, "step-1": "from binary_search_tree.gen_unique_bst import gen_unique_bst\n\n\n# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\ndef max_depth(root):\n if not root:\n return 0\n return max(max_depth(root.left), max_depth(root.right)) + 1\n\n\n# The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\ndef min_depth(root):\n if not root:\n return 0\n left, right = min_depth(root.left), min_depth(root.right)\n return left + right + 1 if left == 0 or right == 0 else min(left, right) + 1\n\n\ndef main():\n trees = gen_unique_bst(3)\n for root in trees:\n print max_depth(root), min_depth(root)\n\n\nif __name__ == '__main__':\n main()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
n=int(input()) k=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444] f=0 for i in k: if(n%i==0): f=1 print("YES") break; if(f==0): print("NO")
normal
{ "blob_id": "6161653fb789040d084e475e0ae25921e2e0676b", "index": 2496, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in k:\n if n % i == 0:\n f = 1\n print('YES')\n break\nif f == 0:\n print('NO')\n", "step-3": "n = int(input())\nk = [4, 7, 47, 74, 44, 77, 444, 447, 474, 477, 777, 774, 747, 7444]\nf = 0\nfor i in k:\n if n % i == 0:\n f = 1\n print('YES')\n break\nif f == 0:\n print('NO')\n", "step-4": "n=int(input())\nk=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444]\nf=0\nfor i in k:\n if(n%i==0):\n f=1\n print(\"YES\")\n break;\nif(f==0):\n print(\"NO\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ created by gjwei on 3/26/17 """ class ListNode(object): def __init__(self, x): self.val = x self.next = None a = ListNode(1) a.next = ListNode(3) a.next = None print a.val print a.next def main(): print "hello" a = [] for i in range(20): a.append(i) return a
normal
{ "blob_id": "4a0cbd59ffae4fb5ba6e3bd871231e37065d1aed", "index": 3464, "step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\" \n created by gjwei on 3/26/17\n \n\"\"\"\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\na = ListNode(1)\na.next = ListNode(3)\n\na.next = None\nprint a.val\nprint a.next\n\n\ndef main():\n print \"hello\"\n a = []\n for i in range(20):\n a.append(i)\n\n return a\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'wenchao.hao' """ data.guid package. """ from .guid import Guid
normal
{ "blob_id": "88a379747f955b0410ab2bb33c1165034c701673", "index": 8597, "step-1": "<mask token>\n", "step-2": "__author__ = 'wenchao.hao'\n<mask token>\n", "step-3": "__author__ = 'wenchao.hao'\n<mask token>\nfrom .guid import Guid\n", "step-4": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'wenchao.hao'\n\n\"\"\"\ndata.guid package.\n\"\"\"\n\nfrom .guid import Guid\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#-*- coding: utf8 -*- #credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py import shutil, time, logging import torch import torch.optim import numpy as np import visdom, copy from datetime import datetime from collections import defaultdict from generic_models.yellowfin import YFOptimizer logger = logging.getLogger('app') logger.setLevel(logging.DEBUG) class VisdomMonitor(object): def __init__(self, prefix=None, server='http://localhost', port=8097): self.__prefix = prefix or datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') self.__vis = visdom.Visdom(server=server, port=port) self.__metrics = defaultdict(lambda :defaultdict(list)) self.__win_dict = {} self.__opts = self._init_opts() def _init_opts(self): opts = dict(legend=['Train', 'Validate']) return opts def __add(self, name, value, type): self.__metrics[type][name].append(value) def _add_val_performance(self, name, value): self.__add(name, value, type='val') def _add_train_performance(self, name, value): self.__add(name, value, type='train') def add_performance(self, metric_name, train_value, val_value): self._add_train_performance(metric_name, train_value ) self._add_val_performance(metric_name, val_value) self.plot(metric_name) def plot(self, metric_name): current_win = self.__win_dict.get(metric_name, None) train_values = self.__metrics['train'][metric_name] val_values = self.__metrics['val'][metric_name] epochs = max(len(train_values), len(val_values)) values_for_plot = np.column_stack((np.array(train_values), np.array(val_values))) opts = copy.deepcopy(self.__opts) opts.update(dict(title='%s\ntrain/val %s' % (self.__prefix, metric_name))) win = self.__vis.line(Y=values_for_plot, X=np.arange(epochs), opts=opts, win=current_win) if current_win is None: self.__win_dict[metric_name] = win class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate_by_schedule(config, optimizer, epoch, decrease_rate=0.1): """Sets the learning rate to the initial LR decayed by 1/decrease_rate every 10 epochs""" if not isinstance(optimizer, torch.optim.SGD): return #lr = config.lr * (0.1 ** (epoch // 10)) if epoch and epoch % 10 == 0: for i, param_group in enumerate(optimizer.param_groups): param_group['lr'] *= decrease_rate logger.info('Setting learning layer=i, rate=%.6f', i, param_group['lr']) class PlateauScheduler(object): """Sets the lr to the initial LR decayed by 1/decrease_rate, when not improving for max_stops epochs""" def __init__(self, optimizer, patience, early_stop_n, decrease_rate=0.1, eps=1e-5, warm_up_epochs=None, best_score=None): self.optimizer = optimizer if not isinstance(optimizer, (torch.optim.SGD, YFOptimizer)): raise TypeError self.patience = patience self.early_stop_n = early_stop_n self.decrease_rate = decrease_rate self.eps = eps self.warm_up_epochs = warm_up_epochs self.__lr_changed = 0 self.__early_stop_counter = 0 self.__best_score = best_score self.__descrease_times = 0 self.__warm_up = self.__has_warm_up(optimizer) def __has_warm_up(self, optimizer): for param_group in self.optimizer.param_groups: if param_group['lr'] != param_group['after_warmup_lr']: logger.info('Optimizer has warm-up stage') return True def step(self, epoch, score): adjusted, to_break = False, False prev_best_score = self.__best_score or -1 is_best = self.__best_score is None or score < self.__best_score - self.eps self.__best_score = self.__best_score is not None and min(score, self.__best_score) or score if is_best: logger.info('Current model is best by val score %.5f < %.5f' % (self.__best_score, prev_best_score)) self.__early_stop_counter = 0 else: self.__early_stop_counter += 1 if self.__early_stop_counter >= self.early_stop_n: logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter) to_break = True logger.info('early_stop_counter: %d', self.__early_stop_counter) if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \ (self.__lr_changed <= epoch - self.patience and \ (self.__early_stop_counter is not None and self.patience and self.__early_stop_counter >= self.patience)): self.__lr_changed = epoch for param_group in self.optimizer.param_groups: if self.__descrease_times == 0 and self.__warm_up: param_group['lr'] = param_group['after_warmup_lr'] else: param_group['lr'] = param_group['lr'] * self.decrease_rate logger.info('Setting for group learning rate=%.8f, epoch=%d', param_group['lr'], self.__lr_changed) adjusted = True self.__descrease_times += 1 return adjusted, to_break, is_best def init_optimizer(model, config, exact_layers=None): """param 'exact_layers' specifies which parameters of the model to train, None - all, else - list of layers with a multiplier (optional) for LR schedule""" opt_type = config.optimizer if exact_layers: logger.info('Learning exact layers, number=%d', len(exact_layers)) parameters = [] for i, layer in enumerate(exact_layers): if isinstance(layer, tuple) and len(layer) == 2: layer, multiplier = layer init_multiplier = 1 elif isinstance(layer, tuple) and len(layer) == 3: layer, init_multiplier, multiplier = layer else: multiplier = 1 init_multiplier = 1 lr = config.lr * multiplier init_lr = config.lr * multiplier * init_multiplier logger.info('Layer=%d, lr=%.5f', i, init_lr) parameters.append({'params': layer.parameters(), 'lr': init_lr, 'after_warmup_lr': lr}) else: logger.info('Optimizing all parameters, lr=%.5f', config.lr) parameters = model.parameters() if opt_type == 'sgd': optimizer = torch.optim.SGD(parameters, config.lr, momentum=config.momentum, weight_decay=config.weight_decay) elif opt_type == 'adam': optimizer = torch.optim.Adam(parameters, lr=config.lr, weight_decay=config.weight_decay) elif opt_type == 'yf': optimizer = YFOptimizer(parameters, config.lr, mu=config.momentum, weight_decay=config.weight_decay, clip_thresh=0.1) else: raise TypeError, 'Unknown optimizer type=%s' % (opt_type, ) return optimizer def save_checkpoint(state, epoch, is_best, filename, best_filename): torch.save(state, filename) if is_best: shutil.copyfile(filename, best_filename) shutil.copyfile(filename, best_filename + '-%d' % epoch) def load_checkpoint(filename): checkpoint = torch.load(filename) return checkpoint def train(train_loader, model, criterion, optimizer, epoch, is_multi_fc=False): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() predictions = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) target = target.cuda(async=True) input_var = torch.autograd.Variable(input) target_var = torch.autograd.Variable(target) # compute output if is_multi_fc==False: # this is original loss function output = model(input_var) loss = criterion(output, target_var) else: # this is for inception_v3 with 2 output channels # https://github.com/pytorch/vision/issues/302 output, output_aux = model(input_var) loss = criterion(output, target_var) loss+= criterion(output_aux, target_var) # measure accuracy and record loss losses.update(loss.data[0], input.size(0)) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if (i and i % 50 == 0) or i == len(train_loader) - 1: logger.info('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Accuracy {acc.val:.4f} ({acc.avg:.4f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format( epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, acc=predictions)) return losses.avg def compute_f2(output, target): true_and_pred = target * output ttp_sum = torch.sum(true_and_pred, 1) tpred_sum = torch.sum(output, 1) ttrue_sum = torch.sum(target, 1) tprecision = ttp_sum / tpred_sum trecall = ttp_sum / ttrue_sum f2 = ((1 + 4) * tprecision * trecall) / (4 * tprecision + trecall) return f2 def validate(val_loader, model, criterion, activation=torch.sigmoid): logger.info('Validating model') batch_time = AverageMeter() losses = AverageMeter() f2s = AverageMeter() # switch to evaluate mode model.eval() end = time.time() for i, (input, target) in enumerate(val_loader): target = target.cuda(async=True) input_var = torch.autograd.Variable(input, volatile=True) target_var = torch.autograd.Variable(target, volatile=True) # compute output output = model(input_var) loss = criterion(output, target_var) # compute f2 f2 = compute_f2(activation(output), target_var).mean() f2s.update(f2.data[0], input.size(0)) # measure accuracy and record loss losses.update(loss.data[0], input.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() logger.info('Test: [{0}/{0}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.5f}\t' 'F2: {f2s.avg}\t'.format( len(val_loader), batch_time=batch_time, loss=losses, f2s=f2s)) return losses.avg def get_outputs(loader, model, activation): model.eval() outputs, targets = [], [] for i, (input, target) in enumerate(loader): input_var = torch.autograd.Variable(input, volatile=True) output = model(input_var) if activation is not None: output = activation(output) outputs.extend(output.cpu().data) targets.extend(target) return outputs, targets def test_model(test_loader, model, activation=None): logger.info('Testing') model.eval() names, results = [], [] for i, (input, name_batch) in enumerate(test_loader): input_var = torch.autograd.Variable(input, volatile=True) output = model(input_var) if activation is not None: output = activation(output) names.extend(name_batch) results.extend(output.cpu()) if i and i % 20 == 0: logger.info('Batch %d',i) return names, results
normal
{ "blob_id": "be90dcb4bbb69053e9451479990e030cd4841e4a", "index": 1620, "step-1": "#-*- coding: utf8 -*-\n#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport shutil, time, logging\nimport torch\nimport torch.optim\nimport numpy as np\nimport visdom, copy\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom generic_models.yellowfin import YFOptimizer\n\n\nlogger = logging.getLogger('app')\nlogger.setLevel(logging.DEBUG)\n\n\nclass VisdomMonitor(object):\n def __init__(self, prefix=None, server='http://localhost', port=8097):\n self.__prefix = prefix or datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n self.__vis = visdom.Visdom(server=server, port=port)\n self.__metrics = defaultdict(lambda :defaultdict(list))\n self.__win_dict = {}\n self.__opts = self._init_opts()\n\n def _init_opts(self):\n opts = dict(legend=['Train', 'Validate'])\n return opts\n\n def __add(self, name, value, type):\n self.__metrics[type][name].append(value)\n\n def _add_val_performance(self, name, value):\n self.__add(name, value, type='val')\n\n def _add_train_performance(self, name, value):\n self.__add(name, value, type='train')\n\n def add_performance(self, metric_name, train_value, val_value):\n self._add_train_performance(metric_name, train_value )\n self._add_val_performance(metric_name, val_value)\n self.plot(metric_name)\n\n def plot(self, metric_name):\n current_win = self.__win_dict.get(metric_name, None)\n train_values = self.__metrics['train'][metric_name]\n val_values = self.__metrics['val'][metric_name]\n epochs = max(len(train_values), len(val_values))\n values_for_plot = np.column_stack((np.array(train_values), np.array(val_values)))\n opts = copy.deepcopy(self.__opts)\n opts.update(dict(title='%s\\ntrain/val %s' % (self.__prefix, metric_name)))\n win = self.__vis.line(Y=values_for_plot, X=np.arange(epochs), opts=opts, win=current_win)\n\n if current_win is None:\n self.__win_dict[metric_name] = win\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate_by_schedule(config, optimizer, epoch, decrease_rate=0.1):\n \"\"\"Sets the learning rate to the initial LR decayed by 1/decrease_rate every 10 epochs\"\"\"\n if not isinstance(optimizer, torch.optim.SGD):\n return\n #lr = config.lr * (0.1 ** (epoch // 10))\n if epoch and epoch % 10 == 0:\n for i, param_group in enumerate(optimizer.param_groups):\n param_group['lr'] *= decrease_rate\n logger.info('Setting learning layer=i, rate=%.6f', i, param_group['lr'])\n\n\nclass PlateauScheduler(object):\n \"\"\"Sets the lr to the initial LR decayed by 1/decrease_rate, when not improving for max_stops epochs\"\"\"\n def __init__(self, optimizer, patience, early_stop_n, decrease_rate=0.1, eps=1e-5,\n warm_up_epochs=None, best_score=None):\n self.optimizer = optimizer\n if not isinstance(optimizer, (torch.optim.SGD, YFOptimizer)):\n raise TypeError\n self.patience = patience\n self.early_stop_n = early_stop_n\n self.decrease_rate = decrease_rate\n self.eps = eps\n self.warm_up_epochs = warm_up_epochs\n self.__lr_changed = 0\n self.__early_stop_counter = 0\n self.__best_score = best_score\n self.__descrease_times = 0\n self.__warm_up = self.__has_warm_up(optimizer)\n\n def __has_warm_up(self, optimizer):\n for param_group in self.optimizer.param_groups:\n if param_group['lr'] != param_group['after_warmup_lr']:\n logger.info('Optimizer has warm-up stage')\n return True\n\n def step(self, epoch, score):\n adjusted, to_break = False, False\n\n prev_best_score = self.__best_score or -1\n is_best = self.__best_score is None or score < self.__best_score - self.eps\n self.__best_score = self.__best_score is not None and min(score, self.__best_score) or score\n if is_best:\n logger.info('Current model is best by val score %.5f < %.5f' % (self.__best_score, prev_best_score))\n self.__early_stop_counter = 0\n else:\n self.__early_stop_counter += 1\n if self.__early_stop_counter >= self.early_stop_n:\n logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter)\n to_break = True\n logger.info('early_stop_counter: %d', self.__early_stop_counter)\n\n if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \\\n (self.__lr_changed <= epoch - self.patience and \\\n (self.__early_stop_counter is not None and self.patience and self.__early_stop_counter >= self.patience)):\n self.__lr_changed = epoch\n for param_group in self.optimizer.param_groups:\n if self.__descrease_times == 0 and self.__warm_up:\n param_group['lr'] = param_group['after_warmup_lr']\n else:\n param_group['lr'] = param_group['lr'] * self.decrease_rate\n logger.info('Setting for group learning rate=%.8f, epoch=%d', param_group['lr'], self.__lr_changed)\n adjusted = True\n self.__descrease_times += 1\n\n return adjusted, to_break, is_best\n\n\ndef init_optimizer(model, config, exact_layers=None):\n \"\"\"param 'exact_layers' specifies which parameters of the model to train, None - all,\n else - list of layers with a multiplier (optional) for LR schedule\"\"\"\n opt_type = config.optimizer\n if exact_layers:\n logger.info('Learning exact layers, number=%d', len(exact_layers))\n parameters = []\n for i, layer in enumerate(exact_layers):\n if isinstance(layer, tuple) and len(layer) == 2:\n layer, multiplier = layer\n init_multiplier = 1\n elif isinstance(layer, tuple) and len(layer) == 3:\n layer, init_multiplier, multiplier = layer\n else:\n multiplier = 1\n init_multiplier = 1\n lr = config.lr * multiplier\n init_lr = config.lr * multiplier * init_multiplier\n logger.info('Layer=%d, lr=%.5f', i, init_lr)\n parameters.append({'params': layer.parameters(), 'lr': init_lr, 'after_warmup_lr': lr})\n else:\n logger.info('Optimizing all parameters, lr=%.5f', config.lr)\n parameters = model.parameters()\n\n if opt_type == 'sgd':\n optimizer = torch.optim.SGD(parameters, config.lr, momentum=config.momentum, weight_decay=config.weight_decay)\n elif opt_type == 'adam':\n optimizer = torch.optim.Adam(parameters, lr=config.lr, weight_decay=config.weight_decay)\n elif opt_type == 'yf':\n optimizer = YFOptimizer(parameters, config.lr, mu=config.momentum, weight_decay=config.weight_decay,\n clip_thresh=0.1)\n else:\n raise TypeError, 'Unknown optimizer type=%s' % (opt_type, )\n return optimizer\n\n\ndef save_checkpoint(state, epoch, is_best, filename, best_filename):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, best_filename)\n shutil.copyfile(filename, best_filename + '-%d' % epoch)\n\n\ndef load_checkpoint(filename):\n checkpoint = torch.load(filename)\n return checkpoint\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, is_multi_fc=False):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n predictions = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n target = target.cuda(async=True)\n input_var = torch.autograd.Variable(input)\n target_var = torch.autograd.Variable(target)\n # compute output\n if is_multi_fc==False:\n # this is original loss function\n output = model(input_var)\n loss = criterion(output, target_var)\n else:\n # this is for inception_v3 with 2 output channels\n # https://github.com/pytorch/vision/issues/302\n output, output_aux = model(input_var)\n loss = criterion(output, target_var)\n loss+= criterion(output_aux, target_var)\n \n # measure accuracy and record loss\n losses.update(loss.data[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if (i and i % 50 == 0) or i == len(train_loader) - 1:\n logger.info('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Accuracy {acc.val:.4f} ({acc.avg:.4f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses, acc=predictions))\n\n return losses.avg\n\n\ndef compute_f2(output, target):\n true_and_pred = target * output\n\n ttp_sum = torch.sum(true_and_pred, 1)\n tpred_sum = torch.sum(output, 1)\n ttrue_sum = torch.sum(target, 1)\n\n tprecision = ttp_sum / tpred_sum\n trecall = ttp_sum / ttrue_sum\n f2 = ((1 + 4) * tprecision * trecall) / (4 * tprecision + trecall)\n\n return f2\n\n\ndef validate(val_loader, model, criterion, activation=torch.sigmoid):\n logger.info('Validating model')\n batch_time = AverageMeter()\n losses = AverageMeter()\n f2s = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n target = target.cuda(async=True)\n input_var = torch.autograd.Variable(input, volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n\n # compute output\n output = model(input_var)\n\n loss = criterion(output, target_var)\n\n # compute f2\n f2 = compute_f2(activation(output), target_var).mean()\n f2s.update(f2.data[0], input.size(0))\n\n # measure accuracy and record loss\n losses.update(loss.data[0], input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n logger.info('Test: [{0}/{0}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.avg:.5f}\\t'\n 'F2: {f2s.avg}\\t'.format(\n len(val_loader), batch_time=batch_time, loss=losses, f2s=f2s))\n\n return losses.avg\n\n\ndef get_outputs(loader, model, activation):\n model.eval()\n outputs, targets = [], []\n for i, (input, target) in enumerate(loader):\n input_var = torch.autograd.Variable(input, volatile=True)\n output = model(input_var)\n if activation is not None:\n output = activation(output)\n outputs.extend(output.cpu().data)\n targets.extend(target)\n return outputs, targets\n\n\ndef test_model(test_loader, model, activation=None):\n logger.info('Testing')\n model.eval()\n\n names, results = [], []\n for i, (input, name_batch) in enumerate(test_loader):\n input_var = torch.autograd.Variable(input, volatile=True)\n\n output = model(input_var)\n if activation is not None:\n output = activation(output)\n\n names.extend(name_batch)\n results.extend(output.cpu())\n if i and i % 20 == 0:\n logger.info('Batch %d',i)\n\n return names, results\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import re def make_slug(string): print(re.sub(^'\w','',string)) make_slug('#$gejcb#$evnk?.kjb')
normal
{ "blob_id": "41e981e2192b600cdf9c9b515fe9f397cd1b8826", "index": 5788, "step-1": "import re\n\ndef make_slug(string):\n print(re.sub(^'\\w','',string))\n \nmake_slug('#$gejcb#$evnk?.kjb')\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from typing import Dict, Any from urllib import request from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Product from cart.forms import CartAddProductForm from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from .forms import UserForm, UserLogInForm from django.views import generic from django.views.generic import View def product_list(request): products = Product.objects.filter(available=True) context = {'products': products, 'user': request.user} return render(request, 'shop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() context = {'product': product, 'cart_product_form': cart_product_form} return render(request, 'shop/product/detail.html', context) class UserFormView(View): form_class = UserForm template_name = 'shop/signup.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) #print(request.user.is_authenticated()) return redirect('/shop/') return render(request, self.template_name, {'form': form}) def user_login(request): context = { 'form': UserLogInForm } if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) return redirect('/shop/') else: context['error'] = "Provide valid credentials" return render(request, 'shop/login.html', context) else: return render(request, 'shop/login.html', context) def user_logout(request): if request.method == 'POST': logout(request) return render(request, "shop/login.html")
normal
{ "blob_id": "1d72a9882aea1e0f808969828ed2e69ecd79ac71", "index": 7522, "step-1": "<mask token>\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/shop/')\n return render(request, self.template_name, {'form': form})\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n context = {'product': product, 'cart_product_form': cart_product_form}\n return render(request, 'shop/product/detail.html', context)\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/shop/')\n return render(request, self.template_name, {'form': form})\n\n\n<mask token>\n\n\ndef user_logout(request):\n if request.method == 'POST':\n logout(request)\n return render(request, 'shop/login.html')\n", "step-3": "<mask token>\n\n\ndef product_list(request):\n products = Product.objects.filter(available=True)\n context = {'products': products, 'user': request.user}\n return render(request, 'shop/product/list.html', context)\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n context = {'product': product, 'cart_product_form': cart_product_form}\n return render(request, 'shop/product/detail.html', context)\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/shop/')\n return render(request, self.template_name, {'form': form})\n\n\ndef user_login(request):\n context = {'form': UserLogInForm}\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user:\n login(request, user)\n return redirect('/shop/')\n else:\n context['error'] = 'Provide valid credentials'\n return render(request, 'shop/login.html', context)\n else:\n return render(request, 'shop/login.html', context)\n\n\ndef user_logout(request):\n if request.method == 'POST':\n logout(request)\n return render(request, 'shop/login.html')\n", "step-4": "from typing import Dict, Any\nfrom urllib import request\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\nfrom .models import Product\nfrom cart.forms import CartAddProductForm\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom .forms import UserForm, UserLogInForm\nfrom django.views import generic\nfrom django.views.generic import View\n\n\ndef product_list(request):\n products = Product.objects.filter(available=True)\n context = {'products': products, 'user': request.user}\n return render(request, 'shop/product/list.html', context)\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n context = {'product': product, 'cart_product_form': cart_product_form}\n return render(request, 'shop/product/detail.html', context)\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/shop/')\n return render(request, self.template_name, {'form': form})\n\n\ndef user_login(request):\n context = {'form': UserLogInForm}\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user:\n login(request, user)\n return redirect('/shop/')\n else:\n context['error'] = 'Provide valid credentials'\n return render(request, 'shop/login.html', context)\n else:\n return render(request, 'shop/login.html', context)\n\n\ndef user_logout(request):\n if request.method == 'POST':\n logout(request)\n return render(request, 'shop/login.html')\n", "step-5": "from typing import Dict, Any\nfrom urllib import request\n\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\n\nfrom .models import Product\nfrom cart.forms import CartAddProductForm\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom .forms import UserForm, UserLogInForm\nfrom django.views import generic\nfrom django.views.generic import View\n\n\ndef product_list(request):\n products = Product.objects.filter(available=True)\n\n context = {'products': products,\n 'user': request.user}\n return render(request, 'shop/product/list.html', context)\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n context = {'product': product,\n 'cart_product_form': cart_product_form}\n return render(request, 'shop/product/detail.html', context)\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n # display blank form\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name, {'form': form})\n\n # process form data\n def post(self, request):\n form = self.form_class(request.POST)\n\n if form.is_valid():\n\n user = form.save(commit=False)\n\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n\n user = authenticate(username=username, password=password)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n #print(request.user.is_authenticated())\n return redirect('/shop/')\n\n return render(request, self.template_name, {'form': form})\n\n\ndef user_login(request):\n context = {\n 'form': UserLogInForm\n }\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user:\n login(request, user)\n return redirect('/shop/')\n else:\n context['error'] = \"Provide valid credentials\"\n return render(request, 'shop/login.html', context)\n else:\n return render(request, 'shop/login.html', context)\n\n\ndef user_logout(request):\n if request.method == 'POST':\n logout(request)\n\n return render(request, \"shop/login.html\")\n\n\n\n\n\n\n", "step-ids": [ 4, 6, 8, 9, 10 ] }
[ 4, 6, 8, 9, 10 ]
from datetime import date from django.test import TestCase from model_mommy import mommy from apps.debtors.models import Debtor from apps.invoices.models import Invoice, InvoiceStatusChoices from apps.invoices.services import InvoiceService class InvoiceServiceTestCase(TestCase): def setUp(self) ->None: self.invoice_service = InvoiceService() self.debtor_1 = mommy.make(Debtor) self.invoice_1 = mommy.make(Invoice, debtor=self.debtor_1) def test_create_invoice(self): invoice = self.invoice_service.create_invoice(amount=12.1, status= InvoiceStatusChoices.OVERDUE, due_date=date(2019, 4, 1), debtor =self.debtor_1) self.assertEqual(invoice.amount, 12.1) self.assertEqual(invoice.status, InvoiceStatusChoices.OVERDUE) self.assertEqual(invoice.due_date, date(2019, 4, 1)) self.assertEqual(invoice.debtor, self.debtor_1) def test_update_invoice(self): updated_invoice = self.invoice_service.update_invoice(instance=self .invoice_1, status=InvoiceStatusChoices.PAID, random_attr='foo') self.assertEqual(updated_invoice.status, InvoiceStatusChoices.PAID) self.assertFalse(hasattr(updated_invoice, 'random_attr')) def test_delete_invoice(self): self.invoice_service.delete_invoice(instance=self.invoice_1) self.assertFalse(Invoice.objects.all().exists())
normal
{ "blob_id": "5f77e93d63c696363c30f019019acd22c694308b", "index": 4529, "step-1": "<mask token>\n\n\nclass InvoiceServiceTestCase(TestCase):\n <mask token>\n\n def test_create_invoice(self):\n invoice = self.invoice_service.create_invoice(amount=12.1, status=\n InvoiceStatusChoices.OVERDUE, due_date=date(2019, 4, 1), debtor\n =self.debtor_1)\n self.assertEqual(invoice.amount, 12.1)\n self.assertEqual(invoice.status, InvoiceStatusChoices.OVERDUE)\n self.assertEqual(invoice.due_date, date(2019, 4, 1))\n self.assertEqual(invoice.debtor, self.debtor_1)\n\n def test_update_invoice(self):\n updated_invoice = self.invoice_service.update_invoice(instance=self\n .invoice_1, status=InvoiceStatusChoices.PAID, random_attr='foo')\n self.assertEqual(updated_invoice.status, InvoiceStatusChoices.PAID)\n self.assertFalse(hasattr(updated_invoice, 'random_attr'))\n <mask token>\n", "step-2": "<mask token>\n\n\nclass InvoiceServiceTestCase(TestCase):\n\n def setUp(self) ->None:\n self.invoice_service = InvoiceService()\n self.debtor_1 = mommy.make(Debtor)\n self.invoice_1 = mommy.make(Invoice, debtor=self.debtor_1)\n\n def test_create_invoice(self):\n invoice = self.invoice_service.create_invoice(amount=12.1, status=\n InvoiceStatusChoices.OVERDUE, due_date=date(2019, 4, 1), debtor\n =self.debtor_1)\n self.assertEqual(invoice.amount, 12.1)\n self.assertEqual(invoice.status, InvoiceStatusChoices.OVERDUE)\n self.assertEqual(invoice.due_date, date(2019, 4, 1))\n self.assertEqual(invoice.debtor, self.debtor_1)\n\n def test_update_invoice(self):\n updated_invoice = self.invoice_service.update_invoice(instance=self\n .invoice_1, status=InvoiceStatusChoices.PAID, random_attr='foo')\n self.assertEqual(updated_invoice.status, InvoiceStatusChoices.PAID)\n self.assertFalse(hasattr(updated_invoice, 'random_attr'))\n <mask token>\n", "step-3": "<mask token>\n\n\nclass InvoiceServiceTestCase(TestCase):\n\n def setUp(self) ->None:\n self.invoice_service = InvoiceService()\n self.debtor_1 = mommy.make(Debtor)\n self.invoice_1 = mommy.make(Invoice, debtor=self.debtor_1)\n\n def test_create_invoice(self):\n invoice = self.invoice_service.create_invoice(amount=12.1, status=\n InvoiceStatusChoices.OVERDUE, due_date=date(2019, 4, 1), debtor\n =self.debtor_1)\n self.assertEqual(invoice.amount, 12.1)\n self.assertEqual(invoice.status, InvoiceStatusChoices.OVERDUE)\n self.assertEqual(invoice.due_date, date(2019, 4, 1))\n self.assertEqual(invoice.debtor, self.debtor_1)\n\n def test_update_invoice(self):\n updated_invoice = self.invoice_service.update_invoice(instance=self\n .invoice_1, status=InvoiceStatusChoices.PAID, random_attr='foo')\n self.assertEqual(updated_invoice.status, InvoiceStatusChoices.PAID)\n self.assertFalse(hasattr(updated_invoice, 'random_attr'))\n\n def test_delete_invoice(self):\n self.invoice_service.delete_invoice(instance=self.invoice_1)\n self.assertFalse(Invoice.objects.all().exists())\n", "step-4": "from datetime import date\nfrom django.test import TestCase\nfrom model_mommy import mommy\nfrom apps.debtors.models import Debtor\nfrom apps.invoices.models import Invoice, InvoiceStatusChoices\nfrom apps.invoices.services import InvoiceService\n\n\nclass InvoiceServiceTestCase(TestCase):\n\n def setUp(self) ->None:\n self.invoice_service = InvoiceService()\n self.debtor_1 = mommy.make(Debtor)\n self.invoice_1 = mommy.make(Invoice, debtor=self.debtor_1)\n\n def test_create_invoice(self):\n invoice = self.invoice_service.create_invoice(amount=12.1, status=\n InvoiceStatusChoices.OVERDUE, due_date=date(2019, 4, 1), debtor\n =self.debtor_1)\n self.assertEqual(invoice.amount, 12.1)\n self.assertEqual(invoice.status, InvoiceStatusChoices.OVERDUE)\n self.assertEqual(invoice.due_date, date(2019, 4, 1))\n self.assertEqual(invoice.debtor, self.debtor_1)\n\n def test_update_invoice(self):\n updated_invoice = self.invoice_service.update_invoice(instance=self\n .invoice_1, status=InvoiceStatusChoices.PAID, random_attr='foo')\n self.assertEqual(updated_invoice.status, InvoiceStatusChoices.PAID)\n self.assertFalse(hasattr(updated_invoice, 'random_attr'))\n\n def test_delete_invoice(self):\n self.invoice_service.delete_invoice(instance=self.invoice_1)\n self.assertFalse(Invoice.objects.all().exists())\n", "step-5": null, "step-ids": [ 3, 4, 5, 6 ] }
[ 3, 4, 5, 6 ]
import numpy as np import random import argparse import networkx as nx from gensim.models import Word2Vec from utils import read_node_label, plot_embeddings class node2vec_walk(): def __init__(self, nx_G, is_directed, p, q): self.G = nx_G self.is_directed = is_directed self.p = p self.q = q def node2vec_walk(self, walk_length, start_node): G = self.G alias_nodes = self.alias_nodes alias_edges = self.alias_edges walk = [start_node] while len(walk) < walk_length: curr = walk[-1] cur_nbrs = sorted(G.neighbors(curr)) if len(cur_nbrs) > 0: if len(walk) == 1: walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0], alias_nodes[curr][1])]) else: prev = walk[-2] next = cur_nbrs[alias_draw(alias_edges[(prev, curr)][0], alias_edges[(prev, curr)][1])] walk.append(next) else: break return walk def simulate_walks(self, num_walks, walk_length): G = self.G walks = [] nodes = list(G.nodes()) print("Walk iteration...") for walk_iter in range(num_walks): print(f"{walk_iter + 1}/{num_walks}") random.shuffle(nodes) for node in nodes: walks.append(self.node2vec_walk(walk_length, node)) return walks def get_alias_edge(self, src, dst): G = self.G p = self.p q = self.q unnormalized_probs = [] for dst_nbr in sorted(G.neighbors(dst)): if dst_nbr == src: unnormalized_probs.append(G[dst][dst_nbr]["weight"] / p) elif G.has_edge(dst_nbr, src): unnormalized_probs.append(G[dst][dst_nbr]["weight"]) else: unnormalized_probs.append(G[dst][dst_nbr]["weight"] / q) norm_cost = sum(unnormalized_probs) normalized_probs = [float(v) / norm_cost for v in unnormalized_probs] return alias_setup(normalized_probs) def preprocess_transition_probs(self): # 预处理转移概率 G = self.G is_directed = self.is_directed alias_nodes = {} for node in G.nodes(): unnormalized_probs = [G[node][nbr]["weight"] for nbr in sorted(G.neighbors(node))] norm_const = sum(unnormalized_probs) normalized_probs = [float(v) / norm_const for v in unnormalized_probs] alias_nodes[node] = alias_setup(normalized_probs) alias_edges = {} if is_directed: for edge in G.edges(): alias_edges[edge] = self.get_alias_edge(edge[0], edge[1]) else: for edge in G.edges(): alias_edges[edge] = self.get_alias_edge(edge[0], edge[1]) alias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0]) self.alias_nodes = alias_nodes self.alias_edges = alias_edges def alias_setup(probs): K = len(probs) q = np.zeros(K) J = np.zeros(K, dtype=np.int) smaller = [] larger = [] for kk, prob in enumerate(probs): q[kk] = K * prob # 记录小于均匀分布概率的Index if q[kk] > 1.0: larger.append(kk) else: smaller.append(kk) while len(smaller) > 0 and len(larger) > 0: small = smaller.pop() large = larger.pop() # 记录index J[small] = large # 将small的补充满1后,算出剩余large的概率 q[large] = q[small] + q[large] - 1 # 若q[large]不等于1,则继续放入smaller和larger的数组中进行迭代 if q[large] < 1.0: smaller.append(large) else: larger.append(large) return J, q def alias_draw(J, q): # 非均匀分布进行采样 K = len(J) kk = int(np.floor(np.random.rand() * K)) if np.random.rand() < q[kk]: return kk else: return J[kk] def parse_args(): parser = argparse.ArgumentParser(description="Run node2vec.") parser.add_argument('--input', nargs='?', default='./data/Wiki_edgelist.txt', help='Input graph path') parser.add_argument('--output', nargs='?', default='emb/node2vec_wiki.emb', help='Embeddings path') parser.add_argument('--label_file', nargs='?', default='data/wiki_labels.txt', help='Labels path') parser.add_argument('--dimensions', type=int, default=128, help='Number of dimensions. Default is 128.') parser.add_argument('--walk-length', type=int, default=80, help='Length of walk per source. Default is 80.') parser.add_argument('--num-walks', type=int, default=20, help='Number of walks per source. Default is 10.') parser.add_argument('--window-size', type=int, default=10, help='Context size for optimization. Default is 10.') parser.add_argument('--iter', default=2, type=int, help='Number of epochs in SGD') parser.add_argument('--workers', type=int, default=8, help='Number of parallel workers. Default is 8.') parser.add_argument('--p', type=float, default=1, help='Return hyperparameter. Default is 1.') parser.add_argument('--q', type=float, default=1, help='Inout hyperparameter. Default is 1.') parser.add_argument('--weighted', dest='weighted', action='store_true', help='Boolean specifying (un)weighted. Default is unweighted.') parser.add_argument('--unweighted', dest='unweighted', action='store_false') parser.set_defaults(weighted=False) parser.add_argument('--directed', dest='directed', action='store_true', help='Graph is (un)directed. Default is undirected.') parser.add_argument('--undirected', dest='undirected', action='store_false') parser.set_defaults(directed=False) return parser.parse_args() def read_graph(): if args.weighted: G = nx.read_edgelist(args.input, nodetype=int, data=(('weight', float), ), create_using=nx.DiGraph) else: G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph()) for edge in G.edges(): G[edge[0]][edge[1]]['weight'] = 1 if not args.directed: G = G.to_undirected() return G def learning_walks(walks): walks = [list(map(str, walk)) for walk in walks] model = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers, iter=args.iter) model.wv.save_word2vec_format(args.output) return model def main(args): nx_G = read_graph() G = node2vec_walk(nx_G, args.directed, args.p, args.q) G.preprocess_transition_probs() walks = G.simulate_walks(args.num_walks, args.walk_length) model = learning_walks(walks) _embeddings = {} for v in nx_G.nodes(): _embeddings[str(v)] = model.wv[str(v)] plot_embeddings(_embeddings, args.label_file) if __name__ == "__main__": args = parse_args() main(args)
normal
{ "blob_id": "fc2748d766ebce8c9577f1eebc8435e2aa58ae25", "index": 8605, "step-1": "<mask token>\n\n\nclass node2vec_walk:\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n walk = [start_node]\n while len(walk) < walk_length:\n curr = walk[-1]\n cur_nbrs = sorted(G.neighbors(curr))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0],\n alias_nodes[curr][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[prev, curr][0],\n alias_edges[prev, curr][1])]\n walk.append(next)\n else:\n break\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n G = self.G\n walks = []\n nodes = list(G.nodes())\n print('Walk iteration...')\n for walk_iter in range(num_walks):\n print(f'{walk_iter + 1}/{num_walks}')\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length, node))\n return walks\n\n def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr]['weight'])\n else:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / q)\n norm_cost = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_cost) for v in unnormalized_probs]\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n G = self.G\n is_directed = self.is_directed\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(\n G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_const) for v in\n unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n alias_edges = {}\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[edge[1], edge[0]] = self.get_alias_edge(edge[1],\n edge[0])\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n\n<mask token>\n\n\ndef read_graph():\n if args.weighted:\n G = nx.read_edgelist(args.input, nodetype=int, data=(('weight',\n float),), create_using=nx.DiGraph)\n else:\n G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.\n DiGraph())\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n if not args.directed:\n G = G.to_undirected()\n return G\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass node2vec_walk:\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n walk = [start_node]\n while len(walk) < walk_length:\n curr = walk[-1]\n cur_nbrs = sorted(G.neighbors(curr))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0],\n alias_nodes[curr][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[prev, curr][0],\n alias_edges[prev, curr][1])]\n walk.append(next)\n else:\n break\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n G = self.G\n walks = []\n nodes = list(G.nodes())\n print('Walk iteration...')\n for walk_iter in range(num_walks):\n print(f'{walk_iter + 1}/{num_walks}')\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length, node))\n return walks\n\n def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr]['weight'])\n else:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / q)\n norm_cost = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_cost) for v in unnormalized_probs]\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n G = self.G\n is_directed = self.is_directed\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(\n G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_const) for v in\n unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n alias_edges = {}\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[edge[1], edge[0]] = self.get_alias_edge(edge[1],\n edge[0])\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n\n<mask token>\n\n\ndef read_graph():\n if args.weighted:\n G = nx.read_edgelist(args.input, nodetype=int, data=(('weight',\n float),), create_using=nx.DiGraph)\n else:\n G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.\n DiGraph())\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n if not args.directed:\n G = G.to_undirected()\n return G\n\n\n<mask token>\n\n\ndef main(args):\n nx_G = read_graph()\n G = node2vec_walk(nx_G, args.directed, args.p, args.q)\n G.preprocess_transition_probs()\n walks = G.simulate_walks(args.num_walks, args.walk_length)\n model = learning_walks(walks)\n _embeddings = {}\n for v in nx_G.nodes():\n _embeddings[str(v)] = model.wv[str(v)]\n plot_embeddings(_embeddings, args.label_file)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass node2vec_walk:\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n walk = [start_node]\n while len(walk) < walk_length:\n curr = walk[-1]\n cur_nbrs = sorted(G.neighbors(curr))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0],\n alias_nodes[curr][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[prev, curr][0],\n alias_edges[prev, curr][1])]\n walk.append(next)\n else:\n break\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n G = self.G\n walks = []\n nodes = list(G.nodes())\n print('Walk iteration...')\n for walk_iter in range(num_walks):\n print(f'{walk_iter + 1}/{num_walks}')\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length, node))\n return walks\n\n def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr]['weight'])\n else:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / q)\n norm_cost = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_cost) for v in unnormalized_probs]\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n G = self.G\n is_directed = self.is_directed\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(\n G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_const) for v in\n unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n alias_edges = {}\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[edge[1], edge[0]] = self.get_alias_edge(edge[1],\n edge[0])\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n\ndef alias_setup(probs):\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K * prob\n if q[kk] > 1.0:\n larger.append(kk)\n else:\n smaller.append(kk)\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n J[small] = large\n q[large] = q[small] + q[large] - 1\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n return J, q\n\n\ndef alias_draw(J, q):\n K = len(J)\n kk = int(np.floor(np.random.rand() * K))\n if np.random.rand() < q[kk]:\n return kk\n else:\n return J[kk]\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Run node2vec.')\n parser.add_argument('--input', nargs='?', default=\n './data/Wiki_edgelist.txt', help='Input graph path')\n parser.add_argument('--output', nargs='?', default=\n 'emb/node2vec_wiki.emb', help='Embeddings path')\n parser.add_argument('--label_file', nargs='?', default=\n 'data/wiki_labels.txt', help='Labels path')\n parser.add_argument('--dimensions', type=int, default=128, help=\n 'Number of dimensions. Default is 128.')\n parser.add_argument('--walk-length', type=int, default=80, help=\n 'Length of walk per source. Default is 80.')\n parser.add_argument('--num-walks', type=int, default=20, help=\n 'Number of walks per source. Default is 10.')\n parser.add_argument('--window-size', type=int, default=10, help=\n 'Context size for optimization. Default is 10.')\n parser.add_argument('--iter', default=2, type=int, help=\n 'Number of epochs in SGD')\n parser.add_argument('--workers', type=int, default=8, help=\n 'Number of parallel workers. Default is 8.')\n parser.add_argument('--p', type=float, default=1, help=\n 'Return hyperparameter. Default is 1.')\n parser.add_argument('--q', type=float, default=1, help=\n 'Inout hyperparameter. Default is 1.')\n parser.add_argument('--weighted', dest='weighted', action='store_true',\n help='Boolean specifying (un)weighted. Default is unweighted.')\n parser.add_argument('--unweighted', dest='unweighted', action='store_false'\n )\n parser.set_defaults(weighted=False)\n parser.add_argument('--directed', dest='directed', action='store_true',\n help='Graph is (un)directed. Default is undirected.')\n parser.add_argument('--undirected', dest='undirected', action='store_false'\n )\n parser.set_defaults(directed=False)\n return parser.parse_args()\n\n\ndef read_graph():\n if args.weighted:\n G = nx.read_edgelist(args.input, nodetype=int, data=(('weight',\n float),), create_using=nx.DiGraph)\n else:\n G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.\n DiGraph())\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n if not args.directed:\n G = G.to_undirected()\n return G\n\n\ndef learning_walks(walks):\n walks = [list(map(str, walk)) for walk in walks]\n model = Word2Vec(walks, size=args.dimensions, window=args.window_size,\n min_count=0, sg=1, workers=args.workers, iter=args.iter)\n model.wv.save_word2vec_format(args.output)\n return model\n\n\ndef main(args):\n nx_G = read_graph()\n G = node2vec_walk(nx_G, args.directed, args.p, args.q)\n G.preprocess_transition_probs()\n walks = G.simulate_walks(args.num_walks, args.walk_length)\n model = learning_walks(walks)\n _embeddings = {}\n for v in nx_G.nodes():\n _embeddings[str(v)] = model.wv[str(v)]\n plot_embeddings(_embeddings, args.label_file)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass node2vec_walk:\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n walk = [start_node]\n while len(walk) < walk_length:\n curr = walk[-1]\n cur_nbrs = sorted(G.neighbors(curr))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0],\n alias_nodes[curr][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[prev, curr][0],\n alias_edges[prev, curr][1])]\n walk.append(next)\n else:\n break\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n G = self.G\n walks = []\n nodes = list(G.nodes())\n print('Walk iteration...')\n for walk_iter in range(num_walks):\n print(f'{walk_iter + 1}/{num_walks}')\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length, node))\n return walks\n\n def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr]['weight'])\n else:\n unnormalized_probs.append(G[dst][dst_nbr]['weight'] / q)\n norm_cost = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_cost) for v in unnormalized_probs]\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n G = self.G\n is_directed = self.is_directed\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(\n G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [(float(v) / norm_const) for v in\n unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n alias_edges = {}\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[edge[1], edge[0]] = self.get_alias_edge(edge[1],\n edge[0])\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n\ndef alias_setup(probs):\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K * prob\n if q[kk] > 1.0:\n larger.append(kk)\n else:\n smaller.append(kk)\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n J[small] = large\n q[large] = q[small] + q[large] - 1\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n return J, q\n\n\ndef alias_draw(J, q):\n K = len(J)\n kk = int(np.floor(np.random.rand() * K))\n if np.random.rand() < q[kk]:\n return kk\n else:\n return J[kk]\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Run node2vec.')\n parser.add_argument('--input', nargs='?', default=\n './data/Wiki_edgelist.txt', help='Input graph path')\n parser.add_argument('--output', nargs='?', default=\n 'emb/node2vec_wiki.emb', help='Embeddings path')\n parser.add_argument('--label_file', nargs='?', default=\n 'data/wiki_labels.txt', help='Labels path')\n parser.add_argument('--dimensions', type=int, default=128, help=\n 'Number of dimensions. Default is 128.')\n parser.add_argument('--walk-length', type=int, default=80, help=\n 'Length of walk per source. Default is 80.')\n parser.add_argument('--num-walks', type=int, default=20, help=\n 'Number of walks per source. Default is 10.')\n parser.add_argument('--window-size', type=int, default=10, help=\n 'Context size for optimization. Default is 10.')\n parser.add_argument('--iter', default=2, type=int, help=\n 'Number of epochs in SGD')\n parser.add_argument('--workers', type=int, default=8, help=\n 'Number of parallel workers. Default is 8.')\n parser.add_argument('--p', type=float, default=1, help=\n 'Return hyperparameter. Default is 1.')\n parser.add_argument('--q', type=float, default=1, help=\n 'Inout hyperparameter. Default is 1.')\n parser.add_argument('--weighted', dest='weighted', action='store_true',\n help='Boolean specifying (un)weighted. Default is unweighted.')\n parser.add_argument('--unweighted', dest='unweighted', action='store_false'\n )\n parser.set_defaults(weighted=False)\n parser.add_argument('--directed', dest='directed', action='store_true',\n help='Graph is (un)directed. Default is undirected.')\n parser.add_argument('--undirected', dest='undirected', action='store_false'\n )\n parser.set_defaults(directed=False)\n return parser.parse_args()\n\n\ndef read_graph():\n if args.weighted:\n G = nx.read_edgelist(args.input, nodetype=int, data=(('weight',\n float),), create_using=nx.DiGraph)\n else:\n G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.\n DiGraph())\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n if not args.directed:\n G = G.to_undirected()\n return G\n\n\ndef learning_walks(walks):\n walks = [list(map(str, walk)) for walk in walks]\n model = Word2Vec(walks, size=args.dimensions, window=args.window_size,\n min_count=0, sg=1, workers=args.workers, iter=args.iter)\n model.wv.save_word2vec_format(args.output)\n return model\n\n\ndef main(args):\n nx_G = read_graph()\n G = node2vec_walk(nx_G, args.directed, args.p, args.q)\n G.preprocess_transition_probs()\n walks = G.simulate_walks(args.num_walks, args.walk_length)\n model = learning_walks(walks)\n _embeddings = {}\n for v in nx_G.nodes():\n _embeddings[str(v)] = model.wv[str(v)]\n plot_embeddings(_embeddings, args.label_file)\n\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n", "step-5": "\n\nimport numpy as np\nimport random\n\nimport argparse\nimport networkx as nx\nfrom gensim.models import Word2Vec\n\nfrom utils import read_node_label, plot_embeddings\n\nclass node2vec_walk():\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n\n walk = [start_node]\n\n while len(walk) < walk_length:\n curr = walk[-1]\n cur_nbrs = sorted(G.neighbors(curr))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[curr][0], alias_nodes[curr][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[(prev, curr)][0], alias_edges[(prev, curr)][1])]\n walk.append(next)\n else:\n break\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n G = self.G\n walks = []\n nodes = list(G.nodes())\n\n print(\"Walk iteration...\")\n\n for walk_iter in range(num_walks):\n print(f\"{walk_iter + 1}/{num_walks}\")\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length, node))\n return walks\n\n def get_alias_edge(self, src, dst):\n G = self.G\n p = self.p\n q = self.q\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr][\"weight\"] / p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr][\"weight\"])\n else:\n unnormalized_probs.append(G[dst][dst_nbr][\"weight\"] / q)\n norm_cost = sum(unnormalized_probs)\n normalized_probs = [float(v) / norm_cost for v in unnormalized_probs]\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n # 预处理转移概率\n G = self.G\n is_directed = self.is_directed\n\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr][\"weight\"] for nbr in sorted(G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [float(v) / norm_const for v in unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n\n alias_edges = {}\n\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0])\n\n\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n\n\ndef alias_setup(probs):\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K * prob\n # 记录小于均匀分布概率的Index\n if q[kk] > 1.0:\n larger.append(kk)\n else:\n smaller.append(kk)\n\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n\n # 记录index\n J[small] = large\n # 将small的补充满1后,算出剩余large的概率\n q[large] = q[small] + q[large] - 1\n # 若q[large]不等于1,则继续放入smaller和larger的数组中进行迭代\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n\n return J, q\n\ndef alias_draw(J, q):\n # 非均匀分布进行采样\n K = len(J)\n\n kk = int(np.floor(np.random.rand() * K))\n if np.random.rand() < q[kk]:\n return kk\n else:\n return J[kk]\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Run node2vec.\")\n parser.add_argument('--input', nargs='?', default='./data/Wiki_edgelist.txt', help='Input graph path')\n parser.add_argument('--output', nargs='?', default='emb/node2vec_wiki.emb', help='Embeddings path')\n parser.add_argument('--label_file', nargs='?', default='data/wiki_labels.txt', help='Labels path')\n parser.add_argument('--dimensions', type=int, default=128, help='Number of dimensions. Default is 128.')\n parser.add_argument('--walk-length', type=int, default=80, help='Length of walk per source. Default is 80.')\n parser.add_argument('--num-walks', type=int, default=20, help='Number of walks per source. Default is 10.')\n parser.add_argument('--window-size', type=int, default=10, help='Context size for optimization. Default is 10.')\n parser.add_argument('--iter', default=2, type=int, help='Number of epochs in SGD')\n parser.add_argument('--workers', type=int, default=8, help='Number of parallel workers. Default is 8.')\n parser.add_argument('--p', type=float, default=1, help='Return hyperparameter. Default is 1.')\n parser.add_argument('--q', type=float, default=1, help='Inout hyperparameter. Default is 1.')\n parser.add_argument('--weighted', dest='weighted', action='store_true', help='Boolean specifying (un)weighted. Default is unweighted.')\n parser.add_argument('--unweighted', dest='unweighted', action='store_false')\n parser.set_defaults(weighted=False)\n parser.add_argument('--directed', dest='directed', action='store_true', help='Graph is (un)directed. Default is undirected.')\n parser.add_argument('--undirected', dest='undirected', action='store_false')\n parser.set_defaults(directed=False)\n return parser.parse_args()\n\ndef read_graph():\n if args.weighted:\n G = nx.read_edgelist(args.input, nodetype=int, data=(('weight', float), ), create_using=nx.DiGraph)\n else:\n G = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph())\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n\n if not args.directed:\n G = G.to_undirected()\n\n return G\n\ndef learning_walks(walks):\n walks = [list(map(str, walk)) for walk in walks]\n model = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers, iter=args.iter)\n model.wv.save_word2vec_format(args.output)\n return model\n\ndef main(args):\n nx_G = read_graph()\n G = node2vec_walk(nx_G, args.directed, args.p, args.q)\n G.preprocess_transition_probs()\n walks = G.simulate_walks(args.num_walks, args.walk_length)\n model = learning_walks(walks)\n\n _embeddings = {}\n for v in nx_G.nodes():\n _embeddings[str(v)] = model.wv[str(v)]\n\n plot_embeddings(_embeddings, args.label_file)\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n\n\n", "step-ids": [ 7, 8, 12, 13, 15 ] }
[ 7, 8, 12, 13, 15 ]
from models import Person from models import Skeleton from models import Base_dolni from models import Dolen_vrata st = Person("Stoian") Stoian = Person("Ivanov") dolni = Skeleton(st, 900, 600, 2, 18, 28, 40) dolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40) dol_001 = Base_dolni(dolni_st, 550) dol_001.set_description("dolen do mivkata") dol_001.rendModul() dol_002 = Dolen_vrata(dolni_st, 400, 2) dol_002.set_description("долен втори с 2 врати") dol_002.rendModul()
normal
{ "blob_id": "3d10f8810594303beb0ccabce3497de86149b2e5", "index": 6666, "step-1": "<mask token>\n", "step-2": "<mask token>\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\n<mask token>\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-3": "<mask token>\nst = Person('Stoian')\nStoian = Person('Ivanov')\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-4": "from models import Person\nfrom models import Skeleton\nfrom models import Base_dolni\nfrom models import Dolen_vrata\nst = Person('Stoian')\nStoian = Person('Ivanov')\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n", "step-5": "from models import Person\nfrom models import Skeleton\nfrom models import Base_dolni\nfrom models import Dolen_vrata\n\nst = Person(\"Stoian\")\nStoian = Person(\"Ivanov\")\n\ndolni = Skeleton(st, 900, 600, 2, 18, 28, 40)\ndolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)\n\ndol_001 = Base_dolni(dolni_st, 550)\ndol_001.set_description(\"dolen do mivkata\")\ndol_001.rendModul()\n\ndol_002 = Dolen_vrata(dolni_st, 400, 2)\ndol_002.set_description(\"долен втори с 2 врати\")\ndol_002.rendModul()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from nltk.tokenize import sent_tokenize from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer import networkx as nx def summarize(text): sentences_token = sent_tokenize(text) #Feature Extraction vectorizer = CountVectorizer(min_df=1,decode_error='replace') sent_bow = vectorizer.fit_transform(sentences_token) transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True) sent_tfidf = transformer.fit_transform(sent_bow) similarity_graph = sent_tfidf * sent_tfidf.T nx_graph = nx.from_scipy_sparse_matrix(similarity_graph) scores = nx.pagerank(nx_graph) text_rank_graph = sorted(((scores[i],s) for i,s in enumerate(sentences_token)), reverse=True) number_of_sents = int(0.4*len(text_rank_graph)) del text_rank_graph[number_of_sents:] summary = ' '.join(word for _,word in text_rank_graph) return summary
normal
{ "blob_id": "b75ebcd278ae92274bbbe8d1ce5cb3bb7fa14a2c", "index": 9637, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef summarize(text):\n sentences_token = sent_tokenize(text)\n vectorizer = CountVectorizer(min_df=1, decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n similarity_graph = sent_tfidf * sent_tfidf.T\n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i], s) for i, s in enumerate(\n sentences_token)), reverse=True)\n number_of_sents = int(0.4 * len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _, word in text_rank_graph)\n return summary\n", "step-3": "from nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nimport networkx as nx\n\n\ndef summarize(text):\n sentences_token = sent_tokenize(text)\n vectorizer = CountVectorizer(min_df=1, decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n similarity_graph = sent_tfidf * sent_tfidf.T\n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i], s) for i, s in enumerate(\n sentences_token)), reverse=True)\n number_of_sents = int(0.4 * len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _, word in text_rank_graph)\n return summary\n", "step-4": "from nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nimport networkx as nx\n\ndef summarize(text):\n \n sentences_token = sent_tokenize(text)\n \n #Feature Extraction\n vectorizer = CountVectorizer(min_df=1,decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_token)\n transformer = TfidfTransformer(norm='l2', smooth_idf=True, use_idf=True)\n sent_tfidf = transformer.fit_transform(sent_bow)\n \n similarity_graph = sent_tfidf * sent_tfidf.T\n \n nx_graph = nx.from_scipy_sparse_matrix(similarity_graph)\n scores = nx.pagerank(nx_graph)\n text_rank_graph = sorted(((scores[i],s) for i,s in enumerate(sentences_token)), reverse=True)\n number_of_sents = int(0.4*len(text_rank_graph))\n del text_rank_graph[number_of_sents:]\n summary = ' '.join(word for _,word in text_rank_graph)\n \n return summary\n \n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from pypc.a_primitives.nand import nand # nand gates used: 5 def half_adder(a: bool, b: bool) -> (bool, bool): """Returns a + b in the form of a tuple of two bools representing the two bits.""" nand_a_b = nand(a, b) nand_c = nand(nand_a_b, a) nand_d = nand(nand_a_b, b) high = nand(nand_a_b, nand_a_b) low = nand(nand_c, nand_d) return high, low # nand gates used: 9 def full_adder(a: bool, b: bool, c: bool) -> (bool, bool): """Returns a + b + c in the form of a tuple of two bools representing the two bits. Carried value is ignored. """ nand_a_b = nand(a, b) nand_c = nand(nand_a_b, a) nand_d = nand(nand_a_b, b) low_a_b = nand(nand_c, nand_d) nand_low_a_b_c = nand(low_a_b, c) nand_e = nand(low_a_b, nand_low_a_b_c) nand_f = nand(nand_low_a_b_c, c) high = nand(nand_a_b, nand_low_a_b_c) low = nand(nand_e, nand_f) return high, low
normal
{ "blob_id": "66f6639ae62fe8c0b42171cf3e3fb450d8eee2b2", "index": 7671, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef full_adder(a: bool, b: bool, c: bool) ->(bool, bool):\n \"\"\"Returns a + b + c in the form of a tuple of two bools representing the two\n bits.\n \n Carried value is ignored.\n \"\"\"\n nand_a_b = nand(a, b)\n nand_c = nand(nand_a_b, a)\n nand_d = nand(nand_a_b, b)\n low_a_b = nand(nand_c, nand_d)\n nand_low_a_b_c = nand(low_a_b, c)\n nand_e = nand(low_a_b, nand_low_a_b_c)\n nand_f = nand(nand_low_a_b_c, c)\n high = nand(nand_a_b, nand_low_a_b_c)\n low = nand(nand_e, nand_f)\n return high, low\n", "step-3": "<mask token>\n\n\ndef half_adder(a: bool, b: bool) ->(bool, bool):\n \"\"\"Returns a + b in the form of a tuple of two bools representing the two\n bits.\"\"\"\n nand_a_b = nand(a, b)\n nand_c = nand(nand_a_b, a)\n nand_d = nand(nand_a_b, b)\n high = nand(nand_a_b, nand_a_b)\n low = nand(nand_c, nand_d)\n return high, low\n\n\ndef full_adder(a: bool, b: bool, c: bool) ->(bool, bool):\n \"\"\"Returns a + b + c in the form of a tuple of two bools representing the two\n bits.\n \n Carried value is ignored.\n \"\"\"\n nand_a_b = nand(a, b)\n nand_c = nand(nand_a_b, a)\n nand_d = nand(nand_a_b, b)\n low_a_b = nand(nand_c, nand_d)\n nand_low_a_b_c = nand(low_a_b, c)\n nand_e = nand(low_a_b, nand_low_a_b_c)\n nand_f = nand(nand_low_a_b_c, c)\n high = nand(nand_a_b, nand_low_a_b_c)\n low = nand(nand_e, nand_f)\n return high, low\n", "step-4": "from pypc.a_primitives.nand import nand\n\n\ndef half_adder(a: bool, b: bool) ->(bool, bool):\n \"\"\"Returns a + b in the form of a tuple of two bools representing the two\n bits.\"\"\"\n nand_a_b = nand(a, b)\n nand_c = nand(nand_a_b, a)\n nand_d = nand(nand_a_b, b)\n high = nand(nand_a_b, nand_a_b)\n low = nand(nand_c, nand_d)\n return high, low\n\n\ndef full_adder(a: bool, b: bool, c: bool) ->(bool, bool):\n \"\"\"Returns a + b + c in the form of a tuple of two bools representing the two\n bits.\n \n Carried value is ignored.\n \"\"\"\n nand_a_b = nand(a, b)\n nand_c = nand(nand_a_b, a)\n nand_d = nand(nand_a_b, b)\n low_a_b = nand(nand_c, nand_d)\n nand_low_a_b_c = nand(low_a_b, c)\n nand_e = nand(low_a_b, nand_low_a_b_c)\n nand_f = nand(nand_low_a_b_c, c)\n high = nand(nand_a_b, nand_low_a_b_c)\n low = nand(nand_e, nand_f)\n return high, low\n", "step-5": "from pypc.a_primitives.nand import nand\r\n\r\n\r\n# nand gates used: 5\r\ndef half_adder(a: bool, b: bool) -> (bool, bool):\r\n \"\"\"Returns a + b in the form of a tuple of two bools representing the two\r\n bits.\"\"\"\r\n nand_a_b = nand(a, b)\r\n nand_c = nand(nand_a_b, a)\r\n nand_d = nand(nand_a_b, b)\r\n high = nand(nand_a_b, nand_a_b)\r\n low = nand(nand_c, nand_d)\r\n return high, low\r\n\r\n\r\n# nand gates used: 9\r\ndef full_adder(a: bool, b: bool, c: bool) -> (bool, bool):\r\n \"\"\"Returns a + b + c in the form of a tuple of two bools representing the two\r\n bits.\r\n \r\n Carried value is ignored.\r\n \"\"\"\r\n nand_a_b = nand(a, b)\r\n nand_c = nand(nand_a_b, a)\r\n nand_d = nand(nand_a_b, b)\r\n low_a_b = nand(nand_c, nand_d)\r\n nand_low_a_b_c = nand(low_a_b, c)\r\n nand_e = nand(low_a_b, nand_low_a_b_c)\r\n nand_f = nand(nand_low_a_b_c, c)\r\n high = nand(nand_a_b, nand_low_a_b_c)\r\n low = nand(nand_e, nand_f)\r\n return high, low\r\n\r\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" k-element subsets of the set [n] 3-element subsets of the set [6] 123 """ result = [] def get_subset(A, k, n): a_list = [i for i in A] if len(a_list) == k: result.append(a_list) return s_num = max(a_list)+1 if a_list else 1 for i in range(s_num, n+1): a_list.append(i) get_subset(a_list, k, n) a_list.remove(i) def subset_algor(n, k): V = [] get_subset(V, k, n) def main(): # subset_algor(int(input()), int(input())) subset_algor(7, 3) for i in range(len(result)): print(result[i], " Rank: ", i) print(len(result)) if __name__ == "__main__": main()
normal
{ "blob_id": "d48353caa07d3bfa003ea9354b411fe0c79591db", "index": 2725, "step-1": "<mask token>\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list) + 1 if a_list else 1\n for i in range(s_num, n + 1):\n a_list.append(i)\n get_subset(a_list, k, n)\n a_list.remove(i)\n\n\n<mask token>\n\n\ndef main():\n subset_algor(7, 3)\n for i in range(len(result)):\n print(result[i], ' Rank: ', i)\n print(len(result))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list) + 1 if a_list else 1\n for i in range(s_num, n + 1):\n a_list.append(i)\n get_subset(a_list, k, n)\n a_list.remove(i)\n\n\ndef subset_algor(n, k):\n V = []\n get_subset(V, k, n)\n\n\ndef main():\n subset_algor(7, 3)\n for i in range(len(result)):\n print(result[i], ' Rank: ', i)\n print(len(result))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list) + 1 if a_list else 1\n for i in range(s_num, n + 1):\n a_list.append(i)\n get_subset(a_list, k, n)\n a_list.remove(i)\n\n\ndef subset_algor(n, k):\n V = []\n get_subset(V, k, n)\n\n\ndef main():\n subset_algor(7, 3)\n for i in range(len(result)):\n print(result[i], ' Rank: ', i)\n print(len(result))\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nresult = []\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list) + 1 if a_list else 1\n for i in range(s_num, n + 1):\n a_list.append(i)\n get_subset(a_list, k, n)\n a_list.remove(i)\n\n\ndef subset_algor(n, k):\n V = []\n get_subset(V, k, n)\n\n\ndef main():\n subset_algor(7, 3)\n for i in range(len(result)):\n print(result[i], ' Rank: ', i)\n print(len(result))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "\"\"\"\nk-element subsets of the set [n]\n3-element subsets of the set [6]\n\n123\n\"\"\"\n\nresult = []\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list)+1 if a_list else 1\n for i in range(s_num, n+1):\n a_list.append(i)\n get_subset(a_list, k, n)\n a_list.remove(i)\n\n\ndef subset_algor(n, k):\n V = []\n get_subset(V, k, n)\n\n\ndef main():\n # subset_algor(int(input()), int(input()))\n subset_algor(7, 3)\n\n for i in range(len(result)):\n print(result[i], \" Rank: \", i)\n print(len(result))\n\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
def main(): x = float(input("Coordenada x: ")) y = float(input("Coordenada y: ")) if 1 <= y <= 2 and -3 <= x <= 3: print("dentro") elif (4 <= y <= 5 or 6 <= x <= 7) and ( -4 <= x <= -3 or -2 <= x <= -1 or 1 <= x <= 2 or 3 <= x <= 4): print("dentro") else: print("fora") #----------------------------------------------------- if __name__ == '__main__': # chamada da funcao principal main()
normal
{ "blob_id": "06cb832c3adae95fcd1d1d2d0663641d3ac671ef", "index": 9132, "step-1": "<mask token>\n", "step-2": "def main():\n x = float(input('Coordenada x: '))\n y = float(input('Coordenada y: '))\n if 1 <= y <= 2 and -3 <= x <= 3:\n print('dentro')\n elif (4 <= y <= 5 or 6 <= x <= 7) and (-4 <= x <= -3 or -2 <= x <= -1 or\n 1 <= x <= 2 or 3 <= x <= 4):\n print('dentro')\n else:\n print('fora')\n\n\n<mask token>\n", "step-3": "def main():\n x = float(input('Coordenada x: '))\n y = float(input('Coordenada y: '))\n if 1 <= y <= 2 and -3 <= x <= 3:\n print('dentro')\n elif (4 <= y <= 5 or 6 <= x <= 7) and (-4 <= x <= -3 or -2 <= x <= -1 or\n 1 <= x <= 2 or 3 <= x <= 4):\n print('dentro')\n else:\n print('fora')\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "def main():\r\n x = float(input(\"Coordenada x: \"))\r\n y = float(input(\"Coordenada y: \"))\r\n \r\n if 1 <= y <= 2 and -3 <= x <= 3:\r\n print(\"dentro\")\r\n \r\n elif (4 <= y <= 5 or 6 <= x <= 7) and ( -4 <= x <= -3 or -2 <= x <= -1 or 1 <= x <= 2 or 3 <= x <= 4):\r\n print(\"dentro\")\r\n \r\n else:\r\n print(\"fora\")\r\n\r\n\r\n\r\n#-----------------------------------------------------\r\nif __name__ == '__main__': # chamada da funcao principal\r\n main()\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import os import requests from PIL import Image from io import BytesIO import csv from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection # pull the image from the api endpoint and save it if we don't have it, else load it from disk def get_img_from_file_or_url(img_format: str = 'JPEG') -> Callable[[str, str], Image.Image]: def _apply(filepath: str, url: str) -> Image.Image: img = from_file(filepath) if img is None: img = from_url(url) img.save(filepath, img_format) return img.convert('RGB') # convert to rgb if not already (eg if grayscale) return _apply def from_url(url: str) -> Image.Image: api_response = requests.get(url).content response_bytes = BytesIO(api_response) return Image.open(response_bytes) def from_file(path: str) -> Union[Image.Image, None]: if os.path.exists(path): return Image.open(path) else: return None def load_metadata(path: str, cols: Iterable[int], class_cols: Collection[int] = tuple(), valid_only: bool = True, **reader_args)\ -> Tuple[List, int, List, List[Dict[str, int]], List[Dict[int, str]], int]: metadata = [] # one dict for each class col class_to_index: List[Dict[str, int]] = [{}] * len(class_cols) index_to_class: List[Dict[int, str]] = [{}] * len(class_cols) next_indices = [0] * len(class_cols) # next index for a new class value with open(path, 'r', newline='', encoding="utf8") as metadata_file: reader = csv.reader(metadata_file, **reader_args) headers = next(reader) for row in reader: if len(row) != 0: metadatum = [row[c] for c in cols] # for all class cols, add their vals to the class_to_index and index_to_class dicts if not there already for c, class_col in enumerate(class_cols): if not row[class_col] in class_to_index[c]: class_to_index[c][row[class_col]] = next_indices[c] index_to_class[c][next_indices[c]] = row[class_col] next_indices[c] += 1 if valid_only and '' in metadatum: continue metadata.append(metadatum) len_metadata = len(metadata) num_classes = 0 if len(next_indices) == 0 else next_indices[-1] # split off the headers return metadata, len_metadata, headers, class_to_index, index_to_class, num_classes
normal
{ "blob_id": "f2bb44600f011a205c71985ad94c18f7e058634f", "index": 8, "step-1": "<mask token>\n\n\ndef from_url(url: str) ->Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) ->Union[Image.Image, None]:\n if os.path.exists(path):\n return Image.open(path)\n else:\n return None\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],\n Image.Image]:\n\n def _apply(filepath: str, url: str) ->Image.Image:\n img = from_file(filepath)\n if img is None:\n img = from_url(url)\n img.save(filepath, img_format)\n return img.convert('RGB')\n return _apply\n\n\ndef from_url(url: str) ->Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) ->Union[Image.Image, None]:\n if os.path.exists(path):\n return Image.open(path)\n else:\n return None\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],\n Image.Image]:\n\n def _apply(filepath: str, url: str) ->Image.Image:\n img = from_file(filepath)\n if img is None:\n img = from_url(url)\n img.save(filepath, img_format)\n return img.convert('RGB')\n return _apply\n\n\ndef from_url(url: str) ->Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) ->Union[Image.Image, None]:\n if os.path.exists(path):\n return Image.open(path)\n else:\n return None\n\n\ndef load_metadata(path: str, cols: Iterable[int], class_cols: Collection[\n int]=tuple(), valid_only: bool=True, **reader_args) ->Tuple[List, int,\n List, List[Dict[str, int]], List[Dict[int, str]], int]:\n metadata = []\n class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)\n index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)\n next_indices = [0] * len(class_cols)\n with open(path, 'r', newline='', encoding='utf8') as metadata_file:\n reader = csv.reader(metadata_file, **reader_args)\n headers = next(reader)\n for row in reader:\n if len(row) != 0:\n metadatum = [row[c] for c in cols]\n for c, class_col in enumerate(class_cols):\n if not row[class_col] in class_to_index[c]:\n class_to_index[c][row[class_col]] = next_indices[c]\n index_to_class[c][next_indices[c]] = row[class_col]\n next_indices[c] += 1\n if valid_only and '' in metadatum:\n continue\n metadata.append(metadatum)\n len_metadata = len(metadata)\n num_classes = 0 if len(next_indices) == 0 else next_indices[-1]\n return (metadata, len_metadata, headers, class_to_index, index_to_class,\n num_classes)\n", "step-4": "import os\nimport requests\nfrom PIL import Image\nfrom io import BytesIO\nimport csv\nfrom typing import Iterable, List, Tuple, Dict, Callable, Union, Collection\n\n\ndef get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],\n Image.Image]:\n\n def _apply(filepath: str, url: str) ->Image.Image:\n img = from_file(filepath)\n if img is None:\n img = from_url(url)\n img.save(filepath, img_format)\n return img.convert('RGB')\n return _apply\n\n\ndef from_url(url: str) ->Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) ->Union[Image.Image, None]:\n if os.path.exists(path):\n return Image.open(path)\n else:\n return None\n\n\ndef load_metadata(path: str, cols: Iterable[int], class_cols: Collection[\n int]=tuple(), valid_only: bool=True, **reader_args) ->Tuple[List, int,\n List, List[Dict[str, int]], List[Dict[int, str]], int]:\n metadata = []\n class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)\n index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)\n next_indices = [0] * len(class_cols)\n with open(path, 'r', newline='', encoding='utf8') as metadata_file:\n reader = csv.reader(metadata_file, **reader_args)\n headers = next(reader)\n for row in reader:\n if len(row) != 0:\n metadatum = [row[c] for c in cols]\n for c, class_col in enumerate(class_cols):\n if not row[class_col] in class_to_index[c]:\n class_to_index[c][row[class_col]] = next_indices[c]\n index_to_class[c][next_indices[c]] = row[class_col]\n next_indices[c] += 1\n if valid_only and '' in metadatum:\n continue\n metadata.append(metadatum)\n len_metadata = len(metadata)\n num_classes = 0 if len(next_indices) == 0 else next_indices[-1]\n return (metadata, len_metadata, headers, class_to_index, index_to_class,\n num_classes)\n", "step-5": "import os\nimport requests\nfrom PIL import Image\nfrom io import BytesIO\nimport csv\nfrom typing import Iterable, List, Tuple, Dict, Callable, Union, Collection\n\n\n# pull the image from the api endpoint and save it if we don't have it, else load it from disk\ndef get_img_from_file_or_url(img_format: str = 'JPEG') -> Callable[[str, str], Image.Image]:\n def _apply(filepath: str, url: str) -> Image.Image:\n img = from_file(filepath)\n if img is None:\n img = from_url(url)\n img.save(filepath, img_format)\n return img.convert('RGB') # convert to rgb if not already (eg if grayscale)\n return _apply\n\n\ndef from_url(url: str) -> Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) -> Union[Image.Image, None]:\n if os.path.exists(path):\n return Image.open(path)\n else:\n return None\n\n\ndef load_metadata(path: str, cols: Iterable[int], class_cols: Collection[int] = tuple(), valid_only: bool = True, **reader_args)\\\n -> Tuple[List, int, List, List[Dict[str, int]], List[Dict[int, str]], int]:\n metadata = []\n # one dict for each class col\n class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)\n index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)\n next_indices = [0] * len(class_cols) # next index for a new class value\n with open(path, 'r', newline='', encoding=\"utf8\") as metadata_file:\n reader = csv.reader(metadata_file, **reader_args)\n headers = next(reader)\n for row in reader:\n if len(row) != 0:\n metadatum = [row[c] for c in cols]\n # for all class cols, add their vals to the class_to_index and index_to_class dicts if not there already\n for c, class_col in enumerate(class_cols):\n if not row[class_col] in class_to_index[c]:\n class_to_index[c][row[class_col]] = next_indices[c]\n index_to_class[c][next_indices[c]] = row[class_col]\n next_indices[c] += 1\n if valid_only and '' in metadatum:\n continue\n metadata.append(metadatum)\n len_metadata = len(metadata)\n num_classes = 0 if len(next_indices) == 0 else next_indices[-1]\n # split off the headers\n return metadata, len_metadata, headers, class_to_index, index_to_class, num_classes\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
import os import math from collections import defaultdict __author__ = 'steven' question='qb' fs={'t1','small.in','large'} def getmincost(n,c,f,x): t=0.0 for i in range(0,n): t+=1/(2+f*i) t=t*c t+=x/(2+f*n) ct=getmincostnshift(n,c,f,x) return min(t,ct); def getmincostnshift(n,c,f,x): t=0.0 n-=1; for i in range(0,n): t+=1/(2+f*i) t=t*c t+=x/(2+f*n) return t def getminn(c,f,x): return int(math.ceil((x*f-2*c)/(c*f))) def solver(c,f,x): if (x*f-2*c)<0: return x/2 minn=getminn(c,f,x) return getmincost(minn,c,f,x) for s in fs: print question+s f='./'+question+s if os.path.isfile('./'+question+s): ls=open(f) noq=(int)(ls.readline()) fout=open(question+s+'-a','w') print noq for i in range(0,noq): fa=ls.readline() fa=fa.split(); c, f, x=[float(s) for s in fa] fout.write('Case #%d: %f\n'%(i+1,solver(c,f,x))) #Case #1: 7 #Case #2: Bad magician! #Case #3: Volunteer cheated!
normal
{ "blob_id": "8fee548466abf6d35ea180f8de4e52a9b8902d3f", "index": 1025, "step-1": "import os\nimport math\nfrom collections import defaultdict\n__author__ = 'steven'\n\nquestion='qb'\nfs={'t1','small.in','large'}\ndef getmincost(n,c,f,x):\n t=0.0\n\n for i in range(0,n):\n t+=1/(2+f*i)\n t=t*c\n t+=x/(2+f*n)\n ct=getmincostnshift(n,c,f,x)\n return min(t,ct);\n\ndef getmincostnshift(n,c,f,x):\n t=0.0\n n-=1;\n\n for i in range(0,n):\n t+=1/(2+f*i)\n t=t*c\n t+=x/(2+f*n)\n return t\ndef getminn(c,f,x):\n return int(math.ceil((x*f-2*c)/(c*f)))\ndef solver(c,f,x):\n if (x*f-2*c)<0:\n return x/2\n minn=getminn(c,f,x)\n return getmincost(minn,c,f,x)\n\n\nfor s in fs:\n print question+s\n f='./'+question+s\n if os.path.isfile('./'+question+s):\n ls=open(f)\n noq=(int)(ls.readline())\n fout=open(question+s+'-a','w')\n print noq\n for i in range(0,noq):\n fa=ls.readline()\n fa=fa.split();\n c, f, x=[float(s) for s in fa]\n fout.write('Case #%d: %f\\n'%(i+1,solver(c,f,x)))\n\n#Case #1: 7\n#Case #2: Bad magician!\n#Case #3: Volunteer cheated!\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/python3 import sys import math class parameter : opt = 0 xp = 0 yp = 0 zp = 0 xv = 0 yv = 0 zv = 0 p = 0 def check_args() : try : int(sys.argv[1]) int(sys.argv[2]) int(sys.argv[3]) int(sys.argv[4]) int(sys.argv[5]) int(sys.argv[6]) int(sys.argv[7]) int(sys.argv[8]) except : sys.exit(84) if len(sys.argv) != 9 : sys.exit(84) if int(sys.argv[1]) != 1 and int(sys.argv[1]) != 2 and int(sys.argv[1]) != 3 : sys.exit(84) def help() : if len(sys.argv) == 2 and sys.argv[1] == '-h' : print ("USAGE") print (" ./104intersection opt xp yp zp xv yv zv p") print ("DESCRIPTION") print (" opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone") print (" (xp, yp, zp) coordinates of a point by which the light ray passes through") print (" (xv, yv, zv) coordinates of a vector parallel to the light ray") print (" p parameter: radius of the sphere, radius of the cylinder, or") print (" angle formed by the cone and the Z-axis") sys.exit(0) def sphere() : if parameter.p <= 0 : sys.exit(84) print("Sphere of radius "+str(parameter.p)) print("Line passing through the point ("+str(parameter.xp)+", "+str(parameter.yp)+", "+str(parameter.zp)+") and parallel to the vector ("+str(parameter.xv)+", "+str(parameter.yv)+", "+str(parameter.zv)+")") a = float(pow(parameter.xv, 2) + pow(parameter.yv, 2) + pow(parameter.zv, 2)) b = float(parameter.xv*2*parameter.xp + parameter.yv*2*parameter.yp + parameter.zv*2*parameter.zp) c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) + pow(parameter.zp, 2) - pow(parameter.p,2)) descriminant = float(pow(b, 2) - 4 * a * c) if descriminant < 0 : print("No intersection point.") if descriminant == 0 : t1 = float(- (b / (2 * a))) x = float(parameter.xp + parameter.xv * t1) y = float(parameter.yp + parameter.yv * t1) z = float(parameter.zp + parameter.zv * t1) print("1 intersection point:") print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z)) if descriminant > 0 : t1 = float((-b - math.sqrt(descriminant) ) / (2 * a)) t2 = float((-b + math.sqrt(descriminant) ) / (2 * a)) x1 = float(parameter.xp + parameter.xv * t1) y1 = float(parameter.yp + parameter.yv * t1) z1 = float(parameter.zp + parameter.zv * t1) x2 = float(parameter.xp + parameter.xv * t2) y2 = float(parameter.yp + parameter.yv * t2) z2 = float(parameter.zp + parameter.zv * t2) print("2 intersection points:") print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2)) print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1)) def cylinder() : infiny = 0 if parameter.p <= 0 : sys.exit(84) print("Cylinder of radius "+str(parameter.p)) print("Line passing through the point ("+str(parameter.xp)+", "+str(parameter.yp)+", "+str(parameter.zp)+") and parallel to the vector ("+str(parameter.xv)+", "+str(parameter.yv)+", "+str(parameter.zv)+")") a = float(parameter.xv + parameter.yv) b = float( 2 * (parameter.xv * parameter.xp + parameter.yv * parameter.yp)) c = float(pow(parameter.xp,2) + pow(parameter.yp, 2) - pow(parameter.p, 2)) descriminant = float(pow(b, 2) - 4 * a * c) if descriminant < 0 : print("No intersection point.") if descriminant == 0 : try: t1 = float(- (b / (2 * a))) except : t1 = 1 infiny = 1 x = float(parameter.xp + parameter.xv * t1) y = float(parameter.yp + parameter.yv * t1) z = float(parameter.zp + parameter.zv * t1) if infiny == 0 : print("1 intersection point:") print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z)) else: print("There is an infinite number of intersection points.") if descriminant > 0 : t1 = float((-b - math.sqrt(descriminant) ) / (2 * a)) t2 = float((-b + math.sqrt(descriminant) ) / (2 * a)) x1 = float(parameter.xp + parameter.xv * t1) y1 = float(parameter.yp + parameter.yv * t1) z1 = float(parameter.zp + parameter.zv * t1) x2 = float(parameter.xp + parameter.xv * t2) y2 = float(parameter.yp + parameter.yv * t2) z2 = float(parameter.zp + parameter.zv * t2) print("2 intersection points:") print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2)) print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1)) def cone() : if parameter.p <= 0 or parameter.p >= 90 : sys.exit(84) rad = math.radians(parameter.p) print("Cone with a"+str(parameter.p)+" degree angle") print("Line passing through the point ("+str(parameter.xp)+", "+str(parameter.yp)+", "+str(parameter.zp)+") and parallel to the vector ("+str(parameter.xv)+", "+str(parameter.yv)+", "+str(parameter.zv)+")") a = float(parameter.xv + parameter.yv - pow(parameter.zv, 2) * pow(math.tan(rad), 2)) b = float( 2 * (parameter.xv * parameter.xp + parameter.yv * parameter.yp - pow(math.tan(rad),2) * parameter.zp*parameter.zv)) c = float(pow(parameter.xp,2) + pow(parameter.yp, 2) - pow(math.tan(rad),2) * pow(parameter.zp, 2)) descriminant = float(pow(b, 2) - 4 * a * c) if descriminant < 0 : print("No intersection point.") if descriminant == 0 : try: t1 = float(- (b / (2 * a))) except : t1 = 1 infiny = 1 x = float(parameter.xp + parameter.xv * t1) y = float(parameter.yp + parameter.yv * t1) z = float(parameter.zp + parameter.zv * t1) if infiny == 0 : print("1 intersection point:") print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z)) else: print("There is an infinite number of intersection points.") if descriminant > 0 : t1 = float((-b - math.sqrt(descriminant) ) / (2 * a)) t2 = float((-b + math.sqrt(descriminant) ) / (2 * a)) x1 = float(parameter.xp + parameter.xv * t1) y1 = float(parameter.yp + parameter.yv * t1) z1 = float(parameter.zp + parameter.zv * t1) x2 = float(parameter.xp + parameter.xv * t2) y2 = float(parameter.yp + parameter.yv * t2) z2 = float(parameter.zp + parameter.zv * t2) print("2 intersection points:") print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2)) print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1)) def apply_args() : parameter.opt = int(sys.argv[1]) parameter.xp = int(sys.argv[2]) parameter.yp = int(sys.argv[3]) parameter.zp = int(sys.argv[4]) parameter.xv = int(sys.argv[5]) parameter.yv = int(sys.argv[6]) parameter.zv = int(sys.argv[7]) parameter.p = int(sys.argv[8]) def main(): help() check_args() apply_args() if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0 : sys.exit(84) if parameter.opt == 1 : sphere() if parameter.opt == 2 : cylinder() if parameter.opt == 3 : cone() if __name__ == "__main__" : main()
normal
{ "blob_id": "d1af148bc6b27d38052f2e57f1c610c86eccebef", "index": 7757, "step-1": "<mask token>\n\n\nclass parameter:\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\n\n<mask token>\n\n\ndef help():\n if len(sys.argv) == 2 and sys.argv[1] == '-h':\n print('USAGE')\n print(' ./104intersection opt xp yp zp xv yv zv p')\n print('DESCRIPTION')\n print(\n ' opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone'\n )\n print(\n ' (xp, yp, zp) coordinates of a point by which the light ray passes through'\n )\n print(\n ' (xv, yv, zv) coordinates of a vector parallel to the light ray'\n )\n print(\n ' p parameter: radius of the sphere, radius of the cylinder, or'\n )\n print(' angle formed by the cone and the Z-axis')\n sys.exit(0)\n\n\n<mask token>\n\n\ndef apply_args():\n parameter.opt = int(sys.argv[1])\n parameter.xp = int(sys.argv[2])\n parameter.yp = int(sys.argv[3])\n parameter.zp = int(sys.argv[4])\n parameter.xv = int(sys.argv[5])\n parameter.yv = int(sys.argv[6])\n parameter.zv = int(sys.argv[7])\n parameter.p = int(sys.argv[8])\n\n\ndef main():\n help()\n check_args()\n apply_args()\n if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0:\n sys.exit(84)\n if parameter.opt == 1:\n sphere()\n if parameter.opt == 2:\n cylinder()\n if parameter.opt == 3:\n cone()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass parameter:\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\n\ndef check_args():\n try:\n int(sys.argv[1])\n int(sys.argv[2])\n int(sys.argv[3])\n int(sys.argv[4])\n int(sys.argv[5])\n int(sys.argv[6])\n int(sys.argv[7])\n int(sys.argv[8])\n except:\n sys.exit(84)\n if len(sys.argv) != 9:\n sys.exit(84)\n if int(sys.argv[1]) != 1 and int(sys.argv[1]) != 2 and int(sys.argv[1]\n ) != 3:\n sys.exit(84)\n\n\ndef help():\n if len(sys.argv) == 2 and sys.argv[1] == '-h':\n print('USAGE')\n print(' ./104intersection opt xp yp zp xv yv zv p')\n print('DESCRIPTION')\n print(\n ' opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone'\n )\n print(\n ' (xp, yp, zp) coordinates of a point by which the light ray passes through'\n )\n print(\n ' (xv, yv, zv) coordinates of a vector parallel to the light ray'\n )\n print(\n ' p parameter: radius of the sphere, radius of the cylinder, or'\n )\n print(' angle formed by the cone and the Z-axis')\n sys.exit(0)\n\n\n<mask token>\n\n\ndef cone():\n if parameter.p <= 0 or parameter.p >= 90:\n sys.exit(84)\n rad = math.radians(parameter.p)\n print('Cone with a' + str(parameter.p) + ' degree angle')\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(parameter.xv + parameter.yv - pow(parameter.zv, 2) * pow(math\n .tan(rad), 2))\n b = float(2 * (parameter.xv * parameter.xp + parameter.yv * parameter.\n yp - pow(math.tan(rad), 2) * parameter.zp * parameter.zv))\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) - pow(math.tan(\n rad), 2) * pow(parameter.zp, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n try:\n t1 = float(-(b / (2 * a)))\n except:\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0:\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n else:\n print('There is an infinite number of intersection points.')\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\ndef apply_args():\n parameter.opt = int(sys.argv[1])\n parameter.xp = int(sys.argv[2])\n parameter.yp = int(sys.argv[3])\n parameter.zp = int(sys.argv[4])\n parameter.xv = int(sys.argv[5])\n parameter.yv = int(sys.argv[6])\n parameter.zv = int(sys.argv[7])\n parameter.p = int(sys.argv[8])\n\n\ndef main():\n help()\n check_args()\n apply_args()\n if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0:\n sys.exit(84)\n if parameter.opt == 1:\n sphere()\n if parameter.opt == 2:\n cylinder()\n if parameter.opt == 3:\n cone()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass parameter:\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\n\ndef check_args():\n try:\n int(sys.argv[1])\n int(sys.argv[2])\n int(sys.argv[3])\n int(sys.argv[4])\n int(sys.argv[5])\n int(sys.argv[6])\n int(sys.argv[7])\n int(sys.argv[8])\n except:\n sys.exit(84)\n if len(sys.argv) != 9:\n sys.exit(84)\n if int(sys.argv[1]) != 1 and int(sys.argv[1]) != 2 and int(sys.argv[1]\n ) != 3:\n sys.exit(84)\n\n\ndef help():\n if len(sys.argv) == 2 and sys.argv[1] == '-h':\n print('USAGE')\n print(' ./104intersection opt xp yp zp xv yv zv p')\n print('DESCRIPTION')\n print(\n ' opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone'\n )\n print(\n ' (xp, yp, zp) coordinates of a point by which the light ray passes through'\n )\n print(\n ' (xv, yv, zv) coordinates of a vector parallel to the light ray'\n )\n print(\n ' p parameter: radius of the sphere, radius of the cylinder, or'\n )\n print(' angle formed by the cone and the Z-axis')\n sys.exit(0)\n\n\ndef sphere():\n if parameter.p <= 0:\n sys.exit(84)\n print('Sphere of radius ' + str(parameter.p))\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(pow(parameter.xv, 2) + pow(parameter.yv, 2) + pow(parameter.\n zv, 2))\n b = float(parameter.xv * 2 * parameter.xp + parameter.yv * 2 *\n parameter.yp + parameter.zv * 2 * parameter.zp)\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) + pow(parameter.\n zp, 2) - pow(parameter.p, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n t1 = float(-(b / (2 * a)))\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\n<mask token>\n\n\ndef cone():\n if parameter.p <= 0 or parameter.p >= 90:\n sys.exit(84)\n rad = math.radians(parameter.p)\n print('Cone with a' + str(parameter.p) + ' degree angle')\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(parameter.xv + parameter.yv - pow(parameter.zv, 2) * pow(math\n .tan(rad), 2))\n b = float(2 * (parameter.xv * parameter.xp + parameter.yv * parameter.\n yp - pow(math.tan(rad), 2) * parameter.zp * parameter.zv))\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) - pow(math.tan(\n rad), 2) * pow(parameter.zp, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n try:\n t1 = float(-(b / (2 * a)))\n except:\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0:\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n else:\n print('There is an infinite number of intersection points.')\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\ndef apply_args():\n parameter.opt = int(sys.argv[1])\n parameter.xp = int(sys.argv[2])\n parameter.yp = int(sys.argv[3])\n parameter.zp = int(sys.argv[4])\n parameter.xv = int(sys.argv[5])\n parameter.yv = int(sys.argv[6])\n parameter.zv = int(sys.argv[7])\n parameter.p = int(sys.argv[8])\n\n\ndef main():\n help()\n check_args()\n apply_args()\n if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0:\n sys.exit(84)\n if parameter.opt == 1:\n sphere()\n if parameter.opt == 2:\n cylinder()\n if parameter.opt == 3:\n cone()\n\n\n<mask token>\n", "step-4": "import sys\nimport math\n\n\nclass parameter:\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\n\ndef check_args():\n try:\n int(sys.argv[1])\n int(sys.argv[2])\n int(sys.argv[3])\n int(sys.argv[4])\n int(sys.argv[5])\n int(sys.argv[6])\n int(sys.argv[7])\n int(sys.argv[8])\n except:\n sys.exit(84)\n if len(sys.argv) != 9:\n sys.exit(84)\n if int(sys.argv[1]) != 1 and int(sys.argv[1]) != 2 and int(sys.argv[1]\n ) != 3:\n sys.exit(84)\n\n\ndef help():\n if len(sys.argv) == 2 and sys.argv[1] == '-h':\n print('USAGE')\n print(' ./104intersection opt xp yp zp xv yv zv p')\n print('DESCRIPTION')\n print(\n ' opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone'\n )\n print(\n ' (xp, yp, zp) coordinates of a point by which the light ray passes through'\n )\n print(\n ' (xv, yv, zv) coordinates of a vector parallel to the light ray'\n )\n print(\n ' p parameter: radius of the sphere, radius of the cylinder, or'\n )\n print(' angle formed by the cone and the Z-axis')\n sys.exit(0)\n\n\ndef sphere():\n if parameter.p <= 0:\n sys.exit(84)\n print('Sphere of radius ' + str(parameter.p))\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(pow(parameter.xv, 2) + pow(parameter.yv, 2) + pow(parameter.\n zv, 2))\n b = float(parameter.xv * 2 * parameter.xp + parameter.yv * 2 *\n parameter.yp + parameter.zv * 2 * parameter.zp)\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) + pow(parameter.\n zp, 2) - pow(parameter.p, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n t1 = float(-(b / (2 * a)))\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\ndef cylinder():\n infiny = 0\n if parameter.p <= 0:\n sys.exit(84)\n print('Cylinder of radius ' + str(parameter.p))\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(parameter.xv + parameter.yv)\n b = float(2 * (parameter.xv * parameter.xp + parameter.yv * parameter.yp))\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) - pow(parameter.p, 2)\n )\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n try:\n t1 = float(-(b / (2 * a)))\n except:\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0:\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n else:\n print('There is an infinite number of intersection points.')\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\ndef cone():\n if parameter.p <= 0 or parameter.p >= 90:\n sys.exit(84)\n rad = math.radians(parameter.p)\n print('Cone with a' + str(parameter.p) + ' degree angle')\n print('Line passing through the point (' + str(parameter.xp) + ', ' +\n str(parameter.yp) + ', ' + str(parameter.zp) +\n ') and parallel to the vector (' + str(parameter.xv) + ', ' + str(\n parameter.yv) + ', ' + str(parameter.zv) + ')')\n a = float(parameter.xv + parameter.yv - pow(parameter.zv, 2) * pow(math\n .tan(rad), 2))\n b = float(2 * (parameter.xv * parameter.xp + parameter.yv * parameter.\n yp - pow(math.tan(rad), 2) * parameter.zp * parameter.zv))\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) - pow(math.tan(\n rad), 2) * pow(parameter.zp, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n if descriminant < 0:\n print('No intersection point.')\n if descriminant == 0:\n try:\n t1 = float(-(b / (2 * a)))\n except:\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0:\n print('1 intersection point:')\n print('(%.3f,' % float(x), '%.3f,' % float(y), '%.3f)' % float(z))\n else:\n print('There is an infinite number of intersection points.')\n if descriminant > 0:\n t1 = float((-b - math.sqrt(descriminant)) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant)) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print('2 intersection points:')\n print('(%.3f,' % float(x2), '%.3f,' % float(y2), '%.3f)' % float(z2))\n print('(%.3f,' % float(x1), '%.3f,' % float(y1), '%.3f)' % float(z1))\n\n\ndef apply_args():\n parameter.opt = int(sys.argv[1])\n parameter.xp = int(sys.argv[2])\n parameter.yp = int(sys.argv[3])\n parameter.zp = int(sys.argv[4])\n parameter.xv = int(sys.argv[5])\n parameter.yv = int(sys.argv[6])\n parameter.zv = int(sys.argv[7])\n parameter.p = int(sys.argv[8])\n\n\ndef main():\n help()\n check_args()\n apply_args()\n if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0:\n sys.exit(84)\n if parameter.opt == 1:\n sphere()\n if parameter.opt == 2:\n cylinder()\n if parameter.opt == 3:\n cone()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#!/usr/bin/python3\n\nimport sys\nimport math\n\nclass parameter :\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\ndef check_args() :\n try :\n int(sys.argv[1])\n int(sys.argv[2])\n int(sys.argv[3])\n int(sys.argv[4])\n int(sys.argv[5])\n int(sys.argv[6])\n int(sys.argv[7])\n int(sys.argv[8])\n except :\n sys.exit(84)\n if len(sys.argv) != 9 :\n sys.exit(84)\n if int(sys.argv[1]) != 1 and int(sys.argv[1]) != 2 and int(sys.argv[1]) != 3 :\n sys.exit(84)\n\ndef help() :\n if len(sys.argv) == 2 and sys.argv[1] == '-h' :\n print (\"USAGE\")\n print (\" ./104intersection opt xp yp zp xv yv zv p\")\n print (\"DESCRIPTION\")\n print (\" opt surface option: 1 for a sphere, 2 for a cylinder, 3 for a cone\")\n print (\" (xp, yp, zp) coordinates of a point by which the light ray passes through\")\n print (\" (xv, yv, zv) coordinates of a vector parallel to the light ray\")\n print (\" p parameter: radius of the sphere, radius of the cylinder, or\")\n print (\" angle formed by the cone and the Z-axis\")\n sys.exit(0)\n\ndef sphere() :\n if parameter.p <= 0 :\n sys.exit(84)\n print(\"Sphere of radius \"+str(parameter.p))\n print(\"Line passing through the point (\"+str(parameter.xp)+\", \"+str(parameter.yp)+\", \"+str(parameter.zp)+\") and parallel to the vector (\"+str(parameter.xv)+\", \"+str(parameter.yv)+\", \"+str(parameter.zv)+\")\")\n a = float(pow(parameter.xv, 2) + pow(parameter.yv, 2) + pow(parameter.zv, 2))\n b = float(parameter.xv*2*parameter.xp + parameter.yv*2*parameter.yp + parameter.zv*2*parameter.zp)\n c = float(pow(parameter.xp, 2) + pow(parameter.yp, 2) + pow(parameter.zp, 2) - pow(parameter.p,2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n\n if descriminant < 0 :\n print(\"No intersection point.\")\n\n if descriminant == 0 :\n t1 = float(- (b / (2 * a)))\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n print(\"1 intersection point:\")\n print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z))\n\n if descriminant > 0 :\n t1 = float((-b - math.sqrt(descriminant) ) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant) ) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print(\"2 intersection points:\")\n print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2))\n print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1))\n\n\ndef cylinder() :\n infiny = 0\n if parameter.p <= 0 :\n sys.exit(84)\n print(\"Cylinder of radius \"+str(parameter.p))\n print(\"Line passing through the point (\"+str(parameter.xp)+\", \"+str(parameter.yp)+\", \"+str(parameter.zp)+\") and parallel to the vector (\"+str(parameter.xv)+\", \"+str(parameter.yv)+\", \"+str(parameter.zv)+\")\")\n a = float(parameter.xv + parameter.yv)\n b = float( 2 * (parameter.xv * parameter.xp + parameter.yv * parameter.yp))\n c = float(pow(parameter.xp,2) + pow(parameter.yp, 2) - pow(parameter.p, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n\n if descriminant < 0 :\n print(\"No intersection point.\")\n\n if descriminant == 0 :\n try:\n t1 = float(- (b / (2 * a)))\n except :\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0 :\n print(\"1 intersection point:\")\n print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z))\n else:\n print(\"There is an infinite number of intersection points.\")\n\n\n if descriminant > 0 :\n t1 = float((-b - math.sqrt(descriminant) ) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant) ) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print(\"2 intersection points:\")\n print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2))\n print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1))\n\ndef cone() :\n if parameter.p <= 0 or parameter.p >= 90 :\n sys.exit(84)\n rad = math.radians(parameter.p)\n print(\"Cone with a\"+str(parameter.p)+\" degree angle\")\n print(\"Line passing through the point (\"+str(parameter.xp)+\", \"+str(parameter.yp)+\", \"+str(parameter.zp)+\") and parallel to the vector (\"+str(parameter.xv)+\", \"+str(parameter.yv)+\", \"+str(parameter.zv)+\")\")\n a = float(parameter.xv + parameter.yv - pow(parameter.zv, 2) * pow(math.tan(rad), 2))\n b = float( 2 * (parameter.xv * parameter.xp + parameter.yv * parameter.yp - pow(math.tan(rad),2) * parameter.zp*parameter.zv))\n c = float(pow(parameter.xp,2) + pow(parameter.yp, 2) - pow(math.tan(rad),2) * pow(parameter.zp, 2))\n descriminant = float(pow(b, 2) - 4 * a * c)\n\n if descriminant < 0 :\n print(\"No intersection point.\")\n\n if descriminant == 0 :\n try:\n t1 = float(- (b / (2 * a)))\n except :\n t1 = 1\n infiny = 1\n x = float(parameter.xp + parameter.xv * t1)\n y = float(parameter.yp + parameter.yv * t1)\n z = float(parameter.zp + parameter.zv * t1)\n if infiny == 0 :\n print(\"1 intersection point:\")\n print('(%.3f,' %float(x), '%.3f,' %float(y), '%.3f)' %float(z))\n else:\n print(\"There is an infinite number of intersection points.\")\n\n if descriminant > 0 :\n t1 = float((-b - math.sqrt(descriminant) ) / (2 * a))\n t2 = float((-b + math.sqrt(descriminant) ) / (2 * a))\n x1 = float(parameter.xp + parameter.xv * t1)\n y1 = float(parameter.yp + parameter.yv * t1)\n z1 = float(parameter.zp + parameter.zv * t1)\n x2 = float(parameter.xp + parameter.xv * t2)\n y2 = float(parameter.yp + parameter.yv * t2)\n z2 = float(parameter.zp + parameter.zv * t2)\n print(\"2 intersection points:\")\n print('(%.3f,' %float(x2), '%.3f,' %float(y2), '%.3f)' %float(z2))\n print('(%.3f,' %float(x1), '%.3f,' %float(y1), '%.3f)' %float(z1))\n\ndef apply_args() :\n parameter.opt = int(sys.argv[1])\n parameter.xp = int(sys.argv[2])\n parameter.yp = int(sys.argv[3])\n parameter.zp = int(sys.argv[4])\n parameter.xv = int(sys.argv[5])\n parameter.yv = int(sys.argv[6])\n parameter.zv = int(sys.argv[7])\n parameter.p = int(sys.argv[8])\n\ndef main():\n help()\n check_args()\n apply_args()\n if parameter.xv == 0 and parameter.yv == 0 and parameter.zv == 0 :\n sys.exit(84)\n if parameter.opt == 1 :\n sphere()\n if parameter.opt == 2 :\n cylinder()\n if parameter.opt == 3 :\n cone()\n\nif __name__ == \"__main__\" :\n main()", "step-ids": [ 5, 7, 8, 11, 12 ] }
[ 5, 7, 8, 11, 12 ]
# Python library import import asyncio, asyncssh, logging # Module logging logger log = logging.getLogger(__package__) # Debug level # logging.basicConfig(level=logging.WARNING) # logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.DEBUG) asyncssh.set_debug_level(2) # Declaration of constant values # Max data to read in read function MAX_BUFFER_DATA = 65535 # Dictonary with all netmasks of IPv4 ipv4_netmask_list = { "0.0.0.0": "0", "128.0.0.0": "1", "192.0.0.0": "2", "224.0.0.0": "3", "240.0.0.0": "4", "248.0.0.0": "5", "252.0.0.0": "6", "254.0.0.0": "7", "255.0.0.0": "8", "255.128.0.0": "9", "255.192.0.0": "10", "255.224.0.0": "11", "255.240.0.0": "12", "255.248.0.0": "13", "255.252.0.0": "14", "255.254.0.0": "15", "255.255.0.0": "16", "255.255.128.0": "17", "255.255.192.0": "18", "255.255.224.0": "19", "255.255.240.0": "20", "255.255.248.0": "21", "255.255.252.0": "22", "255.255.254.0": "23", "255.255.255.0": "24", "255.255.255.128": "25", "255.255.255.192": "26", "255.255.255.224": "27", "255.255.255.240": "28", "255.255.255.248": "29", "255.255.255.252": "30", "255.255.255.254": "31", "255.255.255.255": "32", } class NetworkDevice: """ Base class for network object :param ip: IP address of a device :type ip: str :param username: Username used to connect to a device :type username: str :param password: Password used to connect to a device :type password: str :param device_type: Type of device used :type device_type: str :param port: TCP port used to connect a device. Default value is "22" for SSH :type port: int, optional :param timeout: TCP port used to connect a device. Default value is 10 seconds :type timeout: int, optional :param _protocol: Protocol used to connect a device. "ssh" or "telnet" are possible options. Default value is "ssh" :type _protocol: str, optional :param enable_mode: Enable mode for devices requiring it. Default value is "False" :type enable_mode: bool, optional :param enable_password: Enable password used for enable mode. :type enable_password: str, optional :param conn: Variable used for the management of the SSH connection :type conn: SSHClientConnection object :param _writer: Variable used for the management of the Telnet connection and writing channel :type _writer: StreamWriter object :param _reader: Variable used for the management of the Telnet reading channel :type _reader: StreamReader object :param possible_prompts: Used by the connect method to list all possible prompts of the device :type possible_prompts: list :param _connect_first_ending_prompt: Default possible ending prompts. Used only the time after login and password to discover the prompt :type _connect_first_ending_prompt: list :param list_of_possible_ending_prompts: Different strings at the end of a prompt the device can get. Used for detecting the prompt returned in sent commands :type list_of_possible_ending_prompts: list :param _telnet_connect_login: Login prompt for Telnet. Used to detect when a login is expected or when login and password access is failed :type _telnet_connect_login: str :param _telnet_connect_password: Password prompt for Telnet. Used to detect when a login is expected or when login and password access is failed :type _telnet_connect_password: list :param _telnet_connect_authentication_fail_prompt: Known failing messages or prompts when an authentication has failed. Used to get an answer faster than timeout events :type _telnet_connect_authentication_fail_prompt: list :param cmd_enable: Enable command for entering into enable mode :type cmd_enable: str :param cmd_disable_paging: Command used to disable paging on a device. That command is run at connection time :type cmd_disable_paging: str :param cmd_enter_config_mode: Command used to enter into a configuration mode on a device when this device support that feature. :type cmd_enter_config_mode: str :param cmd_exit_config_mode: Command used to leave a configuration mode on a device when this device support that feature. :type cmd_exit_config_mode: str :param cmd_get_version: API command used to get the software version of a device :type cmd_get_version: str :param cmd_get_hostname: API command used to get the hostname of a device :type cmd_get_hostname: str :param cmd_get_model: API command used to get the model of a device :type cmd_get_model: str :param cmd_get_serial_number: API command used to get the serial number of a device :type cmd_get_serial_number: str :param cmd_get_config: API command used to get the running configuration of a device :type cmd_get_config: str :param cmd_save_config: API command used to save the running configuration on the device :type cmd_save_config: str """ def __init__(self, **kwargs): # Display info message log.info("__init__") self.ip = "" self.username = "" self.password = "" self.device_type = "" self.port = 22 self.timeout = 10 self._protocol = "ssh" self.enable_mode = False self.enable_password = "" self.conn = None self._writer = None self._reader = None self.possible_prompts = [] self._connect_first_ending_prompt = ["#", ">"] self.list_of_possible_ending_prompts = [ "(config-line)#", "(config-if)#", "(config)#", ">", "#", ] self._carriage_return_for_send_command = "\n" self._send_command_error_in_returned_output = [] self._telnet_connect_login = "Username:" self._telnet_connect_password = "Password:" self._telnet_connect_authentication_fail_prompt = [":", "%"] # General commands self.cmd_enable = "enable" self.cmd_disable_paging = "terminal length 0" self.cmd_enter_config_mode = "configure terminal" self.cmd_exit_config_mode = "exit" self.cmd_get_version = "show version" self.cmd_get_hostname = "show version | include uptime" self.cmd_get_model = "show inventory" self.cmd_get_serial_number = "show inventory | i SN" self.cmd_get_config = "show running-config" self.cmd_save_config = "write memory" # Layer 1 commands self.cmd_get_interfaces = [ "interface ethernet print terse without-paging", "foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}", "interface bridge port print terse without-paging", ] self.cmd_set_interface = [ "interface ethernet enable <INTERFACE>", "interface ethernet disable <INTERFACE>", 'interface ethernet comment <INTERFACE> "<COMMENT>"', "interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>", "interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]", ] # Layer 2 commands self.cmd_get_mac_address_table = "interface bridge host print without-paging" self.cmd_get_arp = "ip arp print terse without-paging" self.cmd_get_lldp_neighbors = "ip neighbor print terse without-paging" self.cmd_get_vlans = "interface bridge vlan print terse without-paging" self.cmd_add_vlan = 'interface bridge vlan add vlan-ids=<VLAN> comment="<VLAN_NAME>" bridge=<BRIDGE>' self.cmd_remove_vlan = "interface bridge vlan remove [find vlan-ids=<VLAN>]" self.cmd_add_interface_to_vlan = [ "interface bridge vlan print terse", "interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>", "interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>", "interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>", ] self.cmd_remove_interface_from_vlan = [ "interface bridge vlan print terse", "interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>", "interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>", "interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>", ] # Layer 3 commands self.cmd_get_routing_table = "ip route print without-paging terse" self.cmd_get_interfaces_ip = "ip address print terse without-paging" self.cmd_add_static_route = "ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>" self.cmd_remove_static_route = ( "ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]" ) # Display info message log.debug("__init__: kwargs: " + str(kwargs)) # Get information from dictionary # "ip" found? if "ip" in kwargs: # Save "ip" parameter self.ip = kwargs["ip"] # Display info message log.info("__init__: ip found: " + str(self.ip)) # "username" found? if "username" in kwargs: self.username = kwargs["username"] # Display info message log.info("__init__: username found: " + str(self.username)) # "password" found? if "password" in kwargs: self.password = kwargs["password"] # Display info message log.debug("__init__: password found: " + str(self.password)) # "device_type" found? if "device_type" in kwargs: self.device_type = kwargs["device_type"] # Display info message log.info("__init__: device_type found: " + str(self.device_type)) # "timeout" found? if "timeout" in kwargs: self.timeout = kwargs["timeout"] # Display info message log.info("__init__: timeout found: " + str(self.timeout)) # "protocol" found? if "protocol" in kwargs: self._protocol = kwargs["protocol"].lower() # Display info message log.info("__init__: protocol found: " + str(self._protocol)) # By default telnet port is 23 if self._protocol.lower() == "telnet": self.port = 23 # "port" found? if "port" in kwargs: self.port = kwargs["port"] # Display info message log.info("__init__: port found: " + str(self.port)) # "enable_mode" found? if "enable_mode" in kwargs: self.enable_mode = kwargs["enable_mode"] # Display info message log.info("__init__: enable_mode found: " + str(self.enable_mode)) # "enable_password" found? if "enable_password" in kwargs: self.enable_password = kwargs["enable_password"] # Display info message log.info("__init__: enable_password found: " + str(self.enable_password)) async def __aenter__(self): """ Context manager opening connection """ try: # Run an async method to connect a device await self.connect() except Exception: # Disconnection (if needed) in case the connection is done but something failed await self.disconnect() # propagate exception if needed raise return self # async def _aexit_(self, exc_type, exc_value, traceback): async def __aexit__(self, exc_type, exc_value, traceback): """ Context manager closing connection """ # Close the connection await self.disconnect() def find_prompt(self, text): """ Method used to find a prompt inside an output string This method is used during the first communication with the device. First it find the prompt then caculate the different forms the prompt can take. This will be useful later on while finding prompt in other output stream (read). :param text: data with a prompt :type text: str :return: the prompt found :rtype: str """ # Get last line of the data prompt = text.split("\n")[-1] # Remove possible \r in the data # prompt = prompt.replace("\r", "") prompt = text.split("\r")[-1] # Display info message log.info(f"find_prompt: prompt: '{prompt}'") # Get the possible prompts for future recognition self.possible_prompts = self.get_possible_prompts(prompt) # Return the prompt return prompt def get_possible_prompts(self, prompt): """ Method used to check if a prompt has one of the expected endings then create a list with all possible prompts for the device :param prompt: a prompt with a possible ending prompt (eg. "switch#") :type prompt: str :return: the list of prompts :rtype: list """ # By default no prompts are returned list_of_prompts = [] # Get all the ppossible values of the endings of the prompt list_of_possible_ending_prompts = self.list_of_possible_ending_prompts # Temporary variable storing the prompt value my_prompt = prompt # Test each possible prompt ending (i.e '#', '>', "(config-if)#", "(config)#") for ending in list_of_possible_ending_prompts: # Is this current prompt ending at the end of the prompt? if my_prompt.endswith(ending): # Yes # Then remove the ending my_prompt = my_prompt[: -len(ending)] # Break the loop break # Prompt should be from "switch#" to "switch" # Display info message log.info(f"get_possible_prompts: prompt found: '{my_prompt}'") # Display info message log.info(f"get_possible_prompts: prompt found size: '{len(my_prompt)}'") # Now create all the possible prompts for that device for ending in list_of_possible_ending_prompts: # Save the prompt name with a possible ending in the list list_of_prompts.append(my_prompt + ending) # Display info message log.info(f"get_possible_prompts: list of possible prompts: {list_of_prompts}") # Return the list of prompts return list_of_prompts def check_if_prompt_is_found(self, text): """ Method used to check if a prompt is detected inside a string :param text: a string with prompt :type text: str :return: the prompt found :rtype: str """ # By default the prompt is not found prompt_found = False # Check all possible prompts for prompt in self.possible_prompts: # Display info message log.info(f"check_if_prompt_is_found: prompt: '{prompt}'") # Is this prompt present in the text? if prompt in text: # Yes prompt_found = True # Display info message log.info(f"check_if_prompt_is_found: prompt found: '{prompt}'") # Leave the for loop break # Return the prompt found return prompt_found def remove_command_in_output(self, text, cmd): """ Method removing the command at the beginning of a string After sending commands an "echo" of the command sent is display in the output string. This method removes it. :param text: the text with the command at the beginning :type text: str :param cmd: the command previously sent :type cmd: str :return: the output string without the command :rtype: str """ # Display info message log.info(f"remove_command_in_output: cmd = '{cmd}'") # Display info message log.info(f"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'") # Remove the command from the beginning of the output # output = text.lstrip(cmd + "\n") output = text.split(cmd + "\n")[-1] # Display info message log.info(f"remove_command_in_output: output = '{output}'") # Return the string without the command return output def remove_starting_carriage_return_in_output(self, text): """ Method removing the carriage return at the beginning of a string :param text: the text with the command at the beginning :type text: str :return: the output string without the starting carriage return :rtype: str """ # Display info message log.info("remove_starting_carriage_return_in_output") # Remove the carriage return at the beginning of the string output = text.lstrip("\r\n\r") # Display info message log.info(f"remove_starting_carriage_return_in_output: output = '{output}'") # Return the string without the starting carriage return return output def remove_ending_prompt_in_output(self, text): """ Method removing the prompt at the end of a string :param text: the text with a prompt at the beginning :type text: str :return: the output string without the ending prompt :rtype: str """ # Display info message log.info("remove_ending_prompt_in_output") # Check all possible prompts for prompt in self.possible_prompts: # Display info message log.info(f"remove_ending_prompt_in_output: prompt: '{prompt}'") # Prompt found in the text? if prompt in text: # Yes # Then it is removed from the text # text = text.rstrip(prompt) text = text[: -len(prompt)] # Remove also carriage return text = text.rstrip("\r\n") # Leave the loop break # output = text.rstrip("\r\n" + self.prompt) # Display info message log.info(f"remove_ending_prompt_in_output: text without prompt:\n'{text}'") # Return the text without prompt at the end return text def check_error_output(self, output): """ Check if an error is returned by the device ("% Unrecognized command", "% Ambiguous command", etc.) If an error is found, then an exception is raised """ # Display info message log.info("check_error_output") # Check if output has some data if output: # Yes # Display info message log.info("check_error_output: output has some data") # Check all elements in the list of output for element in self._send_command_error_in_returned_output: # Display info message log.info(f"check_error_output: element: {element}") # Display info message log.info(f"check_error_output: output[0]: {output[0]}") # Check if the output starts with a string with an error message (like "% Invalid input detected at '^' marker.") # Error message? if output.startswith(element): # Yes # Raise an exception raise Exception(output) def remove_ansi_escape_sequence(self, text): """ Method removing ANSI escape sequence from a string Just CSI sequences are removed :param text: the text with a prompt at the beginning :type text: str :return: the output string without the ending prompt :rtype: str """ # By default no string returned output = "" # By default no escape sequence found esc_found = 0 # Read char by char a string for i in text: # Display char # log.info(f"{str(i).encode('ascii')}") # No escape previously found? if esc_found == 0: # No escape sequence currently found # Escape? if i == "\x1b": # Yes log.info("Esc!") # Escape found esc_found = 1 else: # No # Then the current char can be saved output += i # Escape previously found? elif esc_found == 1: # Yes # Then check if this is a CSI sequence if i == "[": # Beginning of CSI sequence log.info("CSI sequence") # CSI sequence esc_found = 2 else: # Another Escape sequence # Keep the escape sequence in the string output += "\x1b" + i # No escape sequence next esc_found = 0 else: # Char between 'a' and 'z' or 'A' and 'Z'? if (i >= "a" and i <= "z") or (i >= "A" and i <= "Z"): # Yes # Then it is the end of CSI escape sequence log.info("End of escape sequence") # No escape sequence next esc_found = 0 # Return a string without ANSI escape sequence return output async def disable_paging(self): """ Async method disabling paging on a device Use the "cmd_disable_paging" attribute """ # Display info message log.info("disable_paging") # Send command to the device to disable paging await self.send_command(self.cmd_disable_paging) async def connect(self): """ Async method used for connecting a device Currently supported: SSH and Telnet """ # Display info message log.info("connect") try: # SSH? if self._protocol == "ssh": # Yes # Then Connect using SSH await self.connectSSH() # Telnet? elif self._protocol == "telnet": # Yes # Then Connect using Telnet await self.connectTelnet() else: # Unsupported protocol # Raise an exception raise Exception(f"connect: unsupported protocol: {self._protocol}") except Exception: # There was a problem with a connection method # Display info message log.info("connect: connection error") raise async def connectSSH(self): """ Async method used for connecting a device using SSH protocol """ # Display info message log.info("connectSSH") # Parameters of the connection generator = asyncssh.connect( self.ip, username=self.username, password=self.password, known_hosts=None, # encryption_algs="*", # Parameter that includes all encryption algorithms (even the old ones disabled by default) encryption_algs=[ algs.decode("utf-8") for algs in asyncssh.encryption._enc_algs ], # Parameter that includes all encryption algorithms (even the old ones disabled by default) ) # Trying to connect to the device try: self.conn = await asyncio.wait_for(generator, timeout=self.timeout) except asyncio.exceptions.TimeoutError as error: # Timeout # Display error message log.error(f"connectSSH: connection failed: {self.ip} timeout: '{error}'") # Exception propagation raise asyncio.exceptions.TimeoutError( "Connection failed: connection timed out." ) except Exception as error: # Connection failed # Display error message log.error(f"connectSSH: connection failed: {self.ip} '{error}'") # Exception propagation raise # Display info message log.info("connectSSH: connection success") # Create a session self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type="netscud") # Display info message log.info("connectSSH: open_session success") # By default no data has been read data = "" # By default no prompt found prompt_not_found = True try: # Read data while prompt_not_found: # Display info message log.info("connectSSH: beginning of the loop") # Read the prompt data += await asyncio.wait_for( self.stdoutx.read(MAX_BUFFER_DATA), timeout=self.timeout ) # Display info message log.info(f"connectSSH: data: '{str(data)}'") # Display info message log.info(f"connectSSH: data: hex:'{data.encode('utf-8').hex()}'") # Check if an initial prompt is found for prompt in self._connect_first_ending_prompt: # Ending prompt found? if data.endswith(prompt): # Yes # Display info message log.info(f"connectSSH: first ending prompt found: '{prompt}'") # A ending prompt has been found prompt_not_found = False # Leave the loop break # Display info message log.info("connectSSH: end of loop") except Exception as error: # Fail while reading the prompt # Display error message log.error( f"connectSSH: timeout while reading the prompt: {self.ip} '{error}'" ) # Exception propagation raise # Display info message log.info(f"connectSSH: end of prompt loop") # Remove possible escape sequence data = self.remove_ansi_escape_sequence(data) # Find prompt self.prompt = self.find_prompt(str(data)) # Display info message log.info(f"connectSSH: prompt found: '{self.prompt}'") # Display info message log.info(f"connectSSH: prompt found size: '{len(self.prompt)}'") # Disable paging command available? if self.cmd_disable_paging: # Yes # Disable paging await self.disable_paging() async def connectTelnet(self): """ Async method used for connecting a device using Telnet protocol """ # Display info message log.info("connectTelnet") try: # Prepare connection with Telnet conn = asyncio.open_connection(self.ip, self.port) except Exception as error: # Preparation to the connection failed # Display error message log.error(f"connectTelnet: preparation to the connection failed: '{error}'") # Exception propagation raise # Display info message log.info("connectTelnet: preparation to the connection success") try: # Connection with Telnet self._reader, self._writer = await asyncio.wait_for( conn, timeout=self.timeout ) except asyncio.TimeoutError: # Time out during connection # Display error message log.error("connectTelnet: connection: timeout") # Exception propagation raise # Display info message log.info("connectTelnet: connection success") # Get prompt for the login prompt = self._telnet_connect_login # Get prompt for the password prompt_password = self._telnet_connect_password # By default a login is expected use_login = True # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" # Read the telnet information and first prompt (for login but a password prompt can be found for IOS for instance) while True: # Display info message log.info(f"connectTelnet: read data for prompt") # Read returned prompt byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=self.timeout ) # Display info message log.info(f"connectTelnet: byte_data: {byte_data}") # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info(f"connectTelnet: output: {output}") # Prompt for the username found? if prompt in output: # Yes # Leave the loop break # Prompt for the password found? elif prompt_password in output: # Yes # That means only password is required use_login = False # Leave the loop break # Display info message log.info(f"connectTelnet: login prompt: '{output}'") # Login to use? if use_login: # Yes # Display info message log.info("connectTelnet: sending login") try: # Send login await self.send_command(self.username, prompt_password) # Display info message log.info("connectTelnet: login sent") except Exception: # Problem with the login # Propagate the exception raise # Display info message log.info("connectTelnet: sending password") try: # Send password output = await self.telnet_send_command_with_unexpected_pattern( self.password, self._connect_first_ending_prompt, self._telnet_connect_authentication_fail_prompt, ) except Exception: # Problem with the password # Propagate the exception raise # Display info message log.info("connectTelnet: password sent") # Find prompt self.prompt = self.find_prompt(str(output)) # Display info message log.info(f"connectTelnet: prompt found: '{self.prompt}'") # Password enable? if self.enable_mode: # Yes # Display info message log.info("connectTelnet: enable mode to be activated") try: # Send enable command await self.send_command(self.cmd_enable, prompt_password) # Display info message log.info("connectTelnet: enable command sent") # Display info message log.info("connectTelnet: sending enable password") # Send enable password await self.telnet_send_command_with_unexpected_pattern( self.enable_password, self._connect_first_ending_prompt, self._telnet_connect_authentication_fail_prompt, ) # Display info message log.info("connectTelnet: enable password sent") except Exception: # Problem with the enable password # Display info message log.info("connectTelnet: enable password failure") # Propagate the exception raise # Disable paging command available? if self.cmd_disable_paging: # Yes # Disable paging await self.disable_paging() async def disconnect(self): """ Async method used to disconnect a device If this method is not used then exceptions will happen when the program will end """ # Debug info message log.info("disconnect") # SSH? if self._protocol == "ssh": # Yes # Then disconnect using SSH await self.disconnectSSH() # Telnet? elif self._protocol == "telnet": # Yes # Then disconnect using Telnet await self.disconnectTelnet() else: # Unsupported protocol # Raise an exception raise Exception(f"Unsupported protocol: {self._protocol}") async def disconnectSSH(self): """ Async method used to disconnect a device in SSH If this method is not used then exceptions will happen when the program will end """ # Debug info message log.info("disconnectSSH") # Connection previously open in SSH? if self.conn: # Yes # Then close the SSH connection self.conn.close() # No more connection to disconnect self.conn = None async def disconnectTelnet(self): """ Async method used to disconnect a device in Telnet If this method is not used then exceptions will happen when the program will end """ # Debug info message log.info("disconnectTelnet") # Connection previously open in Telnet? if self._writer: # Yes # Then close the SSH connection self._writer.close() # No more connection to disconnect self._writer = None async def send_command(self, cmd, pattern=None, timeout=None): """ Async method used to send data to a device :param cmd: command to send :type cmd: str :param pattern: optional, a pattern replacing the prompt when the prompt is not expected :type pattern: str :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the output of command :rtype: str """ # Debug info message log.info("send_command") # Default value of timeout variable if timeout is None: timeout = self.timeout # SSH? if self._protocol == "ssh": # Yes # Then disconnect using SSH output = await self.send_commandSSH(cmd, pattern=pattern, timeout=timeout) # Telnet? elif self._protocol == "telnet": # Yes # Then disconnect using Telnet output = await self.send_commandTelnet( cmd, pattern=pattern, timeout=timeout ) else: # Unsupported protocol # Raise an exception raise Exception(f"send_command: unsupported protocol: {self._protocol}") # Return the result of the command return output async def send_commandSSH(self, cmd, pattern=None, timeout=None): """ Async method used to send data to a device :param cmd: command to send :type cmd: str :param pattern: optional, a pattern replacing the prompt when the prompt is not expected :type pattern: str :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the output of command :rtype: str """ # Debug info message log.info("send_commandSSH") # Default value of timeout variable if timeout is None: timeout = self.timeout # Add carriage return at the end of the command (mandatory to send the command) # cmd = cmd + "\n" # cmd = cmd + "\r\n" # Debug info message log.info(f"send_commandSSH: cmd = '{cmd}'") # Sending command self.stdinx.write(cmd + self._carriage_return_for_send_command) # Display message log.info("send_commandSSH: command sent") # Variable used to gather data output = "" # Reading data while True: # await asyncio.sleep(1) # Read the data received output += await asyncio.wait_for( self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout ) # Debug info message # log.info(f"send_commandSSH: output hex: '{str(output).encode("utf-8").hex()}'") # Remove ANSI escape sequence output = self.remove_ansi_escape_sequence(output) # Remove possible "\r" output = output.replace("\r", "") # data = "" # for i in output: # data += i.encode("utf-8").hex() # print(data) # Debug info message log.info(f"send_commandSSH: output: '{output}'") # Is a patten used? if pattern: # Use pattern instead of prompt if pattern in output: # Yes # Leave the loop break else: # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break # Debug info message log.debug( f"send_commandSSH: raw output: '{output}'\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'" ) # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Debug info message log.debug( f"send_commandSSH: cleaned output: '{output}'\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) # Return the result of the command return output async def send_commandTelnet(self, cmd, pattern=None, timeout=None): """ Async method used to send data to a device :param cmd: command to send :type cmd: str :param pattern: optional, a pattern replacing the prompt when the prompt is not expected :type pattern: str :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the output of command :rtype: str """ # Debug info message log.info("send_commandTelnet") # Default value of timeout variable if timeout is None: timeout = self.timeout # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + "\n" # Sending command self._writer.write(cmd.encode()) # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" try: # Read data while True: # Read returned prompt byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=timeout ) # Display info message log.info(f"send_commandTelnet: byte_data: '{byte_data}'") # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info(f"send_commandTelnet: output: '{output}'") # Is a patten used? if pattern: # Use pattern instead of prompt if pattern in output: # Yes # Leave the loop break else: # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break except asyncio.TimeoutError: # Time out during when reading prompt # Display error message log.error("send_commandTelnet: connection: timeout") # Exception propagation raise except Exception as error: # Error during when reading prompt # Display error message log.error(f"send_commandTelnet: error: {error}") # Exception propagation raise # Convert data (bytes) into string output = byte_data.decode("utf-8", "ignore") # Debug info message log.debug( f"send_commandTelnet: raw output: '{output}'\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'" ) # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Debug info message log.debug( f"send_commandTelnet: cleaned output: '{output}'\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) # Return the result of the command return output async def telnet_send_command_with_unexpected_pattern( self, cmd, pattern, error_pattern=None, timeout=None ): """ Async method used to send command for Telnet connection to a device with possible unexpected patterns send_command can wait till time out if login and password are wrong. This method speed up the returned error message when authentication failed is identified. This method is limited to authentication whem password is required :param cmd: command to send :type cmd: str :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used to define a custom or unexpected prompt a the end of a string :type pattern: str :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :param error_pattern: optional, a list of failed prompts found when the login and password are not correct :type error_pattern: str :return: the output of command :rtype: str """ # Debug info message log.info("telnet_send_command_with_unexpected_pattern") # Default value of timeout variable if timeout is None: timeout = self.timeout # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Sending command self._writer.write(cmd.encode()) # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" # By default pattern is not found pattern_not_found = True try: # Read data while pattern_not_found: # Read returned prompt byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=timeout ) # Display info message log.info( f"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'" ) # Display debug message log.debug( f"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'" ) # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info( f"telnet_send_command_with_unexpected_pattern: output: '{output}'" ) # Is a pattern used? if pattern: # Check all pattern of prompt in the output for prompt in pattern: # Display info message log.info( f"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'" ) # A pattern found? if prompt in output: # Yes # A pattern is found. The main loop can be stopped pattern_not_found = False # Display info message log.info( f"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'" ) # Leave the loop break # Is an unexpected pattern used? if error_pattern and pattern_not_found: # Check all unexpected pattern of prompt in the output for bad_prompt in error_pattern: # Display info message log.info( f"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'" ) # An error_pattern pattern found? if bad_prompt in output: # Yes # Display error message log.error( "telnet_send_command_with_unexpected_pattern: authentication failed" ) # Raise exception raise Exception( "telnet_send_command_with_unexpected_pattern: authentication failed" ) # Leave the loop # break except asyncio.TimeoutError: # Time out during when reading prompt # Close the connection in order to not display RuntimeError await self.disconnect() # Display error message log.error( "telnet_send_command_with_unexpected_pattern: reading prompt: timeout" ) # Exception propagation raise except Exception as error: # Error during when reading prompt # Close the connection in order to not display RuntimeError await self.disconnect() # Display error message log.error( f"telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}" ) # Exception propagation raise # Convert data (bytes) into string output = byte_data.decode("utf-8", "ignore") # Debug info message log.debug( f"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'" ) # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Debug info message log.debug( f"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'" ) # Return the result of the command return output async def send_config_set(self, cmds=None, timeout=None): """ Async method used to send command in config mode The commands send can be either a string a list of strings. There are 3 steps: - Entering configuration mode - Sending the commands - Leaving configuration mode :param cmds: The commands to the device :type cmds: str or list :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the results of the commands sent :rtype: list of str """ # Display info message log.info("send_config_set") # Default value of timeout variable if timeout is None: timeout = self.timeout # Debug info message log.info("send_command") # SSH? if self._protocol == "ssh": # Yes # Then disconnect using SSH output = await self.send_config_setSSH(cmds, timeout) # Telnet? elif self._protocol == "telnet": # Yes # Then disconnect using Telnet output = await self.send_config_setTelnet(cmds, timeout) else: # Unsupported protocol # Raise an exception raise Exception(f"send_config_set: unsupported protocol: {self._protocol}") # Return the result of the commands return output async def send_config_setSSH(self, cmds=None, timeout=None): """ Async method used to send command in config mode The commands send can be either a string a list of strings. There are 3 steps: - Entering configuration mode - Sending the commands - Leaving configuration mode :param cmds: The commands to the device :type cmds: str or list :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the results of the commands sent :rtype: list of str """ # Display info message log.info("send_config_setSSH") # Default value of timeout variable if timeout is None: timeout = self.timeout # Clear returned output returned_output = "" # Check if cmds is a string if isinstance(cmds, str): # A string # Convert the string into a list cmds = [cmds] # A list? elif not isinstance(cmds, list): # Not a list (and not a string) # Display error message log.error( "send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list" ) # Leave the method return returned_output ############################## # Entering configuration mode ############################## # Display info message log.info("send_config_set: entering configuration mode") # Clear output output = "" # Get command for entering in config made cmd = self.cmd_enter_config_mode # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setSSH: cmd = '{cmd}'") # Sending command self.stdinx.write(cmd) # Display message log.info("send_config_setSSH: configuration mode entered") while True: # Read the data received output += await asyncio.wait_for( self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout ) # Display info message log.info(f"send_config_setSSH: output: '{output}'") # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break # Debug info message log.debug( f"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) ############################## # Sending commands ############################## # Display info message log.info("send_config_setSSH: sending commands") # Clear output output = "" # Each command for cmd in cmds: # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setSSH: cmd = '{cmd}'") # Sending command self.stdinx.write(cmd) # Display info message log.info("send_config_setSSH: command sent") while True: # Read the data received output += await asyncio.wait_for( self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout ) # Display info message log.info(f"send_config_setSSH: output: '{output}'") # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break # Debug info message log.debug( f"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) ############################## # Leaving configuration mode ############################## # Display info message log.info("send_config_setSSH: leaving configuration mode") # Clear output output = "" # Get command to leave config made cmd = self.cmd_exit_config_mode # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setSSH: cmd = '{cmd}'") # Sending command self.stdinx.write(cmd) # Display info message log.info("send_config_setSSH: command to leave configuration mode sent") while True: # Read the data received output += await asyncio.wait_for( self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout ) # Display info message log.info(f"send_config_setSSH: output: '{output}'") # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break # Debug info message log.debug( f"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) # Return the result of the commands return returned_output async def send_config_setTelnet(self, cmds=None, timeout=None): """ Async method used to send command in config mode The commands send can be either a string a list of strings. There are 3 steps: - Entering configuration mode - Sending the commands - Leaving configuration mode :param cmds: The commands to the device :type cmds: str or list :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: the results of the commands sent :rtype: list of str """ # Display info message log.info("send_config_setTelnet") # Default value of timeout variable if timeout is None: timeout = self.timeout # Clear returned output returned_output = "" # Check if cmds is a string if isinstance(cmds, str): # A string # Convert the string into a list cmds = [cmds] # A list? elif not isinstance(cmds, list): # Not a list (and not a string) # Display error message log.error( "send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list" ) # Leave the method return returned_output ############################## # Entering configuration mode ############################## # Display info message log.info("send_config_setTelnet: entering configuration mode") # Clear output output = "" # Get command for entering in config made cmd = self.cmd_enter_config_mode # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setTelnet: cmd = '{cmd}'") # Sending command self._writer.write(cmd.encode()) # Display message log.info("send_config_setTelnet: configuration mode entered") # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" try: # Read data while True: # Read the data received byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=timeout ) # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info(f"send_config_setTelnet: output: '{output}'") # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break except asyncio.TimeoutError: # Time out during when reading prompt # Display error message log.error("send_config_setTelnet: connection: timeout") # Exception propagation raise except Exception as error: # Error during when reading prompt # Display error message log.error(f"send_config_setTelnet: error: {error}") # Exception propagation raise # Convert data (bytes) into string output = byte_data.decode("utf-8", "ignore") # Debug info message log.debug( f"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) ############################## # Sending commands ############################## # Display info message log.info("send_config_setTelnet: sending commands") # Clear output output = "" # Each command for cmd in cmds: # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setTelnet: cmd = '{cmd}'") # Sending command self._writer.write(cmd.encode()) # Display info message log.info("send_config_setTelnet: command sent") # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" try: # Read data while True: # Read the data received byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=timeout ) # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info(f"send_config_setTelnet: output: '{output}'") # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break except asyncio.TimeoutError: # Time out during when reading prompt # Display error message log.error("send_config_setTelnet: connection: timeout") # Exception propagation raise except Exception as error: # Error during when reading prompt # Display error message log.error(f"send_config_setTelnet: error: {error}") # Exception propagation raise # Convert data (bytes) into string output = byte_data.decode("utf-8", "ignore") # Debug info message log.debug( f"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) ############################## # Leaving configuration mode ############################## # Display info message log.info("send_config_setTelnet: leaving configuration mode") # Clear output output = "" # Get command to leave config made cmd = self.cmd_exit_config_mode # Add carriage return at the end of the command (mandatory to send the command) cmd = cmd + self._carriage_return_for_send_command # Display info message log.info(f"send_config_setTelnet: cmd = '{cmd}'") # Sending command self._writer.write(cmd.encode()) # Display info message log.info("send_config_setTelnet: command to leave configuration mode sent") # Temporary string variable output = "" # Temporary bytes variable byte_data = b"" # Protection against infinite loop loop = 3 try: # Read data while loop: # Read the data received byte_data += await asyncio.wait_for( self._reader.read(MAX_BUFFER_DATA), timeout=timeout ) # Temporary convertion in string. This string has the following form: "b'....'" output = str(byte_data) # Display info message log.info(f"send_config_setTelnet: output: '{output}'") await asyncio.sleep(0.5) # Check if prompt is found if self.check_if_prompt_is_found(output): # Yes # Leave the loop break # Protection for "exit" command infinite loop in Cisco when enable is not activated loop -= 1 except asyncio.TimeoutError: # Time out during when reading prompt # Display error message log.error("send_config_setTelnet: connection: timeout") # Exception propagation raise except Exception as error: # Error during when reading prompt # Display error message log.error(f"send_config_setTelnet: error: {error}") # Exception propagation raise # Convert data (bytes) into string output = byte_data.decode("utf-8", "ignore") # Debug info message log.debug( f"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'" ) # Add the output to the returned output returned_output += output # Remove the command sent from the result of the command output = self.remove_command_in_output(output, str(cmd)) # Remove the carriage return of the output output = self.remove_starting_carriage_return_in_output(output) # Remove the ending prompt of the output output = self.remove_ending_prompt_in_output(output) # Display info message log.debug( f"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'" ) # Check if there is an error in the output string (like "% Unrecognized command") # and generate an exception if needed self.check_error_output(output) # Return the result of the commands return returned_output ######################################################### # # List of API # ######################################################### async def get_version(self): """ Asyn method used to get the version of the software of the device :return: Version of the software of the device :rtype: str """ # Display info message log.info("get_version") # By default empty string version = "" # Run get version on the device output = await self.send_command(self.cmd_get_version) # Seek "Version " and "," to get the version in the returned output version = output.split("Version ")[1].split(",")[0] # Display info message log.info(f"get_version: version: {version}") # Return the version of the software of the device return version async def get_hostname(self): """ Asyn method used to get the name of the device :return: Name of the device :rtype: str """ # Display info message log.info("get_hostname") # Get hostname output = await self.send_command(self.cmd_get_hostname) # Display info message log.info(f"get_hostname: output: '{output}'") # Remove the useless information in the returned string output = output.split()[0] # Display info message log.info(f"get_hostname: hostname found: '{output}'") # Return the name of the device return output async def get_model(self): """ Asyn method used to get the model of the device :return: Model of the device :rtype: str """ # Display info message log.info("get_model") # Get model output = await self.send_command(self.cmd_get_model) # Display info message log.info(f"get_model: output: '{output}'") # Remove the useless information in the returned string output = output.split('"')[3] # Display info message log.info(f"get_model: model found: '{output}'") # Return the model of the device return output async def get_serial_number(self): """ Get serial number of the switch or the serial number of the first switch of a stack :return: Serial number of the device :rtype: str """ # Display info message log.info("get_serial_number") # Get serial number output = await self.send_command(self.cmd_get_serial_number) # Display info message log.info(f"get_serial_number: output: '{output}'") # Remove the useless information in the returned string output = output.splitlines()[0].split()[-1] # Display info message log.info(f"get_hostname: hostname found: '{output}'") # Return the serial number of the device return output async def get_config(self, timeout=None): """ Asyn method used to get the configuration of the device :param timeout: optional, a timeout for the command sent. Default value is self.timeout :type timeout: str :return: Configuration of the device :rtype: str """ # Display info message log.info("get_config") # Default value of timeout variable if timeout is None: timeout = self.timeout # Get config output = await self.send_command(self.cmd_get_config, timeout=timeout) # Return de configuration of the device return output async def save_config(self): """ Asyn method used to save the current configuration on the device :return: Commands of the configuration saving process :rtype: str """ # Display info message log.info("save_config") # Send command output = await self.send_command(self.cmd_save_config) # Return the commands of the configuration saving process return output
normal
{ "blob_id": "87baaf4a1b48fa248c65d26cc44e819a2ede1140", "index": 3736, "step-1": "<mask token>\n\n\nclass NetworkDevice:\n <mask token>\n\n def __init__(self, **kwargs):\n log.info('__init__')\n self.ip = ''\n self.username = ''\n self.password = ''\n self.device_type = ''\n self.port = 22\n self.timeout = 10\n self._protocol = 'ssh'\n self.enable_mode = False\n self.enable_password = ''\n self.conn = None\n self._writer = None\n self._reader = None\n self.possible_prompts = []\n self._connect_first_ending_prompt = ['#', '>']\n self.list_of_possible_ending_prompts = ['(config-line)#',\n '(config-if)#', '(config)#', '>', '#']\n self._carriage_return_for_send_command = '\\n'\n self._send_command_error_in_returned_output = []\n self._telnet_connect_login = 'Username:'\n self._telnet_connect_password = 'Password:'\n self._telnet_connect_authentication_fail_prompt = [':', '%']\n self.cmd_enable = 'enable'\n self.cmd_disable_paging = 'terminal length 0'\n self.cmd_enter_config_mode = 'configure terminal'\n self.cmd_exit_config_mode = 'exit'\n self.cmd_get_version = 'show version'\n self.cmd_get_hostname = 'show version | include uptime'\n self.cmd_get_model = 'show inventory'\n self.cmd_get_serial_number = 'show inventory | i SN'\n self.cmd_get_config = 'show running-config'\n self.cmd_save_config = 'write memory'\n self.cmd_get_interfaces = [\n 'interface ethernet print terse without-paging',\n 'foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}'\n , 'interface bridge port print terse without-paging']\n self.cmd_set_interface = ['interface ethernet enable <INTERFACE>',\n 'interface ethernet disable <INTERFACE>',\n 'interface ethernet comment <INTERFACE> \"<COMMENT>\"',\n 'interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>',\n 'interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]'\n ]\n self.cmd_get_mac_address_table = (\n 'interface bridge host print without-paging')\n self.cmd_get_arp = 'ip arp print terse without-paging'\n self.cmd_get_lldp_neighbors = 'ip neighbor print terse without-paging'\n self.cmd_get_vlans = 'interface bridge vlan print terse without-paging'\n self.cmd_add_vlan = (\n 'interface bridge vlan add vlan-ids=<VLAN> comment=\"<VLAN_NAME>\" bridge=<BRIDGE>'\n )\n self.cmd_remove_vlan = (\n 'interface bridge vlan remove [find vlan-ids=<VLAN>]')\n self.cmd_add_interface_to_vlan = ['interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_remove_interface_from_vlan = [\n 'interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_get_routing_table = 'ip route print without-paging terse'\n self.cmd_get_interfaces_ip = 'ip address print terse without-paging'\n self.cmd_add_static_route = (\n 'ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>'\n )\n self.cmd_remove_static_route = (\n 'ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]')\n log.debug('__init__: kwargs: ' + str(kwargs))\n if 'ip' in kwargs:\n self.ip = kwargs['ip']\n log.info('__init__: ip found: ' + str(self.ip))\n if 'username' in kwargs:\n self.username = kwargs['username']\n log.info('__init__: username found: ' + str(self.username))\n if 'password' in kwargs:\n self.password = kwargs['password']\n log.debug('__init__: password found: ' + str(self.password))\n if 'device_type' in kwargs:\n self.device_type = kwargs['device_type']\n log.info('__init__: device_type found: ' + str(self.device_type))\n if 'timeout' in kwargs:\n self.timeout = kwargs['timeout']\n log.info('__init__: timeout found: ' + str(self.timeout))\n if 'protocol' in kwargs:\n self._protocol = kwargs['protocol'].lower()\n log.info('__init__: protocol found: ' + str(self._protocol))\n if self._protocol.lower() == 'telnet':\n self.port = 23\n if 'port' in kwargs:\n self.port = kwargs['port']\n log.info('__init__: port found: ' + str(self.port))\n if 'enable_mode' in kwargs:\n self.enable_mode = kwargs['enable_mode']\n log.info('__init__: enable_mode found: ' + str(self.enable_mode))\n if 'enable_password' in kwargs:\n self.enable_password = kwargs['enable_password']\n log.info('__init__: enable_password found: ' + str(self.\n enable_password))\n\n async def __aenter__(self):\n \"\"\"\n Context manager opening connection\n \"\"\"\n try:\n await self.connect()\n except Exception:\n await self.disconnect()\n raise\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback):\n \"\"\"\n Context manager closing connection\n \"\"\"\n await self.disconnect()\n\n def find_prompt(self, text):\n \"\"\"\n Method used to find a prompt inside an output string\n\n This method is used during the first communication with the device.\n First it find the prompt then caculate the different forms the prompt\n can take. This will be useful later on while finding prompt in other\n output stream (read).\n\n :param text: data with a prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt = text.split('\\n')[-1]\n prompt = text.split('\\r')[-1]\n log.info(f\"find_prompt: prompt: '{prompt}'\")\n self.possible_prompts = self.get_possible_prompts(prompt)\n return prompt\n\n def get_possible_prompts(self, prompt):\n \"\"\"\n Method used to check if a prompt has one of the expected endings then\n create a list with all possible prompts for the device\n\n :param prompt: a prompt with a possible ending prompt (eg. \"switch#\")\n :type prompt: str\n\n :return: the list of prompts\n :rtype: list\n \"\"\"\n list_of_prompts = []\n list_of_possible_ending_prompts = self.list_of_possible_ending_prompts\n my_prompt = prompt\n for ending in list_of_possible_ending_prompts:\n if my_prompt.endswith(ending):\n my_prompt = my_prompt[:-len(ending)]\n break\n log.info(f\"get_possible_prompts: prompt found: '{my_prompt}'\")\n log.info(f\"get_possible_prompts: prompt found size: '{len(my_prompt)}'\"\n )\n for ending in list_of_possible_ending_prompts:\n list_of_prompts.append(my_prompt + ending)\n log.info(\n f'get_possible_prompts: list of possible prompts: {list_of_prompts}'\n )\n return list_of_prompts\n\n def check_if_prompt_is_found(self, text):\n \"\"\"\n Method used to check if a prompt is detected inside a string\n\n :param text: a string with prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt_found = False\n for prompt in self.possible_prompts:\n log.info(f\"check_if_prompt_is_found: prompt: '{prompt}'\")\n if prompt in text:\n prompt_found = True\n log.info(f\"check_if_prompt_is_found: prompt found: '{prompt}'\")\n break\n return prompt_found\n\n def remove_command_in_output(self, text, cmd):\n \"\"\"\n Method removing the command at the beginning of a string\n\n After sending commands an \"echo\" of the command sent\n is display in the output string. This method removes it.\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :param cmd: the command previously sent\n :type cmd: str\n\n :return: the output string without the command\n :rtype: str\n \"\"\"\n log.info(f\"remove_command_in_output: cmd = '{cmd}'\")\n log.info(\n f\"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'\")\n output = text.split(cmd + '\\n')[-1]\n log.info(f\"remove_command_in_output: output = '{output}'\")\n return output\n\n def remove_starting_carriage_return_in_output(self, text):\n \"\"\"\n Method removing the carriage return at the beginning of a string\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :return: the output string without the starting carriage return\n :rtype: str\n \"\"\"\n log.info('remove_starting_carriage_return_in_output')\n output = text.lstrip('\\r\\n\\r')\n log.info(\n f\"remove_starting_carriage_return_in_output: output = '{output}'\")\n return output\n <mask token>\n\n def check_error_output(self, output):\n \"\"\"\n Check if an error is returned by the device (\"% Unrecognized command\", \"% Ambiguous command\", etc.)\n\n If an error is found, then an exception is raised\n \"\"\"\n log.info('check_error_output')\n if output:\n log.info('check_error_output: output has some data')\n for element in self._send_command_error_in_returned_output:\n log.info(f'check_error_output: element: {element}')\n log.info(f'check_error_output: output[0]: {output[0]}')\n if output.startswith(element):\n raise Exception(output)\n\n def remove_ansi_escape_sequence(self, text):\n \"\"\"\n Method removing ANSI escape sequence from a string\n Just CSI sequences are removed\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n output = ''\n esc_found = 0\n for i in text:\n if esc_found == 0:\n if i == '\\x1b':\n log.info('Esc!')\n esc_found = 1\n else:\n output += i\n elif esc_found == 1:\n if i == '[':\n log.info('CSI sequence')\n esc_found = 2\n else:\n output += '\\x1b' + i\n esc_found = 0\n elif i >= 'a' and i <= 'z' or i >= 'A' and i <= 'Z':\n log.info('End of escape sequence')\n esc_found = 0\n return output\n\n async def disable_paging(self):\n \"\"\"\n Async method disabling paging on a device\n\n Use the \"cmd_disable_paging\" attribute\n \"\"\"\n log.info('disable_paging')\n await self.send_command(self.cmd_disable_paging)\n\n async def connect(self):\n \"\"\"\n Async method used for connecting a device\n\n Currently supported: SSH and Telnet\n \"\"\"\n log.info('connect')\n try:\n if self._protocol == 'ssh':\n await self.connectSSH()\n elif self._protocol == 'telnet':\n await self.connectTelnet()\n else:\n raise Exception(\n f'connect: unsupported protocol: {self._protocol}')\n except Exception:\n log.info('connect: connection error')\n raise\n\n async def connectSSH(self):\n \"\"\"\n Async method used for connecting a device using SSH protocol\n \"\"\"\n log.info('connectSSH')\n generator = asyncssh.connect(self.ip, username=self.username,\n password=self.password, known_hosts=None, encryption_algs=[algs\n .decode('utf-8') for algs in asyncssh.encryption._enc_algs])\n try:\n self.conn = await asyncio.wait_for(generator, timeout=self.timeout)\n except asyncio.exceptions.TimeoutError as error:\n log.error(\n f\"connectSSH: connection failed: {self.ip} timeout: '{error}'\")\n raise asyncio.exceptions.TimeoutError(\n 'Connection failed: connection timed out.')\n except Exception as error:\n log.error(f\"connectSSH: connection failed: {self.ip} '{error}'\")\n raise\n log.info('connectSSH: connection success')\n self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type\n ='netscud')\n log.info('connectSSH: open_session success')\n data = ''\n prompt_not_found = True\n try:\n while prompt_not_found:\n log.info('connectSSH: beginning of the loop')\n data += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f\"connectSSH: data: '{str(data)}'\")\n log.info(\n f\"connectSSH: data: hex:'{data.encode('utf-8').hex()}'\")\n for prompt in self._connect_first_ending_prompt:\n if data.endswith(prompt):\n log.info(\n f\"connectSSH: first ending prompt found: '{prompt}'\"\n )\n prompt_not_found = False\n break\n log.info('connectSSH: end of loop')\n except Exception as error:\n log.error(\n f\"connectSSH: timeout while reading the prompt: {self.ip} '{error}'\"\n )\n raise\n log.info(f'connectSSH: end of prompt loop')\n data = self.remove_ansi_escape_sequence(data)\n self.prompt = self.find_prompt(str(data))\n log.info(f\"connectSSH: prompt found: '{self.prompt}'\")\n log.info(f\"connectSSH: prompt found size: '{len(self.prompt)}'\")\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def connectTelnet(self):\n \"\"\"\n Async method used for connecting a device using Telnet protocol\n \"\"\"\n log.info('connectTelnet')\n try:\n conn = asyncio.open_connection(self.ip, self.port)\n except Exception as error:\n log.error(\n f\"connectTelnet: preparation to the connection failed: '{error}'\"\n )\n raise\n log.info('connectTelnet: preparation to the connection success')\n try:\n self._reader, self._writer = await asyncio.wait_for(conn,\n timeout=self.timeout)\n except asyncio.TimeoutError:\n log.error('connectTelnet: connection: timeout')\n raise\n log.info('connectTelnet: connection success')\n prompt = self._telnet_connect_login\n prompt_password = self._telnet_connect_password\n use_login = True\n output = ''\n byte_data = b''\n while True:\n log.info(f'connectTelnet: read data for prompt')\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f'connectTelnet: byte_data: {byte_data}')\n output = str(byte_data)\n log.info(f'connectTelnet: output: {output}')\n if prompt in output:\n break\n elif prompt_password in output:\n use_login = False\n break\n log.info(f\"connectTelnet: login prompt: '{output}'\")\n if use_login:\n log.info('connectTelnet: sending login')\n try:\n await self.send_command(self.username, prompt_password)\n log.info('connectTelnet: login sent')\n except Exception:\n raise\n log.info('connectTelnet: sending password')\n try:\n output = await self.telnet_send_command_with_unexpected_pattern(\n self.password, self._connect_first_ending_prompt, self.\n _telnet_connect_authentication_fail_prompt)\n except Exception:\n raise\n log.info('connectTelnet: password sent')\n self.prompt = self.find_prompt(str(output))\n log.info(f\"connectTelnet: prompt found: '{self.prompt}'\")\n if self.enable_mode:\n log.info('connectTelnet: enable mode to be activated')\n try:\n await self.send_command(self.cmd_enable, prompt_password)\n log.info('connectTelnet: enable command sent')\n log.info('connectTelnet: sending enable password')\n await self.telnet_send_command_with_unexpected_pattern(self\n .enable_password, self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt)\n log.info('connectTelnet: enable password sent')\n except Exception:\n log.info('connectTelnet: enable password failure')\n raise\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def disconnect(self):\n \"\"\"\n Async method used to disconnect a device\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnect')\n if self._protocol == 'ssh':\n await self.disconnectSSH()\n elif self._protocol == 'telnet':\n await self.disconnectTelnet()\n else:\n raise Exception(f'Unsupported protocol: {self._protocol}')\n\n async def disconnectSSH(self):\n \"\"\"\n Async method used to disconnect a device in SSH\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectSSH')\n if self.conn:\n self.conn.close()\n self.conn = None\n\n async def disconnectTelnet(self):\n \"\"\"\n Async method used to disconnect a device in Telnet\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectTelnet')\n if self._writer:\n self._writer.close()\n self._writer = None\n\n async def send_command(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_command')\n if timeout is None:\n timeout = self.timeout\n if self._protocol == 'ssh':\n output = await self.send_commandSSH(cmd, pattern=pattern,\n timeout=timeout)\n elif self._protocol == 'telnet':\n output = await self.send_commandTelnet(cmd, pattern=pattern,\n timeout=timeout)\n else:\n raise Exception(\n f'send_command: unsupported protocol: {self._protocol}')\n return output\n\n async def send_commandSSH(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandSSH')\n if timeout is None:\n timeout = self.timeout\n log.info(f\"send_commandSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd + self._carriage_return_for_send_command)\n log.info('send_commandSSH: command sent')\n output = ''\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = self.remove_ansi_escape_sequence(output)\n output = output.replace('\\r', '')\n log.info(f\"send_commandSSH: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_commandSSH: raw output: '{output}'\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandSSH: cleaned output: '{output}'\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def send_commandTelnet(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandTelnet')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + '\\n'\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_commandTelnet: byte_data: '{byte_data}'\")\n output = str(byte_data)\n log.info(f\"send_commandTelnet: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_commandTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_commandTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_commandTelnet: raw output: '{output}'\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandTelnet: cleaned output: '{output}'\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def telnet_send_command_with_unexpected_pattern(self, cmd,\n pattern, error_pattern=None, timeout=None):\n \"\"\"\n Async method used to send command for Telnet connection to a device with possible unexpected patterns\n\n send_command can wait till time out if login and password are wrong. This method\n speed up the returned error message when authentication failed is identified.\n This method is limited to authentication whem password is required\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used\n to define a custom or unexpected prompt a the end of a string\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :param error_pattern: optional, a list of failed prompts found when the login and password are not correct\n :type error_pattern: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('telnet_send_command_with_unexpected_pattern')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + self._carriage_return_for_send_command\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n pattern_not_found = True\n try:\n while pattern_not_found:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'\"\n )\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'\"\n )\n output = str(byte_data)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: output: '{output}'\"\n )\n if pattern:\n for prompt in pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'\"\n )\n if prompt in output:\n pattern_not_found = False\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'\"\n )\n break\n if error_pattern and pattern_not_found:\n for bad_prompt in error_pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'\"\n )\n if bad_prompt in output:\n log.error(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n raise Exception(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n except asyncio.TimeoutError:\n await self.disconnect()\n log.error(\n 'telnet_send_command_with_unexpected_pattern: reading prompt: timeout'\n )\n raise\n except Exception as error:\n await self.disconnect()\n log.error(\n f'telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}'\n )\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n return output\n\n async def send_config_set(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_set')\n if timeout is None:\n timeout = self.timeout\n log.info('send_command')\n if self._protocol == 'ssh':\n output = await self.send_config_setSSH(cmds, timeout)\n elif self._protocol == 'telnet':\n output = await self.send_config_setTelnet(cmds, timeout)\n else:\n raise Exception(\n f'send_config_set: unsupported protocol: {self._protocol}')\n return output\n\n async def send_config_setSSH(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setSSH')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list'\n )\n return returned_output\n log.info('send_config_set: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: configuration mode entered')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command sent')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command to leave configuration mode sent'\n )\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def send_config_setTelnet(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setTelnet')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list'\n )\n return returned_output\n log.info('send_config_setTelnet: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: configuration mode entered')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: command sent')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info(\n 'send_config_setTelnet: command to leave configuration mode sent')\n output = ''\n byte_data = b''\n loop = 3\n try:\n while loop:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n await asyncio.sleep(0.5)\n if self.check_if_prompt_is_found(output):\n break\n loop -= 1\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def get_version(self):\n \"\"\"\n Asyn method used to get the version of the software of the device\n\n :return: Version of the software of the device\n :rtype: str\n \"\"\"\n log.info('get_version')\n version = ''\n output = await self.send_command(self.cmd_get_version)\n version = output.split('Version ')[1].split(',')[0]\n log.info(f'get_version: version: {version}')\n return version\n\n async def get_hostname(self):\n \"\"\"\n Asyn method used to get the name of the device\n\n :return: Name of the device\n :rtype: str\n \"\"\"\n log.info('get_hostname')\n output = await self.send_command(self.cmd_get_hostname)\n log.info(f\"get_hostname: output: '{output}'\")\n output = output.split()[0]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_model(self):\n \"\"\"\n Asyn method used to get the model of the device\n\n :return: Model of the device\n :rtype: str\n \"\"\"\n log.info('get_model')\n output = await self.send_command(self.cmd_get_model)\n log.info(f\"get_model: output: '{output}'\")\n output = output.split('\"')[3]\n log.info(f\"get_model: model found: '{output}'\")\n return output\n\n async def get_serial_number(self):\n \"\"\"\n Get serial number of the switch or the serial number of the first switch of a stack\n\n :return: Serial number of the device\n :rtype: str\n \"\"\"\n log.info('get_serial_number')\n output = await self.send_command(self.cmd_get_serial_number)\n log.info(f\"get_serial_number: output: '{output}'\")\n output = output.splitlines()[0].split()[-1]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_config(self, timeout=None):\n \"\"\"\n Asyn method used to get the configuration of the device\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: Configuration of the device\n :rtype: str\n \"\"\"\n log.info('get_config')\n if timeout is None:\n timeout = self.timeout\n output = await self.send_command(self.cmd_get_config, timeout=timeout)\n return output\n\n async def save_config(self):\n \"\"\"\n Asyn method used to save the current configuration on the device\n\n :return: Commands of the configuration saving process\n :rtype: str\n \"\"\"\n log.info('save_config')\n output = await self.send_command(self.cmd_save_config)\n return output\n", "step-2": "<mask token>\n\n\nclass NetworkDevice:\n <mask token>\n\n def __init__(self, **kwargs):\n log.info('__init__')\n self.ip = ''\n self.username = ''\n self.password = ''\n self.device_type = ''\n self.port = 22\n self.timeout = 10\n self._protocol = 'ssh'\n self.enable_mode = False\n self.enable_password = ''\n self.conn = None\n self._writer = None\n self._reader = None\n self.possible_prompts = []\n self._connect_first_ending_prompt = ['#', '>']\n self.list_of_possible_ending_prompts = ['(config-line)#',\n '(config-if)#', '(config)#', '>', '#']\n self._carriage_return_for_send_command = '\\n'\n self._send_command_error_in_returned_output = []\n self._telnet_connect_login = 'Username:'\n self._telnet_connect_password = 'Password:'\n self._telnet_connect_authentication_fail_prompt = [':', '%']\n self.cmd_enable = 'enable'\n self.cmd_disable_paging = 'terminal length 0'\n self.cmd_enter_config_mode = 'configure terminal'\n self.cmd_exit_config_mode = 'exit'\n self.cmd_get_version = 'show version'\n self.cmd_get_hostname = 'show version | include uptime'\n self.cmd_get_model = 'show inventory'\n self.cmd_get_serial_number = 'show inventory | i SN'\n self.cmd_get_config = 'show running-config'\n self.cmd_save_config = 'write memory'\n self.cmd_get_interfaces = [\n 'interface ethernet print terse without-paging',\n 'foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}'\n , 'interface bridge port print terse without-paging']\n self.cmd_set_interface = ['interface ethernet enable <INTERFACE>',\n 'interface ethernet disable <INTERFACE>',\n 'interface ethernet comment <INTERFACE> \"<COMMENT>\"',\n 'interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>',\n 'interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]'\n ]\n self.cmd_get_mac_address_table = (\n 'interface bridge host print without-paging')\n self.cmd_get_arp = 'ip arp print terse without-paging'\n self.cmd_get_lldp_neighbors = 'ip neighbor print terse without-paging'\n self.cmd_get_vlans = 'interface bridge vlan print terse without-paging'\n self.cmd_add_vlan = (\n 'interface bridge vlan add vlan-ids=<VLAN> comment=\"<VLAN_NAME>\" bridge=<BRIDGE>'\n )\n self.cmd_remove_vlan = (\n 'interface bridge vlan remove [find vlan-ids=<VLAN>]')\n self.cmd_add_interface_to_vlan = ['interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_remove_interface_from_vlan = [\n 'interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_get_routing_table = 'ip route print without-paging terse'\n self.cmd_get_interfaces_ip = 'ip address print terse without-paging'\n self.cmd_add_static_route = (\n 'ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>'\n )\n self.cmd_remove_static_route = (\n 'ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]')\n log.debug('__init__: kwargs: ' + str(kwargs))\n if 'ip' in kwargs:\n self.ip = kwargs['ip']\n log.info('__init__: ip found: ' + str(self.ip))\n if 'username' in kwargs:\n self.username = kwargs['username']\n log.info('__init__: username found: ' + str(self.username))\n if 'password' in kwargs:\n self.password = kwargs['password']\n log.debug('__init__: password found: ' + str(self.password))\n if 'device_type' in kwargs:\n self.device_type = kwargs['device_type']\n log.info('__init__: device_type found: ' + str(self.device_type))\n if 'timeout' in kwargs:\n self.timeout = kwargs['timeout']\n log.info('__init__: timeout found: ' + str(self.timeout))\n if 'protocol' in kwargs:\n self._protocol = kwargs['protocol'].lower()\n log.info('__init__: protocol found: ' + str(self._protocol))\n if self._protocol.lower() == 'telnet':\n self.port = 23\n if 'port' in kwargs:\n self.port = kwargs['port']\n log.info('__init__: port found: ' + str(self.port))\n if 'enable_mode' in kwargs:\n self.enable_mode = kwargs['enable_mode']\n log.info('__init__: enable_mode found: ' + str(self.enable_mode))\n if 'enable_password' in kwargs:\n self.enable_password = kwargs['enable_password']\n log.info('__init__: enable_password found: ' + str(self.\n enable_password))\n\n async def __aenter__(self):\n \"\"\"\n Context manager opening connection\n \"\"\"\n try:\n await self.connect()\n except Exception:\n await self.disconnect()\n raise\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback):\n \"\"\"\n Context manager closing connection\n \"\"\"\n await self.disconnect()\n\n def find_prompt(self, text):\n \"\"\"\n Method used to find a prompt inside an output string\n\n This method is used during the first communication with the device.\n First it find the prompt then caculate the different forms the prompt\n can take. This will be useful later on while finding prompt in other\n output stream (read).\n\n :param text: data with a prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt = text.split('\\n')[-1]\n prompt = text.split('\\r')[-1]\n log.info(f\"find_prompt: prompt: '{prompt}'\")\n self.possible_prompts = self.get_possible_prompts(prompt)\n return prompt\n\n def get_possible_prompts(self, prompt):\n \"\"\"\n Method used to check if a prompt has one of the expected endings then\n create a list with all possible prompts for the device\n\n :param prompt: a prompt with a possible ending prompt (eg. \"switch#\")\n :type prompt: str\n\n :return: the list of prompts\n :rtype: list\n \"\"\"\n list_of_prompts = []\n list_of_possible_ending_prompts = self.list_of_possible_ending_prompts\n my_prompt = prompt\n for ending in list_of_possible_ending_prompts:\n if my_prompt.endswith(ending):\n my_prompt = my_prompt[:-len(ending)]\n break\n log.info(f\"get_possible_prompts: prompt found: '{my_prompt}'\")\n log.info(f\"get_possible_prompts: prompt found size: '{len(my_prompt)}'\"\n )\n for ending in list_of_possible_ending_prompts:\n list_of_prompts.append(my_prompt + ending)\n log.info(\n f'get_possible_prompts: list of possible prompts: {list_of_prompts}'\n )\n return list_of_prompts\n\n def check_if_prompt_is_found(self, text):\n \"\"\"\n Method used to check if a prompt is detected inside a string\n\n :param text: a string with prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt_found = False\n for prompt in self.possible_prompts:\n log.info(f\"check_if_prompt_is_found: prompt: '{prompt}'\")\n if prompt in text:\n prompt_found = True\n log.info(f\"check_if_prompt_is_found: prompt found: '{prompt}'\")\n break\n return prompt_found\n\n def remove_command_in_output(self, text, cmd):\n \"\"\"\n Method removing the command at the beginning of a string\n\n After sending commands an \"echo\" of the command sent\n is display in the output string. This method removes it.\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :param cmd: the command previously sent\n :type cmd: str\n\n :return: the output string without the command\n :rtype: str\n \"\"\"\n log.info(f\"remove_command_in_output: cmd = '{cmd}'\")\n log.info(\n f\"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'\")\n output = text.split(cmd + '\\n')[-1]\n log.info(f\"remove_command_in_output: output = '{output}'\")\n return output\n\n def remove_starting_carriage_return_in_output(self, text):\n \"\"\"\n Method removing the carriage return at the beginning of a string\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :return: the output string without the starting carriage return\n :rtype: str\n \"\"\"\n log.info('remove_starting_carriage_return_in_output')\n output = text.lstrip('\\r\\n\\r')\n log.info(\n f\"remove_starting_carriage_return_in_output: output = '{output}'\")\n return output\n\n def remove_ending_prompt_in_output(self, text):\n \"\"\"\n Method removing the prompt at the end of a string\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n log.info('remove_ending_prompt_in_output')\n for prompt in self.possible_prompts:\n log.info(f\"remove_ending_prompt_in_output: prompt: '{prompt}'\")\n if prompt in text:\n text = text[:-len(prompt)]\n text = text.rstrip('\\r\\n')\n break\n log.info(\n f\"remove_ending_prompt_in_output: text without prompt:\\n'{text}'\")\n return text\n\n def check_error_output(self, output):\n \"\"\"\n Check if an error is returned by the device (\"% Unrecognized command\", \"% Ambiguous command\", etc.)\n\n If an error is found, then an exception is raised\n \"\"\"\n log.info('check_error_output')\n if output:\n log.info('check_error_output: output has some data')\n for element in self._send_command_error_in_returned_output:\n log.info(f'check_error_output: element: {element}')\n log.info(f'check_error_output: output[0]: {output[0]}')\n if output.startswith(element):\n raise Exception(output)\n\n def remove_ansi_escape_sequence(self, text):\n \"\"\"\n Method removing ANSI escape sequence from a string\n Just CSI sequences are removed\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n output = ''\n esc_found = 0\n for i in text:\n if esc_found == 0:\n if i == '\\x1b':\n log.info('Esc!')\n esc_found = 1\n else:\n output += i\n elif esc_found == 1:\n if i == '[':\n log.info('CSI sequence')\n esc_found = 2\n else:\n output += '\\x1b' + i\n esc_found = 0\n elif i >= 'a' and i <= 'z' or i >= 'A' and i <= 'Z':\n log.info('End of escape sequence')\n esc_found = 0\n return output\n\n async def disable_paging(self):\n \"\"\"\n Async method disabling paging on a device\n\n Use the \"cmd_disable_paging\" attribute\n \"\"\"\n log.info('disable_paging')\n await self.send_command(self.cmd_disable_paging)\n\n async def connect(self):\n \"\"\"\n Async method used for connecting a device\n\n Currently supported: SSH and Telnet\n \"\"\"\n log.info('connect')\n try:\n if self._protocol == 'ssh':\n await self.connectSSH()\n elif self._protocol == 'telnet':\n await self.connectTelnet()\n else:\n raise Exception(\n f'connect: unsupported protocol: {self._protocol}')\n except Exception:\n log.info('connect: connection error')\n raise\n\n async def connectSSH(self):\n \"\"\"\n Async method used for connecting a device using SSH protocol\n \"\"\"\n log.info('connectSSH')\n generator = asyncssh.connect(self.ip, username=self.username,\n password=self.password, known_hosts=None, encryption_algs=[algs\n .decode('utf-8') for algs in asyncssh.encryption._enc_algs])\n try:\n self.conn = await asyncio.wait_for(generator, timeout=self.timeout)\n except asyncio.exceptions.TimeoutError as error:\n log.error(\n f\"connectSSH: connection failed: {self.ip} timeout: '{error}'\")\n raise asyncio.exceptions.TimeoutError(\n 'Connection failed: connection timed out.')\n except Exception as error:\n log.error(f\"connectSSH: connection failed: {self.ip} '{error}'\")\n raise\n log.info('connectSSH: connection success')\n self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type\n ='netscud')\n log.info('connectSSH: open_session success')\n data = ''\n prompt_not_found = True\n try:\n while prompt_not_found:\n log.info('connectSSH: beginning of the loop')\n data += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f\"connectSSH: data: '{str(data)}'\")\n log.info(\n f\"connectSSH: data: hex:'{data.encode('utf-8').hex()}'\")\n for prompt in self._connect_first_ending_prompt:\n if data.endswith(prompt):\n log.info(\n f\"connectSSH: first ending prompt found: '{prompt}'\"\n )\n prompt_not_found = False\n break\n log.info('connectSSH: end of loop')\n except Exception as error:\n log.error(\n f\"connectSSH: timeout while reading the prompt: {self.ip} '{error}'\"\n )\n raise\n log.info(f'connectSSH: end of prompt loop')\n data = self.remove_ansi_escape_sequence(data)\n self.prompt = self.find_prompt(str(data))\n log.info(f\"connectSSH: prompt found: '{self.prompt}'\")\n log.info(f\"connectSSH: prompt found size: '{len(self.prompt)}'\")\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def connectTelnet(self):\n \"\"\"\n Async method used for connecting a device using Telnet protocol\n \"\"\"\n log.info('connectTelnet')\n try:\n conn = asyncio.open_connection(self.ip, self.port)\n except Exception as error:\n log.error(\n f\"connectTelnet: preparation to the connection failed: '{error}'\"\n )\n raise\n log.info('connectTelnet: preparation to the connection success')\n try:\n self._reader, self._writer = await asyncio.wait_for(conn,\n timeout=self.timeout)\n except asyncio.TimeoutError:\n log.error('connectTelnet: connection: timeout')\n raise\n log.info('connectTelnet: connection success')\n prompt = self._telnet_connect_login\n prompt_password = self._telnet_connect_password\n use_login = True\n output = ''\n byte_data = b''\n while True:\n log.info(f'connectTelnet: read data for prompt')\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f'connectTelnet: byte_data: {byte_data}')\n output = str(byte_data)\n log.info(f'connectTelnet: output: {output}')\n if prompt in output:\n break\n elif prompt_password in output:\n use_login = False\n break\n log.info(f\"connectTelnet: login prompt: '{output}'\")\n if use_login:\n log.info('connectTelnet: sending login')\n try:\n await self.send_command(self.username, prompt_password)\n log.info('connectTelnet: login sent')\n except Exception:\n raise\n log.info('connectTelnet: sending password')\n try:\n output = await self.telnet_send_command_with_unexpected_pattern(\n self.password, self._connect_first_ending_prompt, self.\n _telnet_connect_authentication_fail_prompt)\n except Exception:\n raise\n log.info('connectTelnet: password sent')\n self.prompt = self.find_prompt(str(output))\n log.info(f\"connectTelnet: prompt found: '{self.prompt}'\")\n if self.enable_mode:\n log.info('connectTelnet: enable mode to be activated')\n try:\n await self.send_command(self.cmd_enable, prompt_password)\n log.info('connectTelnet: enable command sent')\n log.info('connectTelnet: sending enable password')\n await self.telnet_send_command_with_unexpected_pattern(self\n .enable_password, self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt)\n log.info('connectTelnet: enable password sent')\n except Exception:\n log.info('connectTelnet: enable password failure')\n raise\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def disconnect(self):\n \"\"\"\n Async method used to disconnect a device\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnect')\n if self._protocol == 'ssh':\n await self.disconnectSSH()\n elif self._protocol == 'telnet':\n await self.disconnectTelnet()\n else:\n raise Exception(f'Unsupported protocol: {self._protocol}')\n\n async def disconnectSSH(self):\n \"\"\"\n Async method used to disconnect a device in SSH\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectSSH')\n if self.conn:\n self.conn.close()\n self.conn = None\n\n async def disconnectTelnet(self):\n \"\"\"\n Async method used to disconnect a device in Telnet\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectTelnet')\n if self._writer:\n self._writer.close()\n self._writer = None\n\n async def send_command(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_command')\n if timeout is None:\n timeout = self.timeout\n if self._protocol == 'ssh':\n output = await self.send_commandSSH(cmd, pattern=pattern,\n timeout=timeout)\n elif self._protocol == 'telnet':\n output = await self.send_commandTelnet(cmd, pattern=pattern,\n timeout=timeout)\n else:\n raise Exception(\n f'send_command: unsupported protocol: {self._protocol}')\n return output\n\n async def send_commandSSH(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandSSH')\n if timeout is None:\n timeout = self.timeout\n log.info(f\"send_commandSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd + self._carriage_return_for_send_command)\n log.info('send_commandSSH: command sent')\n output = ''\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = self.remove_ansi_escape_sequence(output)\n output = output.replace('\\r', '')\n log.info(f\"send_commandSSH: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_commandSSH: raw output: '{output}'\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandSSH: cleaned output: '{output}'\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def send_commandTelnet(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandTelnet')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + '\\n'\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_commandTelnet: byte_data: '{byte_data}'\")\n output = str(byte_data)\n log.info(f\"send_commandTelnet: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_commandTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_commandTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_commandTelnet: raw output: '{output}'\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandTelnet: cleaned output: '{output}'\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def telnet_send_command_with_unexpected_pattern(self, cmd,\n pattern, error_pattern=None, timeout=None):\n \"\"\"\n Async method used to send command for Telnet connection to a device with possible unexpected patterns\n\n send_command can wait till time out if login and password are wrong. This method\n speed up the returned error message when authentication failed is identified.\n This method is limited to authentication whem password is required\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used\n to define a custom or unexpected prompt a the end of a string\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :param error_pattern: optional, a list of failed prompts found when the login and password are not correct\n :type error_pattern: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('telnet_send_command_with_unexpected_pattern')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + self._carriage_return_for_send_command\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n pattern_not_found = True\n try:\n while pattern_not_found:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'\"\n )\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'\"\n )\n output = str(byte_data)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: output: '{output}'\"\n )\n if pattern:\n for prompt in pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'\"\n )\n if prompt in output:\n pattern_not_found = False\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'\"\n )\n break\n if error_pattern and pattern_not_found:\n for bad_prompt in error_pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'\"\n )\n if bad_prompt in output:\n log.error(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n raise Exception(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n except asyncio.TimeoutError:\n await self.disconnect()\n log.error(\n 'telnet_send_command_with_unexpected_pattern: reading prompt: timeout'\n )\n raise\n except Exception as error:\n await self.disconnect()\n log.error(\n f'telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}'\n )\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n return output\n\n async def send_config_set(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_set')\n if timeout is None:\n timeout = self.timeout\n log.info('send_command')\n if self._protocol == 'ssh':\n output = await self.send_config_setSSH(cmds, timeout)\n elif self._protocol == 'telnet':\n output = await self.send_config_setTelnet(cmds, timeout)\n else:\n raise Exception(\n f'send_config_set: unsupported protocol: {self._protocol}')\n return output\n\n async def send_config_setSSH(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setSSH')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list'\n )\n return returned_output\n log.info('send_config_set: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: configuration mode entered')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command sent')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command to leave configuration mode sent'\n )\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def send_config_setTelnet(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setTelnet')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list'\n )\n return returned_output\n log.info('send_config_setTelnet: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: configuration mode entered')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: command sent')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info(\n 'send_config_setTelnet: command to leave configuration mode sent')\n output = ''\n byte_data = b''\n loop = 3\n try:\n while loop:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n await asyncio.sleep(0.5)\n if self.check_if_prompt_is_found(output):\n break\n loop -= 1\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def get_version(self):\n \"\"\"\n Asyn method used to get the version of the software of the device\n\n :return: Version of the software of the device\n :rtype: str\n \"\"\"\n log.info('get_version')\n version = ''\n output = await self.send_command(self.cmd_get_version)\n version = output.split('Version ')[1].split(',')[0]\n log.info(f'get_version: version: {version}')\n return version\n\n async def get_hostname(self):\n \"\"\"\n Asyn method used to get the name of the device\n\n :return: Name of the device\n :rtype: str\n \"\"\"\n log.info('get_hostname')\n output = await self.send_command(self.cmd_get_hostname)\n log.info(f\"get_hostname: output: '{output}'\")\n output = output.split()[0]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_model(self):\n \"\"\"\n Asyn method used to get the model of the device\n\n :return: Model of the device\n :rtype: str\n \"\"\"\n log.info('get_model')\n output = await self.send_command(self.cmd_get_model)\n log.info(f\"get_model: output: '{output}'\")\n output = output.split('\"')[3]\n log.info(f\"get_model: model found: '{output}'\")\n return output\n\n async def get_serial_number(self):\n \"\"\"\n Get serial number of the switch or the serial number of the first switch of a stack\n\n :return: Serial number of the device\n :rtype: str\n \"\"\"\n log.info('get_serial_number')\n output = await self.send_command(self.cmd_get_serial_number)\n log.info(f\"get_serial_number: output: '{output}'\")\n output = output.splitlines()[0].split()[-1]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_config(self, timeout=None):\n \"\"\"\n Asyn method used to get the configuration of the device\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: Configuration of the device\n :rtype: str\n \"\"\"\n log.info('get_config')\n if timeout is None:\n timeout = self.timeout\n output = await self.send_command(self.cmd_get_config, timeout=timeout)\n return output\n\n async def save_config(self):\n \"\"\"\n Asyn method used to save the current configuration on the device\n\n :return: Commands of the configuration saving process\n :rtype: str\n \"\"\"\n log.info('save_config')\n output = await self.send_command(self.cmd_save_config)\n return output\n", "step-3": "<mask token>\nlogging.basicConfig(level=logging.DEBUG)\nasyncssh.set_debug_level(2)\n<mask token>\n\n\nclass NetworkDevice:\n \"\"\"\n Base class for network object\n\n\n :param ip: IP address of a device\n :type ip: str\n\n :param username: Username used to connect to a device\n :type username: str\n\n :param password: Password used to connect to a device\n :type password: str\n\n :param device_type: Type of device used\n :type device_type: str\n\n :param port: TCP port used to connect a device. Default value is \"22\" for SSH\n :type port: int, optional\n\n :param timeout: TCP port used to connect a device. Default value is 10 seconds\n :type timeout: int, optional\n\n :param _protocol: Protocol used to connect a device. \"ssh\" or \"telnet\" are possible options. Default value is \"ssh\"\n :type _protocol: str, optional\n\n :param enable_mode: Enable mode for devices requiring it. Default value is \"False\"\n :type enable_mode: bool, optional\n\n :param enable_password: Enable password used for enable mode.\n :type enable_password: str, optional\n\n :param conn: Variable used for the management of the SSH connection\n :type conn: SSHClientConnection object\n\n :param _writer: Variable used for the management of the Telnet connection and writing channel\n :type _writer: StreamWriter object\n\n :param _reader: Variable used for the management of the Telnet reading channel\n :type _reader: StreamReader object\n\n :param possible_prompts: Used by the connect method to list all possible prompts of the device\n :type possible_prompts: list\n\n :param _connect_first_ending_prompt: Default possible ending prompts. Used only the time after login and password to discover the prompt\n :type _connect_first_ending_prompt: list\n\n :param list_of_possible_ending_prompts: Different strings at the end of a prompt the device can get. Used for detecting the prompt returned in sent commands\n :type list_of_possible_ending_prompts: list\n\n :param _telnet_connect_login: Login prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_login: str\n\n :param _telnet_connect_password: Password prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_password: list\n\n :param _telnet_connect_authentication_fail_prompt: Known failing messages or prompts when an authentication has failed. Used to get an answer faster than timeout events\n :type _telnet_connect_authentication_fail_prompt: list\n\n :param cmd_enable: Enable command for entering into enable mode\n :type cmd_enable: str\n\n :param cmd_disable_paging: Command used to disable paging on a device. That command is run at connection time\n :type cmd_disable_paging: str\n\n :param cmd_enter_config_mode: Command used to enter into a configuration mode on a device when this device support that feature.\n :type cmd_enter_config_mode: str\n\n :param cmd_exit_config_mode: Command used to leave a configuration mode on a device when this device support that feature.\n :type cmd_exit_config_mode: str\n\n :param cmd_get_version: API command used to get the software version of a device\n :type cmd_get_version: str\n\n :param cmd_get_hostname: API command used to get the hostname of a device\n :type cmd_get_hostname: str\n\n :param cmd_get_model: API command used to get the model of a device\n :type cmd_get_model: str\n\n :param cmd_get_serial_number: API command used to get the serial number of a device\n :type cmd_get_serial_number: str\n\n :param cmd_get_config: API command used to get the running configuration of a device\n :type cmd_get_config: str\n\n :param cmd_save_config: API command used to save the running configuration on the device\n :type cmd_save_config: str\n \"\"\"\n\n def __init__(self, **kwargs):\n log.info('__init__')\n self.ip = ''\n self.username = ''\n self.password = ''\n self.device_type = ''\n self.port = 22\n self.timeout = 10\n self._protocol = 'ssh'\n self.enable_mode = False\n self.enable_password = ''\n self.conn = None\n self._writer = None\n self._reader = None\n self.possible_prompts = []\n self._connect_first_ending_prompt = ['#', '>']\n self.list_of_possible_ending_prompts = ['(config-line)#',\n '(config-if)#', '(config)#', '>', '#']\n self._carriage_return_for_send_command = '\\n'\n self._send_command_error_in_returned_output = []\n self._telnet_connect_login = 'Username:'\n self._telnet_connect_password = 'Password:'\n self._telnet_connect_authentication_fail_prompt = [':', '%']\n self.cmd_enable = 'enable'\n self.cmd_disable_paging = 'terminal length 0'\n self.cmd_enter_config_mode = 'configure terminal'\n self.cmd_exit_config_mode = 'exit'\n self.cmd_get_version = 'show version'\n self.cmd_get_hostname = 'show version | include uptime'\n self.cmd_get_model = 'show inventory'\n self.cmd_get_serial_number = 'show inventory | i SN'\n self.cmd_get_config = 'show running-config'\n self.cmd_save_config = 'write memory'\n self.cmd_get_interfaces = [\n 'interface ethernet print terse without-paging',\n 'foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}'\n , 'interface bridge port print terse without-paging']\n self.cmd_set_interface = ['interface ethernet enable <INTERFACE>',\n 'interface ethernet disable <INTERFACE>',\n 'interface ethernet comment <INTERFACE> \"<COMMENT>\"',\n 'interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>',\n 'interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]'\n ]\n self.cmd_get_mac_address_table = (\n 'interface bridge host print without-paging')\n self.cmd_get_arp = 'ip arp print terse without-paging'\n self.cmd_get_lldp_neighbors = 'ip neighbor print terse without-paging'\n self.cmd_get_vlans = 'interface bridge vlan print terse without-paging'\n self.cmd_add_vlan = (\n 'interface bridge vlan add vlan-ids=<VLAN> comment=\"<VLAN_NAME>\" bridge=<BRIDGE>'\n )\n self.cmd_remove_vlan = (\n 'interface bridge vlan remove [find vlan-ids=<VLAN>]')\n self.cmd_add_interface_to_vlan = ['interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_remove_interface_from_vlan = [\n 'interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_get_routing_table = 'ip route print without-paging terse'\n self.cmd_get_interfaces_ip = 'ip address print terse without-paging'\n self.cmd_add_static_route = (\n 'ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>'\n )\n self.cmd_remove_static_route = (\n 'ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]')\n log.debug('__init__: kwargs: ' + str(kwargs))\n if 'ip' in kwargs:\n self.ip = kwargs['ip']\n log.info('__init__: ip found: ' + str(self.ip))\n if 'username' in kwargs:\n self.username = kwargs['username']\n log.info('__init__: username found: ' + str(self.username))\n if 'password' in kwargs:\n self.password = kwargs['password']\n log.debug('__init__: password found: ' + str(self.password))\n if 'device_type' in kwargs:\n self.device_type = kwargs['device_type']\n log.info('__init__: device_type found: ' + str(self.device_type))\n if 'timeout' in kwargs:\n self.timeout = kwargs['timeout']\n log.info('__init__: timeout found: ' + str(self.timeout))\n if 'protocol' in kwargs:\n self._protocol = kwargs['protocol'].lower()\n log.info('__init__: protocol found: ' + str(self._protocol))\n if self._protocol.lower() == 'telnet':\n self.port = 23\n if 'port' in kwargs:\n self.port = kwargs['port']\n log.info('__init__: port found: ' + str(self.port))\n if 'enable_mode' in kwargs:\n self.enable_mode = kwargs['enable_mode']\n log.info('__init__: enable_mode found: ' + str(self.enable_mode))\n if 'enable_password' in kwargs:\n self.enable_password = kwargs['enable_password']\n log.info('__init__: enable_password found: ' + str(self.\n enable_password))\n\n async def __aenter__(self):\n \"\"\"\n Context manager opening connection\n \"\"\"\n try:\n await self.connect()\n except Exception:\n await self.disconnect()\n raise\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback):\n \"\"\"\n Context manager closing connection\n \"\"\"\n await self.disconnect()\n\n def find_prompt(self, text):\n \"\"\"\n Method used to find a prompt inside an output string\n\n This method is used during the first communication with the device.\n First it find the prompt then caculate the different forms the prompt\n can take. This will be useful later on while finding prompt in other\n output stream (read).\n\n :param text: data with a prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt = text.split('\\n')[-1]\n prompt = text.split('\\r')[-1]\n log.info(f\"find_prompt: prompt: '{prompt}'\")\n self.possible_prompts = self.get_possible_prompts(prompt)\n return prompt\n\n def get_possible_prompts(self, prompt):\n \"\"\"\n Method used to check if a prompt has one of the expected endings then\n create a list with all possible prompts for the device\n\n :param prompt: a prompt with a possible ending prompt (eg. \"switch#\")\n :type prompt: str\n\n :return: the list of prompts\n :rtype: list\n \"\"\"\n list_of_prompts = []\n list_of_possible_ending_prompts = self.list_of_possible_ending_prompts\n my_prompt = prompt\n for ending in list_of_possible_ending_prompts:\n if my_prompt.endswith(ending):\n my_prompt = my_prompt[:-len(ending)]\n break\n log.info(f\"get_possible_prompts: prompt found: '{my_prompt}'\")\n log.info(f\"get_possible_prompts: prompt found size: '{len(my_prompt)}'\"\n )\n for ending in list_of_possible_ending_prompts:\n list_of_prompts.append(my_prompt + ending)\n log.info(\n f'get_possible_prompts: list of possible prompts: {list_of_prompts}'\n )\n return list_of_prompts\n\n def check_if_prompt_is_found(self, text):\n \"\"\"\n Method used to check if a prompt is detected inside a string\n\n :param text: a string with prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt_found = False\n for prompt in self.possible_prompts:\n log.info(f\"check_if_prompt_is_found: prompt: '{prompt}'\")\n if prompt in text:\n prompt_found = True\n log.info(f\"check_if_prompt_is_found: prompt found: '{prompt}'\")\n break\n return prompt_found\n\n def remove_command_in_output(self, text, cmd):\n \"\"\"\n Method removing the command at the beginning of a string\n\n After sending commands an \"echo\" of the command sent\n is display in the output string. This method removes it.\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :param cmd: the command previously sent\n :type cmd: str\n\n :return: the output string without the command\n :rtype: str\n \"\"\"\n log.info(f\"remove_command_in_output: cmd = '{cmd}'\")\n log.info(\n f\"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'\")\n output = text.split(cmd + '\\n')[-1]\n log.info(f\"remove_command_in_output: output = '{output}'\")\n return output\n\n def remove_starting_carriage_return_in_output(self, text):\n \"\"\"\n Method removing the carriage return at the beginning of a string\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :return: the output string without the starting carriage return\n :rtype: str\n \"\"\"\n log.info('remove_starting_carriage_return_in_output')\n output = text.lstrip('\\r\\n\\r')\n log.info(\n f\"remove_starting_carriage_return_in_output: output = '{output}'\")\n return output\n\n def remove_ending_prompt_in_output(self, text):\n \"\"\"\n Method removing the prompt at the end of a string\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n log.info('remove_ending_prompt_in_output')\n for prompt in self.possible_prompts:\n log.info(f\"remove_ending_prompt_in_output: prompt: '{prompt}'\")\n if prompt in text:\n text = text[:-len(prompt)]\n text = text.rstrip('\\r\\n')\n break\n log.info(\n f\"remove_ending_prompt_in_output: text without prompt:\\n'{text}'\")\n return text\n\n def check_error_output(self, output):\n \"\"\"\n Check if an error is returned by the device (\"% Unrecognized command\", \"% Ambiguous command\", etc.)\n\n If an error is found, then an exception is raised\n \"\"\"\n log.info('check_error_output')\n if output:\n log.info('check_error_output: output has some data')\n for element in self._send_command_error_in_returned_output:\n log.info(f'check_error_output: element: {element}')\n log.info(f'check_error_output: output[0]: {output[0]}')\n if output.startswith(element):\n raise Exception(output)\n\n def remove_ansi_escape_sequence(self, text):\n \"\"\"\n Method removing ANSI escape sequence from a string\n Just CSI sequences are removed\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n output = ''\n esc_found = 0\n for i in text:\n if esc_found == 0:\n if i == '\\x1b':\n log.info('Esc!')\n esc_found = 1\n else:\n output += i\n elif esc_found == 1:\n if i == '[':\n log.info('CSI sequence')\n esc_found = 2\n else:\n output += '\\x1b' + i\n esc_found = 0\n elif i >= 'a' and i <= 'z' or i >= 'A' and i <= 'Z':\n log.info('End of escape sequence')\n esc_found = 0\n return output\n\n async def disable_paging(self):\n \"\"\"\n Async method disabling paging on a device\n\n Use the \"cmd_disable_paging\" attribute\n \"\"\"\n log.info('disable_paging')\n await self.send_command(self.cmd_disable_paging)\n\n async def connect(self):\n \"\"\"\n Async method used for connecting a device\n\n Currently supported: SSH and Telnet\n \"\"\"\n log.info('connect')\n try:\n if self._protocol == 'ssh':\n await self.connectSSH()\n elif self._protocol == 'telnet':\n await self.connectTelnet()\n else:\n raise Exception(\n f'connect: unsupported protocol: {self._protocol}')\n except Exception:\n log.info('connect: connection error')\n raise\n\n async def connectSSH(self):\n \"\"\"\n Async method used for connecting a device using SSH protocol\n \"\"\"\n log.info('connectSSH')\n generator = asyncssh.connect(self.ip, username=self.username,\n password=self.password, known_hosts=None, encryption_algs=[algs\n .decode('utf-8') for algs in asyncssh.encryption._enc_algs])\n try:\n self.conn = await asyncio.wait_for(generator, timeout=self.timeout)\n except asyncio.exceptions.TimeoutError as error:\n log.error(\n f\"connectSSH: connection failed: {self.ip} timeout: '{error}'\")\n raise asyncio.exceptions.TimeoutError(\n 'Connection failed: connection timed out.')\n except Exception as error:\n log.error(f\"connectSSH: connection failed: {self.ip} '{error}'\")\n raise\n log.info('connectSSH: connection success')\n self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type\n ='netscud')\n log.info('connectSSH: open_session success')\n data = ''\n prompt_not_found = True\n try:\n while prompt_not_found:\n log.info('connectSSH: beginning of the loop')\n data += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f\"connectSSH: data: '{str(data)}'\")\n log.info(\n f\"connectSSH: data: hex:'{data.encode('utf-8').hex()}'\")\n for prompt in self._connect_first_ending_prompt:\n if data.endswith(prompt):\n log.info(\n f\"connectSSH: first ending prompt found: '{prompt}'\"\n )\n prompt_not_found = False\n break\n log.info('connectSSH: end of loop')\n except Exception as error:\n log.error(\n f\"connectSSH: timeout while reading the prompt: {self.ip} '{error}'\"\n )\n raise\n log.info(f'connectSSH: end of prompt loop')\n data = self.remove_ansi_escape_sequence(data)\n self.prompt = self.find_prompt(str(data))\n log.info(f\"connectSSH: prompt found: '{self.prompt}'\")\n log.info(f\"connectSSH: prompt found size: '{len(self.prompt)}'\")\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def connectTelnet(self):\n \"\"\"\n Async method used for connecting a device using Telnet protocol\n \"\"\"\n log.info('connectTelnet')\n try:\n conn = asyncio.open_connection(self.ip, self.port)\n except Exception as error:\n log.error(\n f\"connectTelnet: preparation to the connection failed: '{error}'\"\n )\n raise\n log.info('connectTelnet: preparation to the connection success')\n try:\n self._reader, self._writer = await asyncio.wait_for(conn,\n timeout=self.timeout)\n except asyncio.TimeoutError:\n log.error('connectTelnet: connection: timeout')\n raise\n log.info('connectTelnet: connection success')\n prompt = self._telnet_connect_login\n prompt_password = self._telnet_connect_password\n use_login = True\n output = ''\n byte_data = b''\n while True:\n log.info(f'connectTelnet: read data for prompt')\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f'connectTelnet: byte_data: {byte_data}')\n output = str(byte_data)\n log.info(f'connectTelnet: output: {output}')\n if prompt in output:\n break\n elif prompt_password in output:\n use_login = False\n break\n log.info(f\"connectTelnet: login prompt: '{output}'\")\n if use_login:\n log.info('connectTelnet: sending login')\n try:\n await self.send_command(self.username, prompt_password)\n log.info('connectTelnet: login sent')\n except Exception:\n raise\n log.info('connectTelnet: sending password')\n try:\n output = await self.telnet_send_command_with_unexpected_pattern(\n self.password, self._connect_first_ending_prompt, self.\n _telnet_connect_authentication_fail_prompt)\n except Exception:\n raise\n log.info('connectTelnet: password sent')\n self.prompt = self.find_prompt(str(output))\n log.info(f\"connectTelnet: prompt found: '{self.prompt}'\")\n if self.enable_mode:\n log.info('connectTelnet: enable mode to be activated')\n try:\n await self.send_command(self.cmd_enable, prompt_password)\n log.info('connectTelnet: enable command sent')\n log.info('connectTelnet: sending enable password')\n await self.telnet_send_command_with_unexpected_pattern(self\n .enable_password, self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt)\n log.info('connectTelnet: enable password sent')\n except Exception:\n log.info('connectTelnet: enable password failure')\n raise\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def disconnect(self):\n \"\"\"\n Async method used to disconnect a device\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnect')\n if self._protocol == 'ssh':\n await self.disconnectSSH()\n elif self._protocol == 'telnet':\n await self.disconnectTelnet()\n else:\n raise Exception(f'Unsupported protocol: {self._protocol}')\n\n async def disconnectSSH(self):\n \"\"\"\n Async method used to disconnect a device in SSH\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectSSH')\n if self.conn:\n self.conn.close()\n self.conn = None\n\n async def disconnectTelnet(self):\n \"\"\"\n Async method used to disconnect a device in Telnet\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectTelnet')\n if self._writer:\n self._writer.close()\n self._writer = None\n\n async def send_command(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_command')\n if timeout is None:\n timeout = self.timeout\n if self._protocol == 'ssh':\n output = await self.send_commandSSH(cmd, pattern=pattern,\n timeout=timeout)\n elif self._protocol == 'telnet':\n output = await self.send_commandTelnet(cmd, pattern=pattern,\n timeout=timeout)\n else:\n raise Exception(\n f'send_command: unsupported protocol: {self._protocol}')\n return output\n\n async def send_commandSSH(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandSSH')\n if timeout is None:\n timeout = self.timeout\n log.info(f\"send_commandSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd + self._carriage_return_for_send_command)\n log.info('send_commandSSH: command sent')\n output = ''\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = self.remove_ansi_escape_sequence(output)\n output = output.replace('\\r', '')\n log.info(f\"send_commandSSH: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_commandSSH: raw output: '{output}'\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandSSH: cleaned output: '{output}'\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def send_commandTelnet(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandTelnet')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + '\\n'\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_commandTelnet: byte_data: '{byte_data}'\")\n output = str(byte_data)\n log.info(f\"send_commandTelnet: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_commandTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_commandTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_commandTelnet: raw output: '{output}'\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandTelnet: cleaned output: '{output}'\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def telnet_send_command_with_unexpected_pattern(self, cmd,\n pattern, error_pattern=None, timeout=None):\n \"\"\"\n Async method used to send command for Telnet connection to a device with possible unexpected patterns\n\n send_command can wait till time out if login and password are wrong. This method\n speed up the returned error message when authentication failed is identified.\n This method is limited to authentication whem password is required\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used\n to define a custom or unexpected prompt a the end of a string\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :param error_pattern: optional, a list of failed prompts found when the login and password are not correct\n :type error_pattern: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('telnet_send_command_with_unexpected_pattern')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + self._carriage_return_for_send_command\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n pattern_not_found = True\n try:\n while pattern_not_found:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'\"\n )\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'\"\n )\n output = str(byte_data)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: output: '{output}'\"\n )\n if pattern:\n for prompt in pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'\"\n )\n if prompt in output:\n pattern_not_found = False\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'\"\n )\n break\n if error_pattern and pattern_not_found:\n for bad_prompt in error_pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'\"\n )\n if bad_prompt in output:\n log.error(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n raise Exception(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n except asyncio.TimeoutError:\n await self.disconnect()\n log.error(\n 'telnet_send_command_with_unexpected_pattern: reading prompt: timeout'\n )\n raise\n except Exception as error:\n await self.disconnect()\n log.error(\n f'telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}'\n )\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n return output\n\n async def send_config_set(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_set')\n if timeout is None:\n timeout = self.timeout\n log.info('send_command')\n if self._protocol == 'ssh':\n output = await self.send_config_setSSH(cmds, timeout)\n elif self._protocol == 'telnet':\n output = await self.send_config_setTelnet(cmds, timeout)\n else:\n raise Exception(\n f'send_config_set: unsupported protocol: {self._protocol}')\n return output\n\n async def send_config_setSSH(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setSSH')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list'\n )\n return returned_output\n log.info('send_config_set: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: configuration mode entered')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command sent')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command to leave configuration mode sent'\n )\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def send_config_setTelnet(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setTelnet')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list'\n )\n return returned_output\n log.info('send_config_setTelnet: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: configuration mode entered')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: command sent')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info(\n 'send_config_setTelnet: command to leave configuration mode sent')\n output = ''\n byte_data = b''\n loop = 3\n try:\n while loop:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n await asyncio.sleep(0.5)\n if self.check_if_prompt_is_found(output):\n break\n loop -= 1\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def get_version(self):\n \"\"\"\n Asyn method used to get the version of the software of the device\n\n :return: Version of the software of the device\n :rtype: str\n \"\"\"\n log.info('get_version')\n version = ''\n output = await self.send_command(self.cmd_get_version)\n version = output.split('Version ')[1].split(',')[0]\n log.info(f'get_version: version: {version}')\n return version\n\n async def get_hostname(self):\n \"\"\"\n Asyn method used to get the name of the device\n\n :return: Name of the device\n :rtype: str\n \"\"\"\n log.info('get_hostname')\n output = await self.send_command(self.cmd_get_hostname)\n log.info(f\"get_hostname: output: '{output}'\")\n output = output.split()[0]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_model(self):\n \"\"\"\n Asyn method used to get the model of the device\n\n :return: Model of the device\n :rtype: str\n \"\"\"\n log.info('get_model')\n output = await self.send_command(self.cmd_get_model)\n log.info(f\"get_model: output: '{output}'\")\n output = output.split('\"')[3]\n log.info(f\"get_model: model found: '{output}'\")\n return output\n\n async def get_serial_number(self):\n \"\"\"\n Get serial number of the switch or the serial number of the first switch of a stack\n\n :return: Serial number of the device\n :rtype: str\n \"\"\"\n log.info('get_serial_number')\n output = await self.send_command(self.cmd_get_serial_number)\n log.info(f\"get_serial_number: output: '{output}'\")\n output = output.splitlines()[0].split()[-1]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_config(self, timeout=None):\n \"\"\"\n Asyn method used to get the configuration of the device\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: Configuration of the device\n :rtype: str\n \"\"\"\n log.info('get_config')\n if timeout is None:\n timeout = self.timeout\n output = await self.send_command(self.cmd_get_config, timeout=timeout)\n return output\n\n async def save_config(self):\n \"\"\"\n Asyn method used to save the current configuration on the device\n\n :return: Commands of the configuration saving process\n :rtype: str\n \"\"\"\n log.info('save_config')\n output = await self.send_command(self.cmd_save_config)\n return output\n", "step-4": "import asyncio, asyncssh, logging\nlog = logging.getLogger(__package__)\nlogging.basicConfig(level=logging.DEBUG)\nasyncssh.set_debug_level(2)\nMAX_BUFFER_DATA = 65535\nipv4_netmask_list = {'0.0.0.0': '0', '128.0.0.0': '1', '192.0.0.0': '2',\n '224.0.0.0': '3', '240.0.0.0': '4', '248.0.0.0': '5', '252.0.0.0': '6',\n '254.0.0.0': '7', '255.0.0.0': '8', '255.128.0.0': '9', '255.192.0.0':\n '10', '255.224.0.0': '11', '255.240.0.0': '12', '255.248.0.0': '13',\n '255.252.0.0': '14', '255.254.0.0': '15', '255.255.0.0': '16',\n '255.255.128.0': '17', '255.255.192.0': '18', '255.255.224.0': '19',\n '255.255.240.0': '20', '255.255.248.0': '21', '255.255.252.0': '22',\n '255.255.254.0': '23', '255.255.255.0': '24', '255.255.255.128': '25',\n '255.255.255.192': '26', '255.255.255.224': '27', '255.255.255.240':\n '28', '255.255.255.248': '29', '255.255.255.252': '30',\n '255.255.255.254': '31', '255.255.255.255': '32'}\n\n\nclass NetworkDevice:\n \"\"\"\n Base class for network object\n\n\n :param ip: IP address of a device\n :type ip: str\n\n :param username: Username used to connect to a device\n :type username: str\n\n :param password: Password used to connect to a device\n :type password: str\n\n :param device_type: Type of device used\n :type device_type: str\n\n :param port: TCP port used to connect a device. Default value is \"22\" for SSH\n :type port: int, optional\n\n :param timeout: TCP port used to connect a device. Default value is 10 seconds\n :type timeout: int, optional\n\n :param _protocol: Protocol used to connect a device. \"ssh\" or \"telnet\" are possible options. Default value is \"ssh\"\n :type _protocol: str, optional\n\n :param enable_mode: Enable mode for devices requiring it. Default value is \"False\"\n :type enable_mode: bool, optional\n\n :param enable_password: Enable password used for enable mode.\n :type enable_password: str, optional\n\n :param conn: Variable used for the management of the SSH connection\n :type conn: SSHClientConnection object\n\n :param _writer: Variable used for the management of the Telnet connection and writing channel\n :type _writer: StreamWriter object\n\n :param _reader: Variable used for the management of the Telnet reading channel\n :type _reader: StreamReader object\n\n :param possible_prompts: Used by the connect method to list all possible prompts of the device\n :type possible_prompts: list\n\n :param _connect_first_ending_prompt: Default possible ending prompts. Used only the time after login and password to discover the prompt\n :type _connect_first_ending_prompt: list\n\n :param list_of_possible_ending_prompts: Different strings at the end of a prompt the device can get. Used for detecting the prompt returned in sent commands\n :type list_of_possible_ending_prompts: list\n\n :param _telnet_connect_login: Login prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_login: str\n\n :param _telnet_connect_password: Password prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_password: list\n\n :param _telnet_connect_authentication_fail_prompt: Known failing messages or prompts when an authentication has failed. Used to get an answer faster than timeout events\n :type _telnet_connect_authentication_fail_prompt: list\n\n :param cmd_enable: Enable command for entering into enable mode\n :type cmd_enable: str\n\n :param cmd_disable_paging: Command used to disable paging on a device. That command is run at connection time\n :type cmd_disable_paging: str\n\n :param cmd_enter_config_mode: Command used to enter into a configuration mode on a device when this device support that feature.\n :type cmd_enter_config_mode: str\n\n :param cmd_exit_config_mode: Command used to leave a configuration mode on a device when this device support that feature.\n :type cmd_exit_config_mode: str\n\n :param cmd_get_version: API command used to get the software version of a device\n :type cmd_get_version: str\n\n :param cmd_get_hostname: API command used to get the hostname of a device\n :type cmd_get_hostname: str\n\n :param cmd_get_model: API command used to get the model of a device\n :type cmd_get_model: str\n\n :param cmd_get_serial_number: API command used to get the serial number of a device\n :type cmd_get_serial_number: str\n\n :param cmd_get_config: API command used to get the running configuration of a device\n :type cmd_get_config: str\n\n :param cmd_save_config: API command used to save the running configuration on the device\n :type cmd_save_config: str\n \"\"\"\n\n def __init__(self, **kwargs):\n log.info('__init__')\n self.ip = ''\n self.username = ''\n self.password = ''\n self.device_type = ''\n self.port = 22\n self.timeout = 10\n self._protocol = 'ssh'\n self.enable_mode = False\n self.enable_password = ''\n self.conn = None\n self._writer = None\n self._reader = None\n self.possible_prompts = []\n self._connect_first_ending_prompt = ['#', '>']\n self.list_of_possible_ending_prompts = ['(config-line)#',\n '(config-if)#', '(config)#', '>', '#']\n self._carriage_return_for_send_command = '\\n'\n self._send_command_error_in_returned_output = []\n self._telnet_connect_login = 'Username:'\n self._telnet_connect_password = 'Password:'\n self._telnet_connect_authentication_fail_prompt = [':', '%']\n self.cmd_enable = 'enable'\n self.cmd_disable_paging = 'terminal length 0'\n self.cmd_enter_config_mode = 'configure terminal'\n self.cmd_exit_config_mode = 'exit'\n self.cmd_get_version = 'show version'\n self.cmd_get_hostname = 'show version | include uptime'\n self.cmd_get_model = 'show inventory'\n self.cmd_get_serial_number = 'show inventory | i SN'\n self.cmd_get_config = 'show running-config'\n self.cmd_save_config = 'write memory'\n self.cmd_get_interfaces = [\n 'interface ethernet print terse without-paging',\n 'foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}'\n , 'interface bridge port print terse without-paging']\n self.cmd_set_interface = ['interface ethernet enable <INTERFACE>',\n 'interface ethernet disable <INTERFACE>',\n 'interface ethernet comment <INTERFACE> \"<COMMENT>\"',\n 'interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>',\n 'interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]'\n ]\n self.cmd_get_mac_address_table = (\n 'interface bridge host print without-paging')\n self.cmd_get_arp = 'ip arp print terse without-paging'\n self.cmd_get_lldp_neighbors = 'ip neighbor print terse without-paging'\n self.cmd_get_vlans = 'interface bridge vlan print terse without-paging'\n self.cmd_add_vlan = (\n 'interface bridge vlan add vlan-ids=<VLAN> comment=\"<VLAN_NAME>\" bridge=<BRIDGE>'\n )\n self.cmd_remove_vlan = (\n 'interface bridge vlan remove [find vlan-ids=<VLAN>]')\n self.cmd_add_interface_to_vlan = ['interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_remove_interface_from_vlan = [\n 'interface bridge vlan print terse',\n 'interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>'\n ,\n 'interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>'\n ,\n 'interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>'\n ]\n self.cmd_get_routing_table = 'ip route print without-paging terse'\n self.cmd_get_interfaces_ip = 'ip address print terse without-paging'\n self.cmd_add_static_route = (\n 'ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>'\n )\n self.cmd_remove_static_route = (\n 'ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]')\n log.debug('__init__: kwargs: ' + str(kwargs))\n if 'ip' in kwargs:\n self.ip = kwargs['ip']\n log.info('__init__: ip found: ' + str(self.ip))\n if 'username' in kwargs:\n self.username = kwargs['username']\n log.info('__init__: username found: ' + str(self.username))\n if 'password' in kwargs:\n self.password = kwargs['password']\n log.debug('__init__: password found: ' + str(self.password))\n if 'device_type' in kwargs:\n self.device_type = kwargs['device_type']\n log.info('__init__: device_type found: ' + str(self.device_type))\n if 'timeout' in kwargs:\n self.timeout = kwargs['timeout']\n log.info('__init__: timeout found: ' + str(self.timeout))\n if 'protocol' in kwargs:\n self._protocol = kwargs['protocol'].lower()\n log.info('__init__: protocol found: ' + str(self._protocol))\n if self._protocol.lower() == 'telnet':\n self.port = 23\n if 'port' in kwargs:\n self.port = kwargs['port']\n log.info('__init__: port found: ' + str(self.port))\n if 'enable_mode' in kwargs:\n self.enable_mode = kwargs['enable_mode']\n log.info('__init__: enable_mode found: ' + str(self.enable_mode))\n if 'enable_password' in kwargs:\n self.enable_password = kwargs['enable_password']\n log.info('__init__: enable_password found: ' + str(self.\n enable_password))\n\n async def __aenter__(self):\n \"\"\"\n Context manager opening connection\n \"\"\"\n try:\n await self.connect()\n except Exception:\n await self.disconnect()\n raise\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback):\n \"\"\"\n Context manager closing connection\n \"\"\"\n await self.disconnect()\n\n def find_prompt(self, text):\n \"\"\"\n Method used to find a prompt inside an output string\n\n This method is used during the first communication with the device.\n First it find the prompt then caculate the different forms the prompt\n can take. This will be useful later on while finding prompt in other\n output stream (read).\n\n :param text: data with a prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt = text.split('\\n')[-1]\n prompt = text.split('\\r')[-1]\n log.info(f\"find_prompt: prompt: '{prompt}'\")\n self.possible_prompts = self.get_possible_prompts(prompt)\n return prompt\n\n def get_possible_prompts(self, prompt):\n \"\"\"\n Method used to check if a prompt has one of the expected endings then\n create a list with all possible prompts for the device\n\n :param prompt: a prompt with a possible ending prompt (eg. \"switch#\")\n :type prompt: str\n\n :return: the list of prompts\n :rtype: list\n \"\"\"\n list_of_prompts = []\n list_of_possible_ending_prompts = self.list_of_possible_ending_prompts\n my_prompt = prompt\n for ending in list_of_possible_ending_prompts:\n if my_prompt.endswith(ending):\n my_prompt = my_prompt[:-len(ending)]\n break\n log.info(f\"get_possible_prompts: prompt found: '{my_prompt}'\")\n log.info(f\"get_possible_prompts: prompt found size: '{len(my_prompt)}'\"\n )\n for ending in list_of_possible_ending_prompts:\n list_of_prompts.append(my_prompt + ending)\n log.info(\n f'get_possible_prompts: list of possible prompts: {list_of_prompts}'\n )\n return list_of_prompts\n\n def check_if_prompt_is_found(self, text):\n \"\"\"\n Method used to check if a prompt is detected inside a string\n\n :param text: a string with prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n prompt_found = False\n for prompt in self.possible_prompts:\n log.info(f\"check_if_prompt_is_found: prompt: '{prompt}'\")\n if prompt in text:\n prompt_found = True\n log.info(f\"check_if_prompt_is_found: prompt found: '{prompt}'\")\n break\n return prompt_found\n\n def remove_command_in_output(self, text, cmd):\n \"\"\"\n Method removing the command at the beginning of a string\n\n After sending commands an \"echo\" of the command sent\n is display in the output string. This method removes it.\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :param cmd: the command previously sent\n :type cmd: str\n\n :return: the output string without the command\n :rtype: str\n \"\"\"\n log.info(f\"remove_command_in_output: cmd = '{cmd}'\")\n log.info(\n f\"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'\")\n output = text.split(cmd + '\\n')[-1]\n log.info(f\"remove_command_in_output: output = '{output}'\")\n return output\n\n def remove_starting_carriage_return_in_output(self, text):\n \"\"\"\n Method removing the carriage return at the beginning of a string\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :return: the output string without the starting carriage return\n :rtype: str\n \"\"\"\n log.info('remove_starting_carriage_return_in_output')\n output = text.lstrip('\\r\\n\\r')\n log.info(\n f\"remove_starting_carriage_return_in_output: output = '{output}'\")\n return output\n\n def remove_ending_prompt_in_output(self, text):\n \"\"\"\n Method removing the prompt at the end of a string\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n log.info('remove_ending_prompt_in_output')\n for prompt in self.possible_prompts:\n log.info(f\"remove_ending_prompt_in_output: prompt: '{prompt}'\")\n if prompt in text:\n text = text[:-len(prompt)]\n text = text.rstrip('\\r\\n')\n break\n log.info(\n f\"remove_ending_prompt_in_output: text without prompt:\\n'{text}'\")\n return text\n\n def check_error_output(self, output):\n \"\"\"\n Check if an error is returned by the device (\"% Unrecognized command\", \"% Ambiguous command\", etc.)\n\n If an error is found, then an exception is raised\n \"\"\"\n log.info('check_error_output')\n if output:\n log.info('check_error_output: output has some data')\n for element in self._send_command_error_in_returned_output:\n log.info(f'check_error_output: element: {element}')\n log.info(f'check_error_output: output[0]: {output[0]}')\n if output.startswith(element):\n raise Exception(output)\n\n def remove_ansi_escape_sequence(self, text):\n \"\"\"\n Method removing ANSI escape sequence from a string\n Just CSI sequences are removed\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n output = ''\n esc_found = 0\n for i in text:\n if esc_found == 0:\n if i == '\\x1b':\n log.info('Esc!')\n esc_found = 1\n else:\n output += i\n elif esc_found == 1:\n if i == '[':\n log.info('CSI sequence')\n esc_found = 2\n else:\n output += '\\x1b' + i\n esc_found = 0\n elif i >= 'a' and i <= 'z' or i >= 'A' and i <= 'Z':\n log.info('End of escape sequence')\n esc_found = 0\n return output\n\n async def disable_paging(self):\n \"\"\"\n Async method disabling paging on a device\n\n Use the \"cmd_disable_paging\" attribute\n \"\"\"\n log.info('disable_paging')\n await self.send_command(self.cmd_disable_paging)\n\n async def connect(self):\n \"\"\"\n Async method used for connecting a device\n\n Currently supported: SSH and Telnet\n \"\"\"\n log.info('connect')\n try:\n if self._protocol == 'ssh':\n await self.connectSSH()\n elif self._protocol == 'telnet':\n await self.connectTelnet()\n else:\n raise Exception(\n f'connect: unsupported protocol: {self._protocol}')\n except Exception:\n log.info('connect: connection error')\n raise\n\n async def connectSSH(self):\n \"\"\"\n Async method used for connecting a device using SSH protocol\n \"\"\"\n log.info('connectSSH')\n generator = asyncssh.connect(self.ip, username=self.username,\n password=self.password, known_hosts=None, encryption_algs=[algs\n .decode('utf-8') for algs in asyncssh.encryption._enc_algs])\n try:\n self.conn = await asyncio.wait_for(generator, timeout=self.timeout)\n except asyncio.exceptions.TimeoutError as error:\n log.error(\n f\"connectSSH: connection failed: {self.ip} timeout: '{error}'\")\n raise asyncio.exceptions.TimeoutError(\n 'Connection failed: connection timed out.')\n except Exception as error:\n log.error(f\"connectSSH: connection failed: {self.ip} '{error}'\")\n raise\n log.info('connectSSH: connection success')\n self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type\n ='netscud')\n log.info('connectSSH: open_session success')\n data = ''\n prompt_not_found = True\n try:\n while prompt_not_found:\n log.info('connectSSH: beginning of the loop')\n data += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f\"connectSSH: data: '{str(data)}'\")\n log.info(\n f\"connectSSH: data: hex:'{data.encode('utf-8').hex()}'\")\n for prompt in self._connect_first_ending_prompt:\n if data.endswith(prompt):\n log.info(\n f\"connectSSH: first ending prompt found: '{prompt}'\"\n )\n prompt_not_found = False\n break\n log.info('connectSSH: end of loop')\n except Exception as error:\n log.error(\n f\"connectSSH: timeout while reading the prompt: {self.ip} '{error}'\"\n )\n raise\n log.info(f'connectSSH: end of prompt loop')\n data = self.remove_ansi_escape_sequence(data)\n self.prompt = self.find_prompt(str(data))\n log.info(f\"connectSSH: prompt found: '{self.prompt}'\")\n log.info(f\"connectSSH: prompt found size: '{len(self.prompt)}'\")\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def connectTelnet(self):\n \"\"\"\n Async method used for connecting a device using Telnet protocol\n \"\"\"\n log.info('connectTelnet')\n try:\n conn = asyncio.open_connection(self.ip, self.port)\n except Exception as error:\n log.error(\n f\"connectTelnet: preparation to the connection failed: '{error}'\"\n )\n raise\n log.info('connectTelnet: preparation to the connection success')\n try:\n self._reader, self._writer = await asyncio.wait_for(conn,\n timeout=self.timeout)\n except asyncio.TimeoutError:\n log.error('connectTelnet: connection: timeout')\n raise\n log.info('connectTelnet: connection success')\n prompt = self._telnet_connect_login\n prompt_password = self._telnet_connect_password\n use_login = True\n output = ''\n byte_data = b''\n while True:\n log.info(f'connectTelnet: read data for prompt')\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=self.timeout)\n log.info(f'connectTelnet: byte_data: {byte_data}')\n output = str(byte_data)\n log.info(f'connectTelnet: output: {output}')\n if prompt in output:\n break\n elif prompt_password in output:\n use_login = False\n break\n log.info(f\"connectTelnet: login prompt: '{output}'\")\n if use_login:\n log.info('connectTelnet: sending login')\n try:\n await self.send_command(self.username, prompt_password)\n log.info('connectTelnet: login sent')\n except Exception:\n raise\n log.info('connectTelnet: sending password')\n try:\n output = await self.telnet_send_command_with_unexpected_pattern(\n self.password, self._connect_first_ending_prompt, self.\n _telnet_connect_authentication_fail_prompt)\n except Exception:\n raise\n log.info('connectTelnet: password sent')\n self.prompt = self.find_prompt(str(output))\n log.info(f\"connectTelnet: prompt found: '{self.prompt}'\")\n if self.enable_mode:\n log.info('connectTelnet: enable mode to be activated')\n try:\n await self.send_command(self.cmd_enable, prompt_password)\n log.info('connectTelnet: enable command sent')\n log.info('connectTelnet: sending enable password')\n await self.telnet_send_command_with_unexpected_pattern(self\n .enable_password, self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt)\n log.info('connectTelnet: enable password sent')\n except Exception:\n log.info('connectTelnet: enable password failure')\n raise\n if self.cmd_disable_paging:\n await self.disable_paging()\n\n async def disconnect(self):\n \"\"\"\n Async method used to disconnect a device\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnect')\n if self._protocol == 'ssh':\n await self.disconnectSSH()\n elif self._protocol == 'telnet':\n await self.disconnectTelnet()\n else:\n raise Exception(f'Unsupported protocol: {self._protocol}')\n\n async def disconnectSSH(self):\n \"\"\"\n Async method used to disconnect a device in SSH\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectSSH')\n if self.conn:\n self.conn.close()\n self.conn = None\n\n async def disconnectTelnet(self):\n \"\"\"\n Async method used to disconnect a device in Telnet\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n log.info('disconnectTelnet')\n if self._writer:\n self._writer.close()\n self._writer = None\n\n async def send_command(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_command')\n if timeout is None:\n timeout = self.timeout\n if self._protocol == 'ssh':\n output = await self.send_commandSSH(cmd, pattern=pattern,\n timeout=timeout)\n elif self._protocol == 'telnet':\n output = await self.send_commandTelnet(cmd, pattern=pattern,\n timeout=timeout)\n else:\n raise Exception(\n f'send_command: unsupported protocol: {self._protocol}')\n return output\n\n async def send_commandSSH(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandSSH')\n if timeout is None:\n timeout = self.timeout\n log.info(f\"send_commandSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd + self._carriage_return_for_send_command)\n log.info('send_commandSSH: command sent')\n output = ''\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = self.remove_ansi_escape_sequence(output)\n output = output.replace('\\r', '')\n log.info(f\"send_commandSSH: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_commandSSH: raw output: '{output}'\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandSSH: cleaned output: '{output}'\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def send_commandTelnet(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('send_commandTelnet')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + '\\n'\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_commandTelnet: byte_data: '{byte_data}'\")\n output = str(byte_data)\n log.info(f\"send_commandTelnet: output: '{output}'\")\n if pattern:\n if pattern in output:\n break\n elif self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_commandTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_commandTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_commandTelnet: raw output: '{output}'\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_commandTelnet: cleaned output: '{output}'\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return output\n\n async def telnet_send_command_with_unexpected_pattern(self, cmd,\n pattern, error_pattern=None, timeout=None):\n \"\"\"\n Async method used to send command for Telnet connection to a device with possible unexpected patterns\n\n send_command can wait till time out if login and password are wrong. This method\n speed up the returned error message when authentication failed is identified.\n This method is limited to authentication whem password is required\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used\n to define a custom or unexpected prompt a the end of a string\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :param error_pattern: optional, a list of failed prompts found when the login and password are not correct\n :type error_pattern: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n log.info('telnet_send_command_with_unexpected_pattern')\n if timeout is None:\n timeout = self.timeout\n cmd = cmd + self._carriage_return_for_send_command\n self._writer.write(cmd.encode())\n output = ''\n byte_data = b''\n pattern_not_found = True\n try:\n while pattern_not_found:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'\"\n )\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'\"\n )\n output = str(byte_data)\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: output: '{output}'\"\n )\n if pattern:\n for prompt in pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'\"\n )\n if prompt in output:\n pattern_not_found = False\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'\"\n )\n break\n if error_pattern and pattern_not_found:\n for bad_prompt in error_pattern:\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'\"\n )\n if bad_prompt in output:\n log.error(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n raise Exception(\n 'telnet_send_command_with_unexpected_pattern: authentication failed'\n )\n except asyncio.TimeoutError:\n await self.disconnect()\n log.error(\n 'telnet_send_command_with_unexpected_pattern: reading prompt: timeout'\n )\n raise\n except Exception as error:\n await self.disconnect()\n log.error(\n f'telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}'\n )\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n return output\n\n async def send_config_set(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_set')\n if timeout is None:\n timeout = self.timeout\n log.info('send_command')\n if self._protocol == 'ssh':\n output = await self.send_config_setSSH(cmds, timeout)\n elif self._protocol == 'telnet':\n output = await self.send_config_setTelnet(cmds, timeout)\n else:\n raise Exception(\n f'send_config_set: unsupported protocol: {self._protocol}')\n return output\n\n async def send_config_setSSH(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setSSH')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list'\n )\n return returned_output\n log.info('send_config_set: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: configuration mode entered')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command sent')\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setSSH: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n self.stdinx.write(cmd)\n log.info('send_config_setSSH: command to leave configuration mode sent'\n )\n while True:\n output += await asyncio.wait_for(self.stdoutx.read(\n MAX_BUFFER_DATA), timeout=timeout)\n log.info(f\"send_config_setSSH: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n log.debug(\n f\"\"\"send_config_setSSH: raw output: '{output}'\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setSSH: cleaned output: '{output}'\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def send_config_setTelnet(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n log.info('send_config_setTelnet')\n if timeout is None:\n timeout = self.timeout\n returned_output = ''\n if isinstance(cmds, str):\n cmds = [cmds]\n elif not isinstance(cmds, list):\n log.error(\n 'send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list'\n )\n return returned_output\n log.info('send_config_setTelnet: entering configuration mode')\n output = ''\n cmd = self.cmd_enter_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: configuration mode entered')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: sending commands')\n output = ''\n for cmd in cmds:\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info('send_config_setTelnet: command sent')\n output = ''\n byte_data = b''\n try:\n while True:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n if self.check_if_prompt_is_found(output):\n break\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n log.info('send_config_setTelnet: leaving configuration mode')\n output = ''\n cmd = self.cmd_exit_config_mode\n cmd = cmd + self._carriage_return_for_send_command\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n self._writer.write(cmd.encode())\n log.info(\n 'send_config_setTelnet: command to leave configuration mode sent')\n output = ''\n byte_data = b''\n loop = 3\n try:\n while loop:\n byte_data += await asyncio.wait_for(self._reader.read(\n MAX_BUFFER_DATA), timeout=timeout)\n output = str(byte_data)\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n await asyncio.sleep(0.5)\n if self.check_if_prompt_is_found(output):\n break\n loop -= 1\n except asyncio.TimeoutError:\n log.error('send_config_setTelnet: connection: timeout')\n raise\n except Exception as error:\n log.error(f'send_config_setTelnet: error: {error}')\n raise\n output = byte_data.decode('utf-8', 'ignore')\n log.debug(\n f\"\"\"send_config_setTelnet: raw output: '{output}'\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\"\"\n )\n returned_output += output\n output = self.remove_command_in_output(output, str(cmd))\n output = self.remove_starting_carriage_return_in_output(output)\n output = self.remove_ending_prompt_in_output(output)\n log.debug(\n f\"\"\"send_config_setTelnet: cleaned output: '{output}'\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\"\"\n )\n self.check_error_output(output)\n return returned_output\n\n async def get_version(self):\n \"\"\"\n Asyn method used to get the version of the software of the device\n\n :return: Version of the software of the device\n :rtype: str\n \"\"\"\n log.info('get_version')\n version = ''\n output = await self.send_command(self.cmd_get_version)\n version = output.split('Version ')[1].split(',')[0]\n log.info(f'get_version: version: {version}')\n return version\n\n async def get_hostname(self):\n \"\"\"\n Asyn method used to get the name of the device\n\n :return: Name of the device\n :rtype: str\n \"\"\"\n log.info('get_hostname')\n output = await self.send_command(self.cmd_get_hostname)\n log.info(f\"get_hostname: output: '{output}'\")\n output = output.split()[0]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_model(self):\n \"\"\"\n Asyn method used to get the model of the device\n\n :return: Model of the device\n :rtype: str\n \"\"\"\n log.info('get_model')\n output = await self.send_command(self.cmd_get_model)\n log.info(f\"get_model: output: '{output}'\")\n output = output.split('\"')[3]\n log.info(f\"get_model: model found: '{output}'\")\n return output\n\n async def get_serial_number(self):\n \"\"\"\n Get serial number of the switch or the serial number of the first switch of a stack\n\n :return: Serial number of the device\n :rtype: str\n \"\"\"\n log.info('get_serial_number')\n output = await self.send_command(self.cmd_get_serial_number)\n log.info(f\"get_serial_number: output: '{output}'\")\n output = output.splitlines()[0].split()[-1]\n log.info(f\"get_hostname: hostname found: '{output}'\")\n return output\n\n async def get_config(self, timeout=None):\n \"\"\"\n Asyn method used to get the configuration of the device\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: Configuration of the device\n :rtype: str\n \"\"\"\n log.info('get_config')\n if timeout is None:\n timeout = self.timeout\n output = await self.send_command(self.cmd_get_config, timeout=timeout)\n return output\n\n async def save_config(self):\n \"\"\"\n Asyn method used to save the current configuration on the device\n\n :return: Commands of the configuration saving process\n :rtype: str\n \"\"\"\n log.info('save_config')\n output = await self.send_command(self.cmd_save_config)\n return output\n", "step-5": "# Python library import\nimport asyncio, asyncssh, logging\n\n# Module logging logger\nlog = logging.getLogger(__package__)\n\n# Debug level\n# logging.basicConfig(level=logging.WARNING)\n# logging.basicConfig(level=logging.INFO)\nlogging.basicConfig(level=logging.DEBUG)\nasyncssh.set_debug_level(2)\n\n\n# Declaration of constant values\n\n# Max data to read in read function\nMAX_BUFFER_DATA = 65535\n\n\n# Dictonary with all netmasks of IPv4\nipv4_netmask_list = {\n \"0.0.0.0\": \"0\",\n \"128.0.0.0\": \"1\",\n \"192.0.0.0\": \"2\",\n \"224.0.0.0\": \"3\",\n \"240.0.0.0\": \"4\",\n \"248.0.0.0\": \"5\",\n \"252.0.0.0\": \"6\",\n \"254.0.0.0\": \"7\",\n \"255.0.0.0\": \"8\",\n \"255.128.0.0\": \"9\",\n \"255.192.0.0\": \"10\",\n \"255.224.0.0\": \"11\",\n \"255.240.0.0\": \"12\",\n \"255.248.0.0\": \"13\",\n \"255.252.0.0\": \"14\",\n \"255.254.0.0\": \"15\",\n \"255.255.0.0\": \"16\",\n \"255.255.128.0\": \"17\",\n \"255.255.192.0\": \"18\",\n \"255.255.224.0\": \"19\",\n \"255.255.240.0\": \"20\",\n \"255.255.248.0\": \"21\",\n \"255.255.252.0\": \"22\",\n \"255.255.254.0\": \"23\",\n \"255.255.255.0\": \"24\",\n \"255.255.255.128\": \"25\",\n \"255.255.255.192\": \"26\",\n \"255.255.255.224\": \"27\",\n \"255.255.255.240\": \"28\",\n \"255.255.255.248\": \"29\",\n \"255.255.255.252\": \"30\",\n \"255.255.255.254\": \"31\",\n \"255.255.255.255\": \"32\",\n}\n\n\nclass NetworkDevice:\n \"\"\"\n Base class for network object\n\n\n :param ip: IP address of a device\n :type ip: str\n\n :param username: Username used to connect to a device\n :type username: str\n\n :param password: Password used to connect to a device\n :type password: str\n\n :param device_type: Type of device used\n :type device_type: str\n\n :param port: TCP port used to connect a device. Default value is \"22\" for SSH\n :type port: int, optional\n\n :param timeout: TCP port used to connect a device. Default value is 10 seconds\n :type timeout: int, optional\n\n :param _protocol: Protocol used to connect a device. \"ssh\" or \"telnet\" are possible options. Default value is \"ssh\"\n :type _protocol: str, optional\n\n :param enable_mode: Enable mode for devices requiring it. Default value is \"False\"\n :type enable_mode: bool, optional\n\n :param enable_password: Enable password used for enable mode.\n :type enable_password: str, optional\n\n :param conn: Variable used for the management of the SSH connection\n :type conn: SSHClientConnection object\n\n :param _writer: Variable used for the management of the Telnet connection and writing channel\n :type _writer: StreamWriter object\n\n :param _reader: Variable used for the management of the Telnet reading channel\n :type _reader: StreamReader object\n\n :param possible_prompts: Used by the connect method to list all possible prompts of the device\n :type possible_prompts: list\n\n :param _connect_first_ending_prompt: Default possible ending prompts. Used only the time after login and password to discover the prompt\n :type _connect_first_ending_prompt: list\n\n :param list_of_possible_ending_prompts: Different strings at the end of a prompt the device can get. Used for detecting the prompt returned in sent commands\n :type list_of_possible_ending_prompts: list\n\n :param _telnet_connect_login: Login prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_login: str\n\n :param _telnet_connect_password: Password prompt for Telnet. Used to detect when a login is expected or when login and password access is failed\n :type _telnet_connect_password: list\n\n :param _telnet_connect_authentication_fail_prompt: Known failing messages or prompts when an authentication has failed. Used to get an answer faster than timeout events\n :type _telnet_connect_authentication_fail_prompt: list\n\n :param cmd_enable: Enable command for entering into enable mode\n :type cmd_enable: str\n\n :param cmd_disable_paging: Command used to disable paging on a device. That command is run at connection time\n :type cmd_disable_paging: str\n\n :param cmd_enter_config_mode: Command used to enter into a configuration mode on a device when this device support that feature.\n :type cmd_enter_config_mode: str\n\n :param cmd_exit_config_mode: Command used to leave a configuration mode on a device when this device support that feature.\n :type cmd_exit_config_mode: str\n\n :param cmd_get_version: API command used to get the software version of a device\n :type cmd_get_version: str\n\n :param cmd_get_hostname: API command used to get the hostname of a device\n :type cmd_get_hostname: str\n\n :param cmd_get_model: API command used to get the model of a device\n :type cmd_get_model: str\n\n :param cmd_get_serial_number: API command used to get the serial number of a device\n :type cmd_get_serial_number: str\n\n :param cmd_get_config: API command used to get the running configuration of a device\n :type cmd_get_config: str\n\n :param cmd_save_config: API command used to save the running configuration on the device\n :type cmd_save_config: str\n \"\"\"\n\n def __init__(self, **kwargs):\n\n # Display info message\n log.info(\"__init__\")\n\n self.ip = \"\"\n self.username = \"\"\n self.password = \"\"\n self.device_type = \"\"\n self.port = 22\n self.timeout = 10\n self._protocol = \"ssh\"\n self.enable_mode = False\n self.enable_password = \"\"\n self.conn = None\n self._writer = None\n self._reader = None\n self.possible_prompts = []\n self._connect_first_ending_prompt = [\"#\", \">\"]\n self.list_of_possible_ending_prompts = [\n \"(config-line)#\",\n \"(config-if)#\",\n \"(config)#\",\n \">\",\n \"#\",\n ]\n self._carriage_return_for_send_command = \"\\n\"\n self._send_command_error_in_returned_output = []\n self._telnet_connect_login = \"Username:\"\n self._telnet_connect_password = \"Password:\"\n self._telnet_connect_authentication_fail_prompt = [\":\", \"%\"]\n\n # General commands\n self.cmd_enable = \"enable\"\n self.cmd_disable_paging = \"terminal length 0\"\n self.cmd_enter_config_mode = \"configure terminal\"\n self.cmd_exit_config_mode = \"exit\"\n self.cmd_get_version = \"show version\"\n self.cmd_get_hostname = \"show version | include uptime\"\n self.cmd_get_model = \"show inventory\"\n self.cmd_get_serial_number = \"show inventory | i SN\"\n self.cmd_get_config = \"show running-config\"\n self.cmd_save_config = \"write memory\"\n\n # Layer 1 commands\n self.cmd_get_interfaces = [\n \"interface ethernet print terse without-paging\",\n \"foreach i in=([/interface ethernet find]) do={/interface ethernet monitor $i once without-paging}\",\n \"interface bridge port print terse without-paging\",\n ]\n self.cmd_set_interface = [\n \"interface ethernet enable <INTERFACE>\",\n \"interface ethernet disable <INTERFACE>\",\n 'interface ethernet comment <INTERFACE> \"<COMMENT>\"',\n \"interface ethernet set l2mtu=<MAXIMUMFRAMESIZE> <INTERFACE>\",\n \"interface bridge port set frame-types=<MODE> ingress-filtering=<FILTERINGVLAN> [find interface=<INTERFACE>]\",\n ]\n\n # Layer 2 commands\n self.cmd_get_mac_address_table = \"interface bridge host print without-paging\"\n self.cmd_get_arp = \"ip arp print terse without-paging\"\n self.cmd_get_lldp_neighbors = \"ip neighbor print terse without-paging\"\n self.cmd_get_vlans = \"interface bridge vlan print terse without-paging\"\n self.cmd_add_vlan = 'interface bridge vlan add vlan-ids=<VLAN> comment=\"<VLAN_NAME>\" bridge=<BRIDGE>'\n self.cmd_remove_vlan = \"interface bridge vlan remove [find vlan-ids=<VLAN>]\"\n self.cmd_add_interface_to_vlan = [\n \"interface bridge vlan print terse\",\n \"interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>\",\n \"interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>\",\n \"interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>\",\n ]\n self.cmd_remove_interface_from_vlan = [\n \"interface bridge vlan print terse\",\n \"interface bridge vlan set [find vlan-ids=<VLAN>] untagged=<INTERFACE>\",\n \"interface bridge vlan set [find vlan-ids=<VLAN>] tagged=<INTERFACE>\",\n \"interface bridge port set [find interface=<INTERFACE>] pvid=<VLAN>\",\n ]\n\n # Layer 3 commands\n self.cmd_get_routing_table = \"ip route print without-paging terse\"\n self.cmd_get_interfaces_ip = \"ip address print terse without-paging\"\n self.cmd_add_static_route = \"ip route add dst-address=<NETWORK>/<PREFIXLENGTH> gateway=<DESTINATION> distance=<METRIC>\"\n self.cmd_remove_static_route = (\n \"ip route remove [find dst-address=<NETWORK>/<PREFIXLENGTH>]\"\n )\n\n # Display info message\n log.debug(\"__init__: kwargs: \" + str(kwargs))\n\n # Get information from dictionary\n\n # \"ip\" found?\n if \"ip\" in kwargs:\n\n # Save \"ip\" parameter\n self.ip = kwargs[\"ip\"]\n\n # Display info message\n log.info(\"__init__: ip found: \" + str(self.ip))\n\n # \"username\" found?\n if \"username\" in kwargs:\n self.username = kwargs[\"username\"]\n\n # Display info message\n log.info(\"__init__: username found: \" + str(self.username))\n\n # \"password\" found?\n if \"password\" in kwargs:\n self.password = kwargs[\"password\"]\n\n # Display info message\n log.debug(\"__init__: password found: \" + str(self.password))\n\n # \"device_type\" found?\n if \"device_type\" in kwargs:\n self.device_type = kwargs[\"device_type\"]\n\n # Display info message\n log.info(\"__init__: device_type found: \" + str(self.device_type))\n\n # \"timeout\" found?\n if \"timeout\" in kwargs:\n self.timeout = kwargs[\"timeout\"]\n\n # Display info message\n log.info(\"__init__: timeout found: \" + str(self.timeout))\n\n # \"protocol\" found?\n if \"protocol\" in kwargs:\n self._protocol = kwargs[\"protocol\"].lower()\n\n # Display info message\n log.info(\"__init__: protocol found: \" + str(self._protocol))\n\n # By default telnet port is 23\n if self._protocol.lower() == \"telnet\":\n self.port = 23\n\n # \"port\" found?\n if \"port\" in kwargs:\n self.port = kwargs[\"port\"]\n\n # Display info message\n log.info(\"__init__: port found: \" + str(self.port))\n\n # \"enable_mode\" found?\n if \"enable_mode\" in kwargs:\n self.enable_mode = kwargs[\"enable_mode\"]\n\n # Display info message\n log.info(\"__init__: enable_mode found: \" + str(self.enable_mode))\n\n # \"enable_password\" found?\n if \"enable_password\" in kwargs:\n self.enable_password = kwargs[\"enable_password\"]\n\n # Display info message\n log.info(\"__init__: enable_password found: \" + str(self.enable_password))\n\n async def __aenter__(self):\n \"\"\"\n Context manager opening connection\n \"\"\"\n\n try:\n # Run an async method to connect a device\n await self.connect()\n\n except Exception:\n\n # Disconnection (if needed) in case the connection is done but something failed\n await self.disconnect()\n\n # propagate exception if needed\n raise\n\n return self\n\n # async def _aexit_(self, exc_type, exc_value, traceback):\n async def __aexit__(self, exc_type, exc_value, traceback):\n\n \"\"\"\n Context manager closing connection\n \"\"\"\n\n # Close the connection\n await self.disconnect()\n\n def find_prompt(self, text):\n \"\"\"\n Method used to find a prompt inside an output string\n\n This method is used during the first communication with the device.\n First it find the prompt then caculate the different forms the prompt\n can take. This will be useful later on while finding prompt in other\n output stream (read).\n\n :param text: data with a prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n\n # Get last line of the data\n prompt = text.split(\"\\n\")[-1]\n\n # Remove possible \\r in the data\n # prompt = prompt.replace(\"\\r\", \"\")\n prompt = text.split(\"\\r\")[-1]\n\n # Display info message\n log.info(f\"find_prompt: prompt: '{prompt}'\")\n\n # Get the possible prompts for future recognition\n self.possible_prompts = self.get_possible_prompts(prompt)\n\n # Return the prompt\n return prompt\n\n def get_possible_prompts(self, prompt):\n \"\"\"\n Method used to check if a prompt has one of the expected endings then\n create a list with all possible prompts for the device\n\n :param prompt: a prompt with a possible ending prompt (eg. \"switch#\")\n :type prompt: str\n\n :return: the list of prompts\n :rtype: list\n \"\"\"\n\n # By default no prompts are returned\n list_of_prompts = []\n\n # Get all the ppossible values of the endings of the prompt\n list_of_possible_ending_prompts = self.list_of_possible_ending_prompts\n\n # Temporary variable storing the prompt value\n my_prompt = prompt\n\n # Test each possible prompt ending (i.e '#', '>', \"(config-if)#\", \"(config)#\")\n for ending in list_of_possible_ending_prompts:\n\n # Is this current prompt ending at the end of the prompt?\n if my_prompt.endswith(ending):\n\n # Yes\n\n # Then remove the ending\n my_prompt = my_prompt[: -len(ending)]\n\n # Break the loop\n break\n\n # Prompt should be from \"switch#\" to \"switch\"\n\n # Display info message\n log.info(f\"get_possible_prompts: prompt found: '{my_prompt}'\")\n\n # Display info message\n log.info(f\"get_possible_prompts: prompt found size: '{len(my_prompt)}'\")\n\n # Now create all the possible prompts for that device\n for ending in list_of_possible_ending_prompts:\n\n # Save the prompt name with a possible ending in the list\n list_of_prompts.append(my_prompt + ending)\n\n # Display info message\n log.info(f\"get_possible_prompts: list of possible prompts: {list_of_prompts}\")\n\n # Return the list of prompts\n return list_of_prompts\n\n def check_if_prompt_is_found(self, text):\n \"\"\"\n Method used to check if a prompt is detected inside a string\n\n :param text: a string with prompt\n :type text: str\n\n :return: the prompt found\n :rtype: str\n \"\"\"\n\n # By default the prompt is not found\n prompt_found = False\n\n # Check all possible prompts\n for prompt in self.possible_prompts:\n\n # Display info message\n log.info(f\"check_if_prompt_is_found: prompt: '{prompt}'\")\n\n # Is this prompt present in the text?\n if prompt in text:\n\n # Yes\n prompt_found = True\n\n # Display info message\n log.info(f\"check_if_prompt_is_found: prompt found: '{prompt}'\")\n\n # Leave the for loop\n break\n\n # Return the prompt found\n return prompt_found\n\n def remove_command_in_output(self, text, cmd):\n \"\"\"\n Method removing the command at the beginning of a string\n\n After sending commands an \"echo\" of the command sent\n is display in the output string. This method removes it.\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :param cmd: the command previously sent\n :type cmd: str\n\n :return: the output string without the command\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(f\"remove_command_in_output: cmd = '{cmd}'\")\n\n # Display info message\n log.info(f\"remove_command_in_output: cmd (hex) = '{cmd.encode().hex()}'\")\n\n # Remove the command from the beginning of the output\n # output = text.lstrip(cmd + \"\\n\")\n output = text.split(cmd + \"\\n\")[-1]\n\n # Display info message\n log.info(f\"remove_command_in_output: output = '{output}'\")\n\n # Return the string without the command\n return output\n\n def remove_starting_carriage_return_in_output(self, text):\n\n \"\"\"\n Method removing the carriage return at the beginning of a string\n\n :param text: the text with the command at the beginning\n :type text: str\n\n :return: the output string without the starting carriage return\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"remove_starting_carriage_return_in_output\")\n\n # Remove the carriage return at the beginning of the string\n output = text.lstrip(\"\\r\\n\\r\")\n\n # Display info message\n log.info(f\"remove_starting_carriage_return_in_output: output = '{output}'\")\n\n # Return the string without the starting carriage return\n return output\n\n def remove_ending_prompt_in_output(self, text):\n\n \"\"\"\n Method removing the prompt at the end of a string\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"remove_ending_prompt_in_output\")\n\n # Check all possible prompts\n for prompt in self.possible_prompts:\n\n # Display info message\n log.info(f\"remove_ending_prompt_in_output: prompt: '{prompt}'\")\n\n # Prompt found in the text?\n if prompt in text:\n\n # Yes\n\n # Then it is removed from the text\n # text = text.rstrip(prompt)\n text = text[: -len(prompt)]\n\n # Remove also carriage return\n text = text.rstrip(\"\\r\\n\")\n\n # Leave the loop\n break\n\n # output = text.rstrip(\"\\r\\n\" + self.prompt)\n\n # Display info message\n log.info(f\"remove_ending_prompt_in_output: text without prompt:\\n'{text}'\")\n\n # Return the text without prompt at the end\n return text\n\n def check_error_output(self, output):\n \"\"\"\n Check if an error is returned by the device (\"% Unrecognized command\", \"% Ambiguous command\", etc.)\n\n If an error is found, then an exception is raised\n \"\"\"\n\n # Display info message\n log.info(\"check_error_output\")\n\n # Check if output has some data\n if output:\n\n # Yes\n\n # Display info message\n log.info(\"check_error_output: output has some data\")\n\n # Check all elements in the list of output\n for element in self._send_command_error_in_returned_output:\n\n # Display info message\n log.info(f\"check_error_output: element: {element}\")\n\n # Display info message\n log.info(f\"check_error_output: output[0]: {output[0]}\")\n\n # Check if the output starts with a string with an error message (like \"% Invalid input detected at '^' marker.\")\n\n # Error message?\n if output.startswith(element):\n\n # Yes\n\n # Raise an exception\n raise Exception(output)\n\n def remove_ansi_escape_sequence(self, text):\n\n \"\"\"\n Method removing ANSI escape sequence from a string\n Just CSI sequences are removed\n\n :param text: the text with a prompt at the beginning\n :type text: str\n\n :return: the output string without the ending prompt\n :rtype: str\n \"\"\"\n\n # By default no string returned\n output = \"\"\n\n # By default no escape sequence found\n esc_found = 0\n\n # Read char by char a string\n for i in text:\n\n # Display char\n # log.info(f\"{str(i).encode('ascii')}\")\n\n # No escape previously found?\n if esc_found == 0:\n\n # No escape sequence currently found\n\n # Escape?\n if i == \"\\x1b\":\n\n # Yes\n log.info(\"Esc!\")\n\n # Escape found\n esc_found = 1\n\n else:\n\n # No\n\n # Then the current char can be saved\n output += i\n\n # Escape previously found?\n elif esc_found == 1:\n\n # Yes\n\n # Then check if this is a CSI sequence\n if i == \"[\":\n\n # Beginning of CSI sequence\n log.info(\"CSI sequence\")\n\n # CSI sequence\n esc_found = 2\n\n else:\n\n # Another Escape sequence\n\n # Keep the escape sequence in the string\n output += \"\\x1b\" + i\n\n # No escape sequence next\n esc_found = 0\n\n else:\n\n # Char between 'a' and 'z' or 'A' and 'Z'?\n if (i >= \"a\" and i <= \"z\") or (i >= \"A\" and i <= \"Z\"):\n\n # Yes\n\n # Then it is the end of CSI escape sequence\n log.info(\"End of escape sequence\")\n\n # No escape sequence next\n esc_found = 0\n\n # Return a string without ANSI escape sequence\n return output\n\n async def disable_paging(self):\n \"\"\"\n Async method disabling paging on a device\n\n Use the \"cmd_disable_paging\" attribute\n \"\"\"\n\n # Display info message\n log.info(\"disable_paging\")\n\n # Send command to the device to disable paging\n await self.send_command(self.cmd_disable_paging)\n\n async def connect(self):\n \"\"\"\n Async method used for connecting a device\n\n Currently supported: SSH and Telnet\n \"\"\"\n\n # Display info message\n log.info(\"connect\")\n\n try:\n\n # SSH?\n if self._protocol == \"ssh\":\n\n # Yes\n\n # Then Connect using SSH\n await self.connectSSH()\n\n # Telnet?\n elif self._protocol == \"telnet\":\n\n # Yes\n\n # Then Connect using Telnet\n await self.connectTelnet()\n\n else:\n\n # Unsupported protocol\n\n # Raise an exception\n raise Exception(f\"connect: unsupported protocol: {self._protocol}\")\n\n except Exception:\n\n # There was a problem with a connection method\n\n # Display info message\n log.info(\"connect: connection error\")\n\n raise\n\n async def connectSSH(self):\n \"\"\"\n Async method used for connecting a device using SSH protocol\n \"\"\"\n\n # Display info message\n log.info(\"connectSSH\")\n\n # Parameters of the connection\n generator = asyncssh.connect(\n self.ip,\n username=self.username,\n password=self.password,\n known_hosts=None,\n # encryption_algs=\"*\", # Parameter that includes all encryption algorithms (even the old ones disabled by default)\n encryption_algs=[\n algs.decode(\"utf-8\") for algs in asyncssh.encryption._enc_algs\n ], # Parameter that includes all encryption algorithms (even the old ones disabled by default)\n )\n\n # Trying to connect to the device\n try:\n\n self.conn = await asyncio.wait_for(generator, timeout=self.timeout)\n\n except asyncio.exceptions.TimeoutError as error:\n\n # Timeout\n\n # Display error message\n log.error(f\"connectSSH: connection failed: {self.ip} timeout: '{error}'\")\n\n # Exception propagation\n raise asyncio.exceptions.TimeoutError(\n \"Connection failed: connection timed out.\"\n )\n\n except Exception as error:\n\n # Connection failed\n\n # Display error message\n log.error(f\"connectSSH: connection failed: {self.ip} '{error}'\")\n\n # Exception propagation\n raise\n\n # Display info message\n log.info(\"connectSSH: connection success\")\n\n # Create a session\n self.stdinx, self.stdoutx, _ = await self.conn.open_session(term_type=\"netscud\")\n\n # Display info message\n log.info(\"connectSSH: open_session success\")\n\n # By default no data has been read\n data = \"\"\n\n # By default no prompt found\n prompt_not_found = True\n\n try:\n\n # Read data\n while prompt_not_found:\n\n # Display info message\n log.info(\"connectSSH: beginning of the loop\")\n\n # Read the prompt\n data += await asyncio.wait_for(\n self.stdoutx.read(MAX_BUFFER_DATA), timeout=self.timeout\n )\n\n # Display info message\n log.info(f\"connectSSH: data: '{str(data)}'\")\n\n # Display info message\n log.info(f\"connectSSH: data: hex:'{data.encode('utf-8').hex()}'\")\n\n # Check if an initial prompt is found\n for prompt in self._connect_first_ending_prompt:\n\n # Ending prompt found?\n if data.endswith(prompt):\n\n # Yes\n\n # Display info message\n log.info(f\"connectSSH: first ending prompt found: '{prompt}'\")\n\n # A ending prompt has been found\n prompt_not_found = False\n\n # Leave the loop\n break\n\n # Display info message\n log.info(\"connectSSH: end of loop\")\n\n except Exception as error:\n\n # Fail while reading the prompt\n\n # Display error message\n log.error(\n f\"connectSSH: timeout while reading the prompt: {self.ip} '{error}'\"\n )\n\n # Exception propagation\n raise\n\n # Display info message\n log.info(f\"connectSSH: end of prompt loop\")\n\n # Remove possible escape sequence\n data = self.remove_ansi_escape_sequence(data)\n\n # Find prompt\n self.prompt = self.find_prompt(str(data))\n\n # Display info message\n log.info(f\"connectSSH: prompt found: '{self.prompt}'\")\n\n # Display info message\n log.info(f\"connectSSH: prompt found size: '{len(self.prompt)}'\")\n\n # Disable paging command available?\n if self.cmd_disable_paging:\n # Yes\n\n # Disable paging\n await self.disable_paging()\n\n async def connectTelnet(self):\n \"\"\"\n Async method used for connecting a device using Telnet protocol\n \"\"\"\n\n # Display info message\n log.info(\"connectTelnet\")\n\n try:\n\n # Prepare connection with Telnet\n conn = asyncio.open_connection(self.ip, self.port)\n\n except Exception as error:\n\n # Preparation to the connection failed\n\n # Display error message\n log.error(f\"connectTelnet: preparation to the connection failed: '{error}'\")\n\n # Exception propagation\n raise\n\n # Display info message\n log.info(\"connectTelnet: preparation to the connection success\")\n\n try:\n\n # Connection with Telnet\n self._reader, self._writer = await asyncio.wait_for(\n conn, timeout=self.timeout\n )\n\n except asyncio.TimeoutError:\n\n # Time out during connection\n\n # Display error message\n log.error(\"connectTelnet: connection: timeout\")\n\n # Exception propagation\n raise\n\n # Display info message\n log.info(\"connectTelnet: connection success\")\n\n # Get prompt for the login\n prompt = self._telnet_connect_login\n\n # Get prompt for the password\n prompt_password = self._telnet_connect_password\n\n # By default a login is expected\n use_login = True\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n # Read the telnet information and first prompt (for login but a password prompt can be found for IOS for instance)\n while True:\n\n # Display info message\n log.info(f\"connectTelnet: read data for prompt\")\n\n # Read returned prompt\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=self.timeout\n )\n\n # Display info message\n log.info(f\"connectTelnet: byte_data: {byte_data}\")\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(f\"connectTelnet: output: {output}\")\n\n # Prompt for the username found?\n if prompt in output:\n\n # Yes\n\n # Leave the loop\n break\n\n # Prompt for the password found?\n elif prompt_password in output:\n\n # Yes\n\n # That means only password is required\n use_login = False\n\n # Leave the loop\n break\n\n # Display info message\n log.info(f\"connectTelnet: login prompt: '{output}'\")\n\n # Login to use?\n if use_login:\n\n # Yes\n\n # Display info message\n log.info(\"connectTelnet: sending login\")\n\n try:\n\n # Send login\n await self.send_command(self.username, prompt_password)\n\n # Display info message\n log.info(\"connectTelnet: login sent\")\n\n except Exception:\n\n # Problem with the login\n\n # Propagate the exception\n raise\n\n # Display info message\n log.info(\"connectTelnet: sending password\")\n\n try:\n # Send password\n output = await self.telnet_send_command_with_unexpected_pattern(\n self.password,\n self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt,\n )\n\n except Exception:\n\n # Problem with the password\n\n # Propagate the exception\n raise\n\n # Display info message\n log.info(\"connectTelnet: password sent\")\n\n # Find prompt\n self.prompt = self.find_prompt(str(output))\n\n # Display info message\n log.info(f\"connectTelnet: prompt found: '{self.prompt}'\")\n\n # Password enable?\n if self.enable_mode:\n\n # Yes\n\n # Display info message\n log.info(\"connectTelnet: enable mode to be activated\")\n\n try:\n\n # Send enable command\n await self.send_command(self.cmd_enable, prompt_password)\n\n # Display info message\n log.info(\"connectTelnet: enable command sent\")\n\n # Display info message\n log.info(\"connectTelnet: sending enable password\")\n\n # Send enable password\n await self.telnet_send_command_with_unexpected_pattern(\n self.enable_password,\n self._connect_first_ending_prompt,\n self._telnet_connect_authentication_fail_prompt,\n )\n\n # Display info message\n log.info(\"connectTelnet: enable password sent\")\n\n except Exception:\n\n # Problem with the enable password\n\n # Display info message\n log.info(\"connectTelnet: enable password failure\")\n\n # Propagate the exception\n raise\n\n # Disable paging command available?\n if self.cmd_disable_paging:\n\n # Yes\n\n # Disable paging\n await self.disable_paging()\n\n async def disconnect(self):\n \"\"\"\n Async method used to disconnect a device\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n\n # Debug info message\n log.info(\"disconnect\")\n\n # SSH?\n if self._protocol == \"ssh\":\n\n # Yes\n\n # Then disconnect using SSH\n await self.disconnectSSH()\n\n # Telnet?\n elif self._protocol == \"telnet\":\n\n # Yes\n\n # Then disconnect using Telnet\n await self.disconnectTelnet()\n\n else:\n\n # Unsupported protocol\n\n # Raise an exception\n raise Exception(f\"Unsupported protocol: {self._protocol}\")\n\n async def disconnectSSH(self):\n \"\"\"\n Async method used to disconnect a device in SSH\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n\n # Debug info message\n log.info(\"disconnectSSH\")\n\n # Connection previously open in SSH?\n if self.conn:\n\n # Yes\n\n # Then close the SSH connection\n self.conn.close()\n\n # No more connection to disconnect\n self.conn = None\n\n async def disconnectTelnet(self):\n \"\"\"\n Async method used to disconnect a device in Telnet\n\n If this method is not used then exceptions will happen\n when the program will end\n \"\"\"\n\n # Debug info message\n log.info(\"disconnectTelnet\")\n\n # Connection previously open in Telnet?\n if self._writer:\n\n # Yes\n\n # Then close the SSH connection\n self._writer.close()\n\n # No more connection to disconnect\n self._writer = None\n\n async def send_command(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n\n # Debug info message\n log.info(\"send_command\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # SSH?\n if self._protocol == \"ssh\":\n\n # Yes\n\n # Then disconnect using SSH\n output = await self.send_commandSSH(cmd, pattern=pattern, timeout=timeout)\n\n # Telnet?\n elif self._protocol == \"telnet\":\n\n # Yes\n\n # Then disconnect using Telnet\n output = await self.send_commandTelnet(\n cmd, pattern=pattern, timeout=timeout\n )\n\n else:\n\n # Unsupported protocol\n\n # Raise an exception\n raise Exception(f\"send_command: unsupported protocol: {self._protocol}\")\n\n # Return the result of the command\n return output\n\n async def send_commandSSH(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n\n # Debug info message\n log.info(\"send_commandSSH\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Add carriage return at the end of the command (mandatory to send the command)\n # cmd = cmd + \"\\n\"\n # cmd = cmd + \"\\r\\n\"\n\n # Debug info message\n log.info(f\"send_commandSSH: cmd = '{cmd}'\")\n\n # Sending command\n self.stdinx.write(cmd + self._carriage_return_for_send_command)\n\n # Display message\n log.info(\"send_commandSSH: command sent\")\n\n # Variable used to gather data\n output = \"\"\n\n # Reading data\n while True:\n\n # await asyncio.sleep(1)\n\n # Read the data received\n output += await asyncio.wait_for(\n self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Debug info message\n # log.info(f\"send_commandSSH: output hex: '{str(output).encode(\"utf-8\").hex()}'\")\n\n # Remove ANSI escape sequence\n output = self.remove_ansi_escape_sequence(output)\n\n # Remove possible \"\\r\"\n output = output.replace(\"\\r\", \"\")\n\n # data = \"\"\n # for i in output:\n # data += i.encode(\"utf-8\").hex()\n\n # print(data)\n\n # Debug info message\n log.info(f\"send_commandSSH: output: '{output}'\")\n\n # Is a patten used?\n if pattern:\n\n # Use pattern instead of prompt\n if pattern in output:\n\n # Yes\n\n # Leave the loop\n break\n\n else:\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n # Debug info message\n log.debug(\n f\"send_commandSSH: raw output: '{output}'\\nsend_commandSSH: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Debug info message\n log.debug(\n f\"send_commandSSH: cleaned output: '{output}'\\nsend_commandSSH: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n # Return the result of the command\n return output\n\n async def send_commandTelnet(self, cmd, pattern=None, timeout=None):\n \"\"\"\n Async method used to send data to a device\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a pattern replacing the prompt when the prompt is not expected\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n\n # Debug info message\n log.info(\"send_commandTelnet\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + \"\\n\"\n\n # Sending command\n self._writer.write(cmd.encode())\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n try:\n\n # Read data\n while True:\n\n # Read returned prompt\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Display info message\n log.info(f\"send_commandTelnet: byte_data: '{byte_data}'\")\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(f\"send_commandTelnet: output: '{output}'\")\n\n # Is a patten used?\n if pattern:\n\n # Use pattern instead of prompt\n if pattern in output:\n\n # Yes\n\n # Leave the loop\n break\n\n else:\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n except asyncio.TimeoutError:\n\n # Time out during when reading prompt\n\n # Display error message\n log.error(\"send_commandTelnet: connection: timeout\")\n\n # Exception propagation\n raise\n\n except Exception as error:\n\n # Error during when reading prompt\n\n # Display error message\n log.error(f\"send_commandTelnet: error: {error}\")\n\n # Exception propagation\n raise\n\n # Convert data (bytes) into string\n output = byte_data.decode(\"utf-8\", \"ignore\")\n\n # Debug info message\n log.debug(\n f\"send_commandTelnet: raw output: '{output}'\\nsend_commandTelnet: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Debug info message\n log.debug(\n f\"send_commandTelnet: cleaned output: '{output}'\\nsend_commandTelnet: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n # Return the result of the command\n return output\n\n async def telnet_send_command_with_unexpected_pattern(\n self, cmd, pattern, error_pattern=None, timeout=None\n ):\n \"\"\"\n Async method used to send command for Telnet connection to a device with possible unexpected patterns\n\n send_command can wait till time out if login and password are wrong. This method\n speed up the returned error message when authentication failed is identified.\n This method is limited to authentication whem password is required\n\n :param cmd: command to send\n :type cmd: str\n\n :param pattern: optional, a list of patterns located at the very end of the a returned string. Can be used\n to define a custom or unexpected prompt a the end of a string\n :type pattern: str\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :param error_pattern: optional, a list of failed prompts found when the login and password are not correct\n :type error_pattern: str\n\n :return: the output of command\n :rtype: str\n \"\"\"\n\n # Debug info message\n log.info(\"telnet_send_command_with_unexpected_pattern\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Sending command\n self._writer.write(cmd.encode())\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n # By default pattern is not found\n pattern_not_found = True\n\n try:\n\n # Read data\n while pattern_not_found:\n\n # Read returned prompt\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Display info message\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: '{byte_data}'\"\n )\n\n # Display debug message\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: byte_data: hex: '{byte_data.hex()}'\"\n )\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: output: '{output}'\"\n )\n\n # Is a pattern used?\n if pattern:\n\n # Check all pattern of prompt in the output\n for prompt in pattern:\n\n # Display info message\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking prompt: '{prompt}'\"\n )\n\n # A pattern found?\n if prompt in output:\n\n # Yes\n\n # A pattern is found. The main loop can be stopped\n pattern_not_found = False\n\n # Display info message\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: prompt found: '{prompt}'\"\n )\n\n # Leave the loop\n break\n\n # Is an unexpected pattern used?\n if error_pattern and pattern_not_found:\n\n # Check all unexpected pattern of prompt in the output\n for bad_prompt in error_pattern:\n\n # Display info message\n log.info(\n f\"telnet_send_command_with_unexpected_pattern: checking unexpected prompt: '{bad_prompt}'\"\n )\n\n # An error_pattern pattern found?\n if bad_prompt in output:\n\n # Yes\n\n # Display error message\n log.error(\n \"telnet_send_command_with_unexpected_pattern: authentication failed\"\n )\n\n # Raise exception\n raise Exception(\n \"telnet_send_command_with_unexpected_pattern: authentication failed\"\n )\n\n # Leave the loop\n # break\n\n except asyncio.TimeoutError:\n\n # Time out during when reading prompt\n\n # Close the connection in order to not display RuntimeError\n await self.disconnect()\n\n # Display error message\n log.error(\n \"telnet_send_command_with_unexpected_pattern: reading prompt: timeout\"\n )\n\n # Exception propagation\n raise\n\n except Exception as error:\n\n # Error during when reading prompt\n\n # Close the connection in order to not display RuntimeError\n await self.disconnect()\n\n # Display error message\n log.error(\n f\"telnet_send_command_with_unexpected_pattern: reading prompt: error: {error}\"\n )\n\n # Exception propagation\n raise\n\n # Convert data (bytes) into string\n output = byte_data.decode(\"utf-8\", \"ignore\")\n\n # Debug info message\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: raw output: '{output}'\\ntelnet_send_command_with_unexpected_pattern: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Debug info message\n log.debug(\n f\"telnet_send_command_with_unexpected_pattern: cleaned output: '{output}'\\ntelnet_send_command_with_unexpected_pattern: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Return the result of the command\n return output\n\n async def send_config_set(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n\n # Display info message\n log.info(\"send_config_set\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Debug info message\n log.info(\"send_command\")\n\n # SSH?\n if self._protocol == \"ssh\":\n\n # Yes\n\n # Then disconnect using SSH\n output = await self.send_config_setSSH(cmds, timeout)\n\n # Telnet?\n elif self._protocol == \"telnet\":\n\n # Yes\n\n # Then disconnect using Telnet\n output = await self.send_config_setTelnet(cmds, timeout)\n\n else:\n\n # Unsupported protocol\n\n # Raise an exception\n raise Exception(f\"send_config_set: unsupported protocol: {self._protocol}\")\n\n # Return the result of the commands\n return output\n\n async def send_config_setSSH(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n\n # Display info message\n log.info(\"send_config_setSSH\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Clear returned output\n returned_output = \"\"\n\n # Check if cmds is a string\n if isinstance(cmds, str):\n\n # A string\n\n # Convert the string into a list\n cmds = [cmds]\n\n # A list?\n elif not isinstance(cmds, list):\n\n # Not a list (and not a string)\n\n # Display error message\n log.error(\n \"send_config_setSSH: parameter cmds used in send_config_set is neither a string nor a list\"\n )\n\n # Leave the method\n return returned_output\n\n ##############################\n # Entering configuration mode\n ##############################\n\n # Display info message\n log.info(\"send_config_set: entering configuration mode\")\n\n # Clear output\n output = \"\"\n\n # Get command for entering in config made\n cmd = self.cmd_enter_config_mode\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n\n # Sending command\n self.stdinx.write(cmd)\n\n # Display message\n log.info(\"send_config_setSSH: configuration mode entered\")\n\n while True:\n\n # Read the data received\n output += await asyncio.wait_for(\n self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Display info message\n log.info(f\"send_config_setSSH: output: '{output}'\")\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n # Debug info message\n log.debug(\n f\"send_config_setSSH: raw output: '{output}'\\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setSSH: cleaned output: '{output}'\\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n ##############################\n # Sending commands\n ##############################\n\n # Display info message\n log.info(\"send_config_setSSH: sending commands\")\n\n # Clear output\n output = \"\"\n\n # Each command\n for cmd in cmds:\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n\n # Sending command\n self.stdinx.write(cmd)\n\n # Display info message\n log.info(\"send_config_setSSH: command sent\")\n\n while True:\n\n # Read the data received\n output += await asyncio.wait_for(\n self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Display info message\n log.info(f\"send_config_setSSH: output: '{output}'\")\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n # Debug info message\n log.debug(\n f\"send_config_setSSH: raw output: '{output}'\\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setSSH: cleaned output: '{output}'\\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n ##############################\n # Leaving configuration mode\n ##############################\n\n # Display info message\n log.info(\"send_config_setSSH: leaving configuration mode\")\n\n # Clear output\n output = \"\"\n\n # Get command to leave config made\n cmd = self.cmd_exit_config_mode\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setSSH: cmd = '{cmd}'\")\n\n # Sending command\n self.stdinx.write(cmd)\n\n # Display info message\n log.info(\"send_config_setSSH: command to leave configuration mode sent\")\n\n while True:\n\n # Read the data received\n output += await asyncio.wait_for(\n self.stdoutx.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Display info message\n log.info(f\"send_config_setSSH: output: '{output}'\")\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n # Debug info message\n log.debug(\n f\"send_config_setSSH: raw output: '{output}'\\nsend_config_setSSH: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setSSH: cleaned output: '{output}'\\nsend_config_setSSH: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n # Return the result of the commands\n return returned_output\n\n async def send_config_setTelnet(self, cmds=None, timeout=None):\n \"\"\"\n Async method used to send command in config mode\n\n The commands send can be either a string a list of strings. There are\n 3 steps:\n - Entering configuration mode\n - Sending the commands\n - Leaving configuration mode\n\n :param cmds: The commands to the device\n :type cmds: str or list\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: the results of the commands sent\n :rtype: list of str\n \"\"\"\n\n # Display info message\n log.info(\"send_config_setTelnet\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Clear returned output\n returned_output = \"\"\n\n # Check if cmds is a string\n if isinstance(cmds, str):\n\n # A string\n\n # Convert the string into a list\n cmds = [cmds]\n\n # A list?\n elif not isinstance(cmds, list):\n\n # Not a list (and not a string)\n\n # Display error message\n log.error(\n \"send_config_setTelnet: parameter cmds used in send_config_set is neither a string or a list\"\n )\n\n # Leave the method\n return returned_output\n\n ##############################\n # Entering configuration mode\n ##############################\n\n # Display info message\n log.info(\"send_config_setTelnet: entering configuration mode\")\n\n # Clear output\n output = \"\"\n\n # Get command for entering in config made\n cmd = self.cmd_enter_config_mode\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n\n # Sending command\n self._writer.write(cmd.encode())\n\n # Display message\n log.info(\"send_config_setTelnet: configuration mode entered\")\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n try:\n\n # Read data\n while True:\n\n # Read the data received\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n except asyncio.TimeoutError:\n\n # Time out during when reading prompt\n\n # Display error message\n log.error(\"send_config_setTelnet: connection: timeout\")\n\n # Exception propagation\n raise\n\n except Exception as error:\n\n # Error during when reading prompt\n\n # Display error message\n log.error(f\"send_config_setTelnet: error: {error}\")\n\n # Exception propagation\n raise\n\n # Convert data (bytes) into string\n output = byte_data.decode(\"utf-8\", \"ignore\")\n\n # Debug info message\n log.debug(\n f\"send_config_setTelnet: raw output: '{output}'\\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setTelnet: cleaned output: '{output}'\\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n ##############################\n # Sending commands\n ##############################\n\n # Display info message\n log.info(\"send_config_setTelnet: sending commands\")\n\n # Clear output\n output = \"\"\n\n # Each command\n for cmd in cmds:\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n\n # Sending command\n self._writer.write(cmd.encode())\n\n # Display info message\n log.info(\"send_config_setTelnet: command sent\")\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n try:\n\n # Read data\n while True:\n\n # Read the data received\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n except asyncio.TimeoutError:\n\n # Time out during when reading prompt\n\n # Display error message\n log.error(\"send_config_setTelnet: connection: timeout\")\n\n # Exception propagation\n raise\n\n except Exception as error:\n\n # Error during when reading prompt\n\n # Display error message\n log.error(f\"send_config_setTelnet: error: {error}\")\n\n # Exception propagation\n raise\n\n # Convert data (bytes) into string\n output = byte_data.decode(\"utf-8\", \"ignore\")\n\n # Debug info message\n log.debug(\n f\"send_config_setTelnet: raw output: '{output}'\\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setTelnet: cleaned output: '{output}'\\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n ##############################\n # Leaving configuration mode\n ##############################\n\n # Display info message\n log.info(\"send_config_setTelnet: leaving configuration mode\")\n\n # Clear output\n output = \"\"\n\n # Get command to leave config made\n cmd = self.cmd_exit_config_mode\n\n # Add carriage return at the end of the command (mandatory to send the command)\n cmd = cmd + self._carriage_return_for_send_command\n\n # Display info message\n log.info(f\"send_config_setTelnet: cmd = '{cmd}'\")\n\n # Sending command\n self._writer.write(cmd.encode())\n\n # Display info message\n log.info(\"send_config_setTelnet: command to leave configuration mode sent\")\n\n # Temporary string variable\n output = \"\"\n\n # Temporary bytes variable\n byte_data = b\"\"\n\n # Protection against infinite loop\n loop = 3\n\n try:\n\n # Read data\n while loop:\n\n # Read the data received\n byte_data += await asyncio.wait_for(\n self._reader.read(MAX_BUFFER_DATA), timeout=timeout\n )\n\n # Temporary convertion in string. This string has the following form: \"b'....'\"\n output = str(byte_data)\n\n # Display info message\n log.info(f\"send_config_setTelnet: output: '{output}'\")\n\n await asyncio.sleep(0.5)\n\n # Check if prompt is found\n if self.check_if_prompt_is_found(output):\n\n # Yes\n\n # Leave the loop\n break\n\n # Protection for \"exit\" command infinite loop in Cisco when enable is not activated\n loop -= 1\n\n except asyncio.TimeoutError:\n\n # Time out during when reading prompt\n\n # Display error message\n log.error(\"send_config_setTelnet: connection: timeout\")\n\n # Exception propagation\n raise\n\n except Exception as error:\n\n # Error during when reading prompt\n\n # Display error message\n log.error(f\"send_config_setTelnet: error: {error}\")\n\n # Exception propagation\n raise\n\n # Convert data (bytes) into string\n output = byte_data.decode(\"utf-8\", \"ignore\")\n\n # Debug info message\n log.debug(\n f\"send_config_setTelnet: raw output: '{output}'\\nsend_config_setTelnet: raw output (hex): '{output.encode().hex()}'\"\n )\n\n # Add the output to the returned output\n returned_output += output\n\n # Remove the command sent from the result of the command\n output = self.remove_command_in_output(output, str(cmd))\n # Remove the carriage return of the output\n output = self.remove_starting_carriage_return_in_output(output)\n # Remove the ending prompt of the output\n output = self.remove_ending_prompt_in_output(output)\n\n # Display info message\n log.debug(\n f\"send_config_setTelnet: cleaned output: '{output}'\\nsend_config_setTelnet: cleaned output (hex): '{output.encode().hex()}'\"\n )\n\n # Check if there is an error in the output string (like \"% Unrecognized command\")\n # and generate an exception if needed\n self.check_error_output(output)\n\n # Return the result of the commands\n return returned_output\n\n #########################################################\n #\n # List of API\n #\n #########################################################\n\n async def get_version(self):\n \"\"\"\n Asyn method used to get the version of the software of the device\n\n :return: Version of the software of the device\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"get_version\")\n\n # By default empty string\n version = \"\"\n\n # Run get version on the device\n output = await self.send_command(self.cmd_get_version)\n\n # Seek \"Version \" and \",\" to get the version in the returned output\n version = output.split(\"Version \")[1].split(\",\")[0]\n\n # Display info message\n log.info(f\"get_version: version: {version}\")\n\n # Return the version of the software of the device\n return version\n\n async def get_hostname(self):\n \"\"\"\n Asyn method used to get the name of the device\n\n :return: Name of the device\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"get_hostname\")\n\n # Get hostname\n output = await self.send_command(self.cmd_get_hostname)\n\n # Display info message\n log.info(f\"get_hostname: output: '{output}'\")\n\n # Remove the useless information in the returned string\n output = output.split()[0]\n\n # Display info message\n log.info(f\"get_hostname: hostname found: '{output}'\")\n\n # Return the name of the device\n return output\n\n async def get_model(self):\n \"\"\"\n Asyn method used to get the model of the device\n\n :return: Model of the device\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"get_model\")\n\n # Get model\n output = await self.send_command(self.cmd_get_model)\n\n # Display info message\n log.info(f\"get_model: output: '{output}'\")\n\n # Remove the useless information in the returned string\n output = output.split('\"')[3]\n\n # Display info message\n log.info(f\"get_model: model found: '{output}'\")\n\n # Return the model of the device\n return output\n\n async def get_serial_number(self):\n \"\"\"\n Get serial number of the switch or the serial number of the first switch of a stack\n\n :return: Serial number of the device\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"get_serial_number\")\n\n # Get serial number\n output = await self.send_command(self.cmd_get_serial_number)\n\n # Display info message\n log.info(f\"get_serial_number: output: '{output}'\")\n\n # Remove the useless information in the returned string\n output = output.splitlines()[0].split()[-1]\n\n # Display info message\n log.info(f\"get_hostname: hostname found: '{output}'\")\n\n # Return the serial number of the device\n return output\n\n async def get_config(self, timeout=None):\n \"\"\"\n Asyn method used to get the configuration of the device\n\n :param timeout: optional, a timeout for the command sent. Default value is self.timeout\n :type timeout: str\n\n :return: Configuration of the device\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"get_config\")\n\n # Default value of timeout variable\n if timeout is None:\n timeout = self.timeout\n\n # Get config\n output = await self.send_command(self.cmd_get_config, timeout=timeout)\n\n # Return de configuration of the device\n return output\n\n async def save_config(self):\n \"\"\"\n Asyn method used to save the current configuration on the device\n\n :return: Commands of the configuration saving process\n :rtype: str\n \"\"\"\n\n # Display info message\n log.info(\"save_config\")\n\n # Send command\n output = await self.send_command(self.cmd_save_config)\n\n # Return the commands of the configuration saving process\n return output\n", "step-ids": [ 9, 10, 12, 14, 15 ] }
[ 9, 10, 12, 14, 15 ]
#!/usr/bin/env python # encoding: utf-8 """ @description: 有序字典 (notice: python3.6 以后字典已经有序了) @author: baoqiang @time: 2019/11/28 1:34 下午 """ from collections import OrderedDict def run206_01(): print('Regular dict:') # d = {'a':'A','b':'B','c':'C'} d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) print('OrderedDict:') d = OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) def run206_02(): """ 相等性判断,需要考虑顺序 :return: """ print('Regular dict:') d1 = {'a': 'A', 'b': 'B', 'c': 'C'} d2 = {'c': 'C', 'b': 'B', 'a': 'A'} print(d1 == d2) for k, v in d1.items(): print(k, v) for k, v in d2.items(): print(k, v) print('OrderedDict:') d1 = OrderedDict(d1) d2 = OrderedDict(d2) print(d1 == d2) for k, v in d1.items(): print(k, v) for k, v in d2.items(): print(k, v) def run206_03(): """ re ordering :return: """ d = OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')]) print('Before:') for k, v in d.items(): print(k, v) d.move_to_end('b') print('\nmove_to_end():') for k, v in d.items(): print(k, v) d.move_to_end('b', last=False) print('\nmove_to_end(last=False):') for k, v in d.items(): print(k, v)
normal
{ "blob_id": "4a7d8db2bc3b753ea1a12120e1ad85f31d572dc7", "index": 4237, "step-1": "<mask token>\n\n\ndef run206_01():\n print('Regular dict:')\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n print('OrderedDict:')\n d = OrderedDict()\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef run206_01():\n print('Regular dict:')\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n print('OrderedDict:')\n d = OrderedDict()\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n\ndef run206_02():\n \"\"\"\n 相等性判断,需要考虑顺序\n :return:\n \"\"\"\n print('Regular dict:')\n d1 = {'a': 'A', 'b': 'B', 'c': 'C'}\n d2 = {'c': 'C', 'b': 'B', 'a': 'A'}\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n print('OrderedDict:')\n d1 = OrderedDict(d1)\n d2 = OrderedDict(d2)\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef run206_01():\n print('Regular dict:')\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n print('OrderedDict:')\n d = OrderedDict()\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n\ndef run206_02():\n \"\"\"\n 相等性判断,需要考虑顺序\n :return:\n \"\"\"\n print('Regular dict:')\n d1 = {'a': 'A', 'b': 'B', 'c': 'C'}\n d2 = {'c': 'C', 'b': 'B', 'a': 'A'}\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n print('OrderedDict:')\n d1 = OrderedDict(d1)\n d2 = OrderedDict(d2)\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n\n\ndef run206_03():\n \"\"\"\n re ordering\n :return:\n \"\"\"\n d = OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')])\n print('Before:')\n for k, v in d.items():\n print(k, v)\n d.move_to_end('b')\n print('\\nmove_to_end():')\n for k, v in d.items():\n print(k, v)\n d.move_to_end('b', last=False)\n print('\\nmove_to_end(last=False):')\n for k, v in d.items():\n print(k, v)\n", "step-4": "<mask token>\nfrom collections import OrderedDict\n\n\ndef run206_01():\n print('Regular dict:')\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n print('OrderedDict:')\n d = OrderedDict()\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n\ndef run206_02():\n \"\"\"\n 相等性判断,需要考虑顺序\n :return:\n \"\"\"\n print('Regular dict:')\n d1 = {'a': 'A', 'b': 'B', 'c': 'C'}\n d2 = {'c': 'C', 'b': 'B', 'a': 'A'}\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n print('OrderedDict:')\n d1 = OrderedDict(d1)\n d2 = OrderedDict(d2)\n print(d1 == d2)\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n\n\ndef run206_03():\n \"\"\"\n re ordering\n :return:\n \"\"\"\n d = OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')])\n print('Before:')\n for k, v in d.items():\n print(k, v)\n d.move_to_end('b')\n print('\\nmove_to_end():')\n for k, v in d.items():\n print(k, v)\n d.move_to_end('b', last=False)\n print('\\nmove_to_end(last=False):')\n for k, v in d.items():\n print(k, v)\n", "step-5": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@description: 有序字典\n(notice: python3.6 以后字典已经有序了)\n\n@author: baoqiang\n@time: 2019/11/28 1:34 下午\n\"\"\"\n\nfrom collections import OrderedDict\n\n\ndef run206_01():\n print('Regular dict:')\n # d = {'a':'A','b':'B','c':'C'}\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n print('OrderedDict:')\n d = OrderedDict()\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n\n\ndef run206_02():\n \"\"\"\n 相等性判断,需要考虑顺序\n :return:\n \"\"\"\n print('Regular dict:')\n d1 = {'a': 'A', 'b': 'B', 'c': 'C'}\n d2 = {'c': 'C', 'b': 'B', 'a': 'A'}\n print(d1 == d2)\n\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n\n print('OrderedDict:')\n d1 = OrderedDict(d1)\n d2 = OrderedDict(d2)\n print(d1 == d2)\n\n for k, v in d1.items():\n print(k, v)\n for k, v in d2.items():\n print(k, v)\n\n\ndef run206_03():\n \"\"\"\n re ordering\n :return:\n \"\"\"\n d = OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')])\n\n print('Before:')\n for k, v in d.items():\n print(k, v)\n\n d.move_to_end('b')\n print('\\nmove_to_end():')\n for k, v in d.items():\n print(k, v)\n\n d.move_to_end('b', last=False)\n print('\\nmove_to_end(last=False):')\n for k, v in d.items():\n print(k, v)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import tensorflow as tf import numpy as np import tensorflow.contrib.layers as layers class Model(object): def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope="model"): self._batch_size = batch_size self._learning_rate = learning_rate self._num_labels = num_labels self._scope = scope self._keep_prob = keep_prob self._conv_hidden_dims = [192, 192] with tf.variable_scope(self._scope): self._build_model() def _build_net(self, x, reuse=False, trainable=True, scope="inference_net"): with tf.variable_scope(scope, reuse=reuse): out = x for i in range(len(self._conv_hidden_dims)): out = layers.conv2d(out, num_outputs=self._conv_hidden_dims[i], kernel_size=(5, 5), activation_fn=tf.nn.relu, trainable=trainable) out = layers.dropout(out, keep_prob=self._keep_prob, is_training=trainable) out = layers.max_pool2d(out, kernel_size=(2, 2)) out = layers.flatten(out) out = layers.fully_connected(out, num_outputs=1000, activation_fn=tf.nn.relu, trainable=trainable) out = layers.dropout(out, keep_prob=self._keep_prob, is_training=trainable) logits = layers.fully_connected(out, self._num_labels, trainable=trainable) return logits def _build_model(self): self.x_ = tf.placeholder(tf.float32, shape=[None, 3072], name='x_') # data gets loaded as a 32x32 vector x = tf.reshape(self.x_, [-1, 32, 32, 3], name='x') # CIFAR dataset is shape 32,32,3 self.y = tf.placeholder(tf.float32, shape=[None, self._num_labels], name='y') # 10 labels # self.keep_prob = tf.placeholder(tf.float32, name='dropout_prob') self.lr = tf.placeholder(tf.float32, shape=(), name='lr') self.logits = self._build_net(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.y) self.loss = tf.reduce_mean(cross_entropy) optimizer = tf.train.MomentumOptimizer(self.lr, momentum=0.9, use_nesterov=True) self.train_op = optimizer.minimize(loss=self.loss) self.acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32)) # for eval steps self.val_logits = self._build_net(x, reuse=True, trainable=False) self.val_acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.val_logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32)) tf.summary.scalar('loss', self.loss) tf.summary.scalar('accuracy', self.acc) self.merged = tf.summary.merge_all()
normal
{ "blob_id": "e9a1fd8464f6c1e65aa2c1af60becbfcbf050814", "index": 7390, "step-1": "<mask token>\n\n\nclass Model(object):\n\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10,\n keep_prob=0.5, scope='model'):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n self._num_labels = num_labels\n self._scope = scope\n self._keep_prob = keep_prob\n self._conv_hidden_dims = [192, 192]\n with tf.variable_scope(self._scope):\n self._build_model()\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Model(object):\n\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10,\n keep_prob=0.5, scope='model'):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n self._num_labels = num_labels\n self._scope = scope\n self._keep_prob = keep_prob\n self._conv_hidden_dims = [192, 192]\n with tf.variable_scope(self._scope):\n self._build_model()\n\n def _build_net(self, x, reuse=False, trainable=True, scope='inference_net'\n ):\n with tf.variable_scope(scope, reuse=reuse):\n out = x\n for i in range(len(self._conv_hidden_dims)):\n out = layers.conv2d(out, num_outputs=self._conv_hidden_dims\n [i], kernel_size=(5, 5), activation_fn=tf.nn.relu,\n trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n out = layers.max_pool2d(out, kernel_size=(2, 2))\n out = layers.flatten(out)\n out = layers.fully_connected(out, num_outputs=1000,\n activation_fn=tf.nn.relu, trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n logits = layers.fully_connected(out, self._num_labels,\n trainable=trainable)\n return logits\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Model(object):\n\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10,\n keep_prob=0.5, scope='model'):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n self._num_labels = num_labels\n self._scope = scope\n self._keep_prob = keep_prob\n self._conv_hidden_dims = [192, 192]\n with tf.variable_scope(self._scope):\n self._build_model()\n\n def _build_net(self, x, reuse=False, trainable=True, scope='inference_net'\n ):\n with tf.variable_scope(scope, reuse=reuse):\n out = x\n for i in range(len(self._conv_hidden_dims)):\n out = layers.conv2d(out, num_outputs=self._conv_hidden_dims\n [i], kernel_size=(5, 5), activation_fn=tf.nn.relu,\n trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n out = layers.max_pool2d(out, kernel_size=(2, 2))\n out = layers.flatten(out)\n out = layers.fully_connected(out, num_outputs=1000,\n activation_fn=tf.nn.relu, trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n logits = layers.fully_connected(out, self._num_labels,\n trainable=trainable)\n return logits\n\n def _build_model(self):\n self.x_ = tf.placeholder(tf.float32, shape=[None, 3072], name='x_')\n x = tf.reshape(self.x_, [-1, 32, 32, 3], name='x')\n self.y = tf.placeholder(tf.float32, shape=[None, self._num_labels],\n name='y')\n self.lr = tf.placeholder(tf.float32, shape=(), name='lr')\n self.logits = self._build_net(x)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self\n .logits, labels=self.y)\n self.loss = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.MomentumOptimizer(self.lr, momentum=0.9,\n use_nesterov=True)\n self.train_op = optimizer.minimize(loss=self.loss)\n self.acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.logits, 1\n ), tf.argmax(self.y, 1)), dtype=tf.float32))\n self.val_logits = self._build_net(x, reuse=True, trainable=False)\n self.val_acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.\n val_logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32))\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.acc)\n self.merged = tf.summary.merge_all()\n", "step-4": "import tensorflow as tf\nimport numpy as np\nimport tensorflow.contrib.layers as layers\n\n\nclass Model(object):\n\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10,\n keep_prob=0.5, scope='model'):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n self._num_labels = num_labels\n self._scope = scope\n self._keep_prob = keep_prob\n self._conv_hidden_dims = [192, 192]\n with tf.variable_scope(self._scope):\n self._build_model()\n\n def _build_net(self, x, reuse=False, trainable=True, scope='inference_net'\n ):\n with tf.variable_scope(scope, reuse=reuse):\n out = x\n for i in range(len(self._conv_hidden_dims)):\n out = layers.conv2d(out, num_outputs=self._conv_hidden_dims\n [i], kernel_size=(5, 5), activation_fn=tf.nn.relu,\n trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n out = layers.max_pool2d(out, kernel_size=(2, 2))\n out = layers.flatten(out)\n out = layers.fully_connected(out, num_outputs=1000,\n activation_fn=tf.nn.relu, trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob,\n is_training=trainable)\n logits = layers.fully_connected(out, self._num_labels,\n trainable=trainable)\n return logits\n\n def _build_model(self):\n self.x_ = tf.placeholder(tf.float32, shape=[None, 3072], name='x_')\n x = tf.reshape(self.x_, [-1, 32, 32, 3], name='x')\n self.y = tf.placeholder(tf.float32, shape=[None, self._num_labels],\n name='y')\n self.lr = tf.placeholder(tf.float32, shape=(), name='lr')\n self.logits = self._build_net(x)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self\n .logits, labels=self.y)\n self.loss = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.MomentumOptimizer(self.lr, momentum=0.9,\n use_nesterov=True)\n self.train_op = optimizer.minimize(loss=self.loss)\n self.acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.logits, 1\n ), tf.argmax(self.y, 1)), dtype=tf.float32))\n self.val_logits = self._build_net(x, reuse=True, trainable=False)\n self.val_acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.\n val_logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32))\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.acc)\n self.merged = tf.summary.merge_all()\n", "step-5": "import tensorflow as tf\nimport numpy as np\nimport tensorflow.contrib.layers as layers\n\nclass Model(object):\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope=\"model\"):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n self._num_labels = num_labels\n self._scope = scope\n self._keep_prob = keep_prob\n self._conv_hidden_dims = [192, 192]\n with tf.variable_scope(self._scope):\n self._build_model()\n\n def _build_net(self, x, reuse=False, trainable=True, scope=\"inference_net\"):\n with tf.variable_scope(scope, reuse=reuse):\n out = x\n for i in range(len(self._conv_hidden_dims)):\n out = layers.conv2d(out, num_outputs=self._conv_hidden_dims[i], kernel_size=(5, 5),\n activation_fn=tf.nn.relu, trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob, is_training=trainable)\n out = layers.max_pool2d(out, kernel_size=(2, 2))\n\n out = layers.flatten(out)\n out = layers.fully_connected(out, num_outputs=1000, activation_fn=tf.nn.relu, trainable=trainable)\n out = layers.dropout(out, keep_prob=self._keep_prob, is_training=trainable)\n logits = layers.fully_connected(out, self._num_labels, trainable=trainable)\n\n return logits\n\n def _build_model(self):\n self.x_ = tf.placeholder(tf.float32, shape=[None, 3072], name='x_') # data gets loaded as a 32x32 vector\n x = tf.reshape(self.x_, [-1, 32, 32, 3], name='x') # CIFAR dataset is shape 32,32,3\n self.y = tf.placeholder(tf.float32, shape=[None, self._num_labels], name='y') # 10 labels\n # self.keep_prob = tf.placeholder(tf.float32, name='dropout_prob')\n self.lr = tf.placeholder(tf.float32, shape=(), name='lr')\n\n self.logits = self._build_net(x)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.y)\n self.loss = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.MomentumOptimizer(self.lr, momentum=0.9, use_nesterov=True)\n self.train_op = optimizer.minimize(loss=self.loss)\n self.acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32))\n\n # for eval steps\n self.val_logits = self._build_net(x, reuse=True, trainable=False)\n self.val_acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.val_logits, 1), tf.argmax(self.y, 1)), dtype=tf.float32))\n\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('accuracy', self.acc)\n self.merged = tf.summary.merge_all()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
import cv2 import numpy as np import time from dronekit import connect, VehicleMode connection_string = "/dev/ttyACM0" baud_rate = 115200 print(">>>> Connecting with the UAV <<<<") vehicle = connect(connection_string, baud=baud_rate, wait_ready=True) vehicle.wait_ready('autopilot_version') print('ready') cap = cv2.VideoCapture(0) if (cap.isOpened() == False): print("Unable to read camera feed") frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) t = str(time.time()) out = cv2.VideoWriter(t+'.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height)) while(True): posdata = str(vehicle.location.global_relative_frame).split(':') _, _, alt = posdata[1].split(',') ret, frame = cap.read() cv2.putText(frame, str(alt),(0,int(frame_height/2.1)),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1) if ret == True: print("record..") out.write(frame) #cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows()
normal
{ "blob_id": "8c11463e35fb32949abbb163a89f874040a33ad0", "index": 5415, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('>>>> Connecting with the UAV <<<<')\n<mask token>\nvehicle.wait_ready('autopilot_version')\nprint('ready')\n<mask token>\nif cap.isOpened() == False:\n print('Unable to read camera feed')\n<mask token>\nwhile True:\n posdata = str(vehicle.location.global_relative_frame).split(':')\n _, _, alt = posdata[1].split(',')\n ret, frame = cap.read()\n cv2.putText(frame, str(alt), (0, int(frame_height / 2.1)), cv2.\n FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)\n if ret == True:\n print('record..')\n out.write(frame)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n break\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n", "step-3": "<mask token>\nconnection_string = '/dev/ttyACM0'\nbaud_rate = 115200\nprint('>>>> Connecting with the UAV <<<<')\nvehicle = connect(connection_string, baud=baud_rate, wait_ready=True)\nvehicle.wait_ready('autopilot_version')\nprint('ready')\ncap = cv2.VideoCapture(0)\nif cap.isOpened() == False:\n print('Unable to read camera feed')\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\nt = str(time.time())\nout = cv2.VideoWriter(t + '.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'\n ), 10, (frame_width, frame_height))\nwhile True:\n posdata = str(vehicle.location.global_relative_frame).split(':')\n _, _, alt = posdata[1].split(',')\n ret, frame = cap.read()\n cv2.putText(frame, str(alt), (0, int(frame_height / 2.1)), cv2.\n FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)\n if ret == True:\n print('record..')\n out.write(frame)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n break\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n", "step-4": "import cv2\nimport numpy as np\nimport time\nfrom dronekit import connect, VehicleMode\nconnection_string = '/dev/ttyACM0'\nbaud_rate = 115200\nprint('>>>> Connecting with the UAV <<<<')\nvehicle = connect(connection_string, baud=baud_rate, wait_ready=True)\nvehicle.wait_ready('autopilot_version')\nprint('ready')\ncap = cv2.VideoCapture(0)\nif cap.isOpened() == False:\n print('Unable to read camera feed')\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\nt = str(time.time())\nout = cv2.VideoWriter(t + '.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'\n ), 10, (frame_width, frame_height))\nwhile True:\n posdata = str(vehicle.location.global_relative_frame).split(':')\n _, _, alt = posdata[1].split(',')\n ret, frame = cap.read()\n cv2.putText(frame, str(alt), (0, int(frame_height / 2.1)), cv2.\n FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)\n if ret == True:\n print('record..')\n out.write(frame)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n break\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n", "step-5": "import cv2\nimport numpy as np\nimport time \nfrom dronekit import connect, VehicleMode\n\nconnection_string = \"/dev/ttyACM0\"\nbaud_rate = 115200\nprint(\">>>> Connecting with the UAV <<<<\")\nvehicle = connect(connection_string, baud=baud_rate, wait_ready=True)\nvehicle.wait_ready('autopilot_version')\nprint('ready')\n\ncap = cv2.VideoCapture(0)\n \nif (cap.isOpened() == False): \n print(\"Unable to read camera feed\")\n\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\nt = str(time.time())\nout = cv2.VideoWriter(t+'.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))\n \nwhile(True):\n posdata = str(vehicle.location.global_relative_frame).split(':')\n _, _, alt = posdata[1].split(',')\n ret, frame = cap.read()\n cv2.putText(frame, str(alt),(0,int(frame_height/2.1)),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)\n if ret == True: \n print(\"record..\")\n out.write(frame)\n #cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break \ncap.release()\nout.release()\ncv2.destroyAllWindows() \n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import numpy as np import scipy.signal as sp from common import * class Processor: def __init__(self, sr, **kwargs): self.samprate = float(sr) self.hopSize = kwargs.get("hopSize", roundUpToPowerOf2(self.samprate * 0.005)) self.olaFac = int(kwargs.get("olaFac", 2)) def analyze(self, x): assert(self.olaFac > 0) # constant nX = len(x) nHop = getNFrame(nX, self.hopSize) nFrame = nHop * self.olaFac nBin = self.hopSize + 1 windowFunc, B, windowMean = getWindow("hanning") windowSize = 2 * self.hopSize halfWindowSize = self.hopSize window = np.sqrt(windowFunc(windowSize)) windowNormFac = 2.0 / (windowMean * windowSize) # do calculate magnList = np.zeros((nFrame, nBin), dtype = np.float64) phaseList = np.zeros((nFrame, nBin), dtype = np.float64) for iFrame in range(nFrame): frame = getFrame(x, iFrame * self.hopSize // self.olaFac, windowSize) frame *= window tSig = np.zeros(windowSize, dtype = np.float64) tSig[:halfWindowSize] = frame[halfWindowSize:] tSig[-halfWindowSize:] = frame[:halfWindowSize] fSig = np.fft.rfft(tSig) magnList[iFrame] = np.abs(fSig) * windowNormFac phaseList[iFrame] = np.unwrap(np.angle(fSig)) return magnList, phaseList def synth(self, *args): # constant nFrame, nBin = args[0].shape nHop = nFrame // self.olaFac nOut = nHop * self.hopSize windowFunc, B, windowMean = getWindow("hanning") windowSize = 2 * self.hopSize halfWindowSize = self.hopSize window = np.sqrt(windowFunc(windowSize)) # check input assert(nBin == self.hopSize + 1) # synth out = np.zeros(nOut, dtype = np.float64) if(len(args) == 1): fSigList = args[0] elif(len(args) == 2): fSigList = magnPhaseToFSig(*args) else: raise ValueError("Bad input.") fSigList *= halfWindowSize for iFrame in range(nFrame): tSig = np.fft.irfft(fSigList[iFrame]) ob, oe, ib, ie = getFrameRange(nOut, iFrame * self.hopSize // self.olaFac, windowSize) out[ib:ie] += (tSig * window)[ob:oe] out /= self.olaFac return out
normal
{ "blob_id": "e0075e4afafba9da70bbcb2ee073b5c1f7782d7d", "index": 6032, "step-1": "<mask token>\n\n\nclass Processor:\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Processor:\n <mask token>\n <mask token>\n\n def synth(self, *args):\n nFrame, nBin = args[0].shape\n nHop = nFrame // self.olaFac\n nOut = nHop * self.hopSize\n windowFunc, B, windowMean = getWindow('hanning')\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n assert nBin == self.hopSize + 1\n out = np.zeros(nOut, dtype=np.float64)\n if len(args) == 1:\n fSigList = args[0]\n elif len(args) == 2:\n fSigList = magnPhaseToFSig(*args)\n else:\n raise ValueError('Bad input.')\n fSigList *= halfWindowSize\n for iFrame in range(nFrame):\n tSig = np.fft.irfft(fSigList[iFrame])\n ob, oe, ib, ie = getFrameRange(nOut, iFrame * self.hopSize //\n self.olaFac, windowSize)\n out[ib:ie] += (tSig * window)[ob:oe]\n out /= self.olaFac\n return out\n", "step-3": "<mask token>\n\n\nclass Processor:\n\n def __init__(self, sr, **kwargs):\n self.samprate = float(sr)\n self.hopSize = kwargs.get('hopSize', roundUpToPowerOf2(self.\n samprate * 0.005))\n self.olaFac = int(kwargs.get('olaFac', 2))\n\n def analyze(self, x):\n assert self.olaFac > 0\n nX = len(x)\n nHop = getNFrame(nX, self.hopSize)\n nFrame = nHop * self.olaFac\n nBin = self.hopSize + 1\n windowFunc, B, windowMean = getWindow('hanning')\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n windowNormFac = 2.0 / (windowMean * windowSize)\n magnList = np.zeros((nFrame, nBin), dtype=np.float64)\n phaseList = np.zeros((nFrame, nBin), dtype=np.float64)\n for iFrame in range(nFrame):\n frame = getFrame(x, iFrame * self.hopSize // self.olaFac,\n windowSize)\n frame *= window\n tSig = np.zeros(windowSize, dtype=np.float64)\n tSig[:halfWindowSize] = frame[halfWindowSize:]\n tSig[-halfWindowSize:] = frame[:halfWindowSize]\n fSig = np.fft.rfft(tSig)\n magnList[iFrame] = np.abs(fSig) * windowNormFac\n phaseList[iFrame] = np.unwrap(np.angle(fSig))\n return magnList, phaseList\n\n def synth(self, *args):\n nFrame, nBin = args[0].shape\n nHop = nFrame // self.olaFac\n nOut = nHop * self.hopSize\n windowFunc, B, windowMean = getWindow('hanning')\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n assert nBin == self.hopSize + 1\n out = np.zeros(nOut, dtype=np.float64)\n if len(args) == 1:\n fSigList = args[0]\n elif len(args) == 2:\n fSigList = magnPhaseToFSig(*args)\n else:\n raise ValueError('Bad input.')\n fSigList *= halfWindowSize\n for iFrame in range(nFrame):\n tSig = np.fft.irfft(fSigList[iFrame])\n ob, oe, ib, ie = getFrameRange(nOut, iFrame * self.hopSize //\n self.olaFac, windowSize)\n out[ib:ie] += (tSig * window)[ob:oe]\n out /= self.olaFac\n return out\n", "step-4": "import numpy as np\nimport scipy.signal as sp\nfrom common import *\n\n\nclass Processor:\n\n def __init__(self, sr, **kwargs):\n self.samprate = float(sr)\n self.hopSize = kwargs.get('hopSize', roundUpToPowerOf2(self.\n samprate * 0.005))\n self.olaFac = int(kwargs.get('olaFac', 2))\n\n def analyze(self, x):\n assert self.olaFac > 0\n nX = len(x)\n nHop = getNFrame(nX, self.hopSize)\n nFrame = nHop * self.olaFac\n nBin = self.hopSize + 1\n windowFunc, B, windowMean = getWindow('hanning')\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n windowNormFac = 2.0 / (windowMean * windowSize)\n magnList = np.zeros((nFrame, nBin), dtype=np.float64)\n phaseList = np.zeros((nFrame, nBin), dtype=np.float64)\n for iFrame in range(nFrame):\n frame = getFrame(x, iFrame * self.hopSize // self.olaFac,\n windowSize)\n frame *= window\n tSig = np.zeros(windowSize, dtype=np.float64)\n tSig[:halfWindowSize] = frame[halfWindowSize:]\n tSig[-halfWindowSize:] = frame[:halfWindowSize]\n fSig = np.fft.rfft(tSig)\n magnList[iFrame] = np.abs(fSig) * windowNormFac\n phaseList[iFrame] = np.unwrap(np.angle(fSig))\n return magnList, phaseList\n\n def synth(self, *args):\n nFrame, nBin = args[0].shape\n nHop = nFrame // self.olaFac\n nOut = nHop * self.hopSize\n windowFunc, B, windowMean = getWindow('hanning')\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n assert nBin == self.hopSize + 1\n out = np.zeros(nOut, dtype=np.float64)\n if len(args) == 1:\n fSigList = args[0]\n elif len(args) == 2:\n fSigList = magnPhaseToFSig(*args)\n else:\n raise ValueError('Bad input.')\n fSigList *= halfWindowSize\n for iFrame in range(nFrame):\n tSig = np.fft.irfft(fSigList[iFrame])\n ob, oe, ib, ie = getFrameRange(nOut, iFrame * self.hopSize //\n self.olaFac, windowSize)\n out[ib:ie] += (tSig * window)[ob:oe]\n out /= self.olaFac\n return out\n", "step-5": "import numpy as np\nimport scipy.signal as sp\n\nfrom common import *\n\nclass Processor:\n def __init__(self, sr, **kwargs):\n self.samprate = float(sr)\n self.hopSize = kwargs.get(\"hopSize\", roundUpToPowerOf2(self.samprate * 0.005))\n self.olaFac = int(kwargs.get(\"olaFac\", 2))\n\n def analyze(self, x):\n assert(self.olaFac > 0)\n # constant\n nX = len(x)\n nHop = getNFrame(nX, self.hopSize)\n nFrame = nHop * self.olaFac\n nBin = self.hopSize + 1\n windowFunc, B, windowMean = getWindow(\"hanning\")\n\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n windowNormFac = 2.0 / (windowMean * windowSize)\n\n # do calculate\n magnList = np.zeros((nFrame, nBin), dtype = np.float64)\n phaseList = np.zeros((nFrame, nBin), dtype = np.float64)\n for iFrame in range(nFrame):\n frame = getFrame(x, iFrame * self.hopSize // self.olaFac, windowSize)\n frame *= window\n\n tSig = np.zeros(windowSize, dtype = np.float64)\n tSig[:halfWindowSize] = frame[halfWindowSize:]\n tSig[-halfWindowSize:] = frame[:halfWindowSize]\n fSig = np.fft.rfft(tSig)\n magnList[iFrame] = np.abs(fSig) * windowNormFac\n phaseList[iFrame] = np.unwrap(np.angle(fSig))\n return magnList, phaseList\n\n def synth(self, *args):\n # constant\n nFrame, nBin = args[0].shape\n nHop = nFrame // self.olaFac\n nOut = nHop * self.hopSize\n\n windowFunc, B, windowMean = getWindow(\"hanning\")\n windowSize = 2 * self.hopSize\n halfWindowSize = self.hopSize\n window = np.sqrt(windowFunc(windowSize))\n\n # check input\n assert(nBin == self.hopSize + 1)\n\n # synth\n out = np.zeros(nOut, dtype = np.float64)\n if(len(args) == 1):\n fSigList = args[0]\n elif(len(args) == 2):\n fSigList = magnPhaseToFSig(*args)\n else:\n raise ValueError(\"Bad input.\")\n\n fSigList *= halfWindowSize\n for iFrame in range(nFrame):\n tSig = np.fft.irfft(fSigList[iFrame])\n ob, oe, ib, ie = getFrameRange(nOut, iFrame * self.hopSize // self.olaFac, windowSize)\n out[ib:ie] += (tSig * window)[ob:oe]\n out /= self.olaFac\n return out\n", "step-ids": [ 1, 2, 4, 5, 6 ] }
[ 1, 2, 4, 5, 6 ]
t3 = float(input('Digite um numero: ')) print('o dobro deste numero é', t3 * 2) print('O triplo deste numero é', t3 * 3) print('E a raiz quadrada deste numero é', t3 ** (1 / 2))
normal
{ "blob_id": "005ea8a1e75447b2b1c030a645bde5d0cdc8fb53", "index": 3532, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('o dobro deste numero é', t3 * 2)\nprint('O triplo deste numero é', t3 * 3)\nprint('E a raiz quadrada deste numero é', t3 ** (1 / 2))\n", "step-3": "t3 = float(input('Digite um numero: '))\nprint('o dobro deste numero é', t3 * 2)\nprint('O triplo deste numero é', t3 * 3)\nprint('E a raiz quadrada deste numero é', t3 ** (1 / 2))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from scipy import misc from math import exp import tensorflow as tf import timeit import os dir_path = os.path.dirname(os.path.realpath(__file__)) IMAGE_WIDTH = 30 IMAGE_HEIGHT = 30 IMAGE_DEPTH = 3 IMAGE_PIXELS = IMAGE_WIDTH * IMAGE_HEIGHT def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def get_single_img(): file_path = dir_path+'/trunk_data_set/img_test/true_seg_cube/220.png' img = misc.imread(file_path) print "the inpute image shape: ", img.shape return img def conv_net(x, W_conv1, b_conv1, W_conv2, b_conv2, W_fc1, b_fc1, W_fc2, b_fc2): # first convolutional leyer x_image = tf.reshape(x, [-1,30,30,3]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # second convolutional leyer h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # third leyer h_pool2_flat = tf.reshape(h_pool2, [-1, 8*8*60]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # drop out h_fc1_drop = tf.nn.dropout(h_fc1, 1.0) # rool out leyer out = tf.add(tf.matmul(h_fc1_drop, W_fc2) , b_fc2) return out config = tf.ConfigProto( device_count = {'GPU': 0} ) with tf.Session(config=config) as sess1: image_input = get_single_img() saver = tf.train.import_meta_graph('learned_model/model.ckpt.meta') saver.restore(sess1,"learned_model/model.ckpt") start = timeit.default_timer() #print("Model restored.") #print tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) W_conv1 = [v for v in tf.trainable_variables() if v.name == "Variable:0"][0] b_conv1 = [v for v in tf.trainable_variables() if v.name == "Variable_1:0"][0] W_conv2 = [v for v in tf.trainable_variables() if v.name == "Variable_2:0"][0] b_conv2 = [v for v in tf.trainable_variables() if v.name == "Variable_3:0"][0] W_fc1 = [v for v in tf.trainable_variables() if v.name == "Variable_4:0"][0] b_fc1 = [v for v in tf.trainable_variables() if v.name == "Variable_5:0"][0] W_fc2 = [v for v in tf.trainable_variables() if v.name == "Variable_6:0"][0] b_fc2 = [v for v in tf.trainable_variables() if v.name == "Variable_7:0"][0] img2 = tf.convert_to_tensor(image_input) img2 = tf.reshape( img2, [ IMAGE_PIXELS * IMAGE_DEPTH ] ) img2.set_shape( [ IMAGE_PIXELS * IMAGE_DEPTH ] ) image_input = tf.cast( img2, tf.float32 ) * ( 1. / 255 ) - 0.5 y = conv_net(image_input,W_conv1, b_conv1, W_conv2, b_conv2, W_fc1, b_fc1, W_fc2, b_fc2) stop = timeit.default_timer() print "There is no trunk with %f probablity" % (1/(1+exp(-y.eval()[0][1]))) print "There is a trunk with %f probablity" % (1/(1+exp(-y.eval()[0][0]))) print "calculation time :", stop - start
normal
{ "blob_id": "8b4bd2d267f20775ee5d41f7fe9ef6f6eeab5bb0", "index": 2516, "step-1": "from scipy import misc\nfrom math import exp\nimport tensorflow as tf\nimport timeit\nimport os \n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\nIMAGE_WIDTH = 30\nIMAGE_HEIGHT = 30\nIMAGE_DEPTH = 3\nIMAGE_PIXELS = IMAGE_WIDTH * IMAGE_HEIGHT\n\n\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\ndef get_single_img():\n file_path = dir_path+'/trunk_data_set/img_test/true_seg_cube/220.png' \n img = misc.imread(file_path)\n print \"the inpute image shape: \", img.shape\n return img\n\n\ndef conv_net(x, W_conv1, b_conv1, W_conv2, b_conv2, W_fc1, b_fc1, W_fc2, b_fc2):\n # first convolutional leyer\n x_image = tf.reshape(x, [-1,30,30,3])\n\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n h_pool1 = max_pool_2x2(h_conv1)\n\n # second convolutional leyer\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n\n # third leyer\n\n h_pool2_flat = tf.reshape(h_pool2, [-1, 8*8*60])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n # drop out\n h_fc1_drop = tf.nn.dropout(h_fc1, 1.0)\n\n # rool out leyer\n out = tf.add(tf.matmul(h_fc1_drop, W_fc2) , b_fc2)\t\n return out \n\n\nconfig = tf.ConfigProto( device_count = {'GPU': 0} )\n\n\nwith tf.Session(config=config) as sess1:\n \n image_input = get_single_img() \n\n saver = tf.train.import_meta_graph('learned_model/model.ckpt.meta')\n saver.restore(sess1,\"learned_model/model.ckpt\")\n\n start = timeit.default_timer()\n \n #print(\"Model restored.\")\n #print tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n \n\n\n \n W_conv1 = [v for v in tf.trainable_variables() if v.name == \"Variable:0\"][0]\n\n b_conv1 = [v for v in tf.trainable_variables() if v.name == \"Variable_1:0\"][0]\n \n W_conv2 = [v for v in tf.trainable_variables() if v.name == \"Variable_2:0\"][0]\n\n b_conv2 = [v for v in tf.trainable_variables() if v.name == \"Variable_3:0\"][0]\n \n W_fc1 = [v for v in tf.trainable_variables() if v.name == \"Variable_4:0\"][0]\n \n b_fc1 = [v for v in tf.trainable_variables() if v.name == \"Variable_5:0\"][0]\n \n W_fc2 = [v for v in tf.trainable_variables() if v.name == \"Variable_6:0\"][0]\n \n b_fc2 = [v for v in tf.trainable_variables() if v.name == \"Variable_7:0\"][0]\t\n\n\n img2 = tf.convert_to_tensor(image_input)\n img2 = tf.reshape( img2, [ IMAGE_PIXELS * IMAGE_DEPTH ] )\n img2.set_shape( [ IMAGE_PIXELS * IMAGE_DEPTH ] )\n\n image_input = tf.cast( img2, tf.float32 ) * ( 1. / 255 ) - 0.5\n \n y = conv_net(image_input,W_conv1, b_conv1, W_conv2, b_conv2, W_fc1, b_fc1, W_fc2, b_fc2)\n\n stop = timeit.default_timer()\n\n print \"There is no trunk with %f probablity\" % (1/(1+exp(-y.eval()[0][1])))\n\n print \"There is a trunk with %f probablity\" % (1/(1+exp(-y.eval()[0][0])))\n \n print \"calculation time :\", stop - start\t\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import pytest from dymopy.client import Dymo from dymopy.client import make_xml, make_params def test_url(): dymo = Dymo() assert dymo.uri == "https://127.0.0.1:41951/DYMO/DLS/Printing" def test_status(): dymo = Dymo() status = dymo.get_status() assert isinstance(status, dict) assert status['status_code'] == 200 def test_printer_name(): dymo = Dymo() printer = dymo.get_printer() assert isinstance(printer, dict) assert printer['status_code'] == 200 def test_xml(): label_params = make_params() label_xml = make_xml("This is working?") def test_printer_job(): dymo = Dymo() label_params = make_params() label_xml = make_xml('Hello', 'World!') # print_resp = dymo.print(label_xml=label_xml, label_params=label_params) # assert print_resp.status_code == 200
normal
{ "blob_id": "766098753ec579e2d63893fcbd94e8819b46bc0b", "index": 6867, "step-1": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\n<mask token>\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-2": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\n<mask token>\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-3": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\ndef test_xml():\n label_params = make_params()\n label_xml = make_xml('This is working?')\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-4": "import pytest\nfrom dymopy.client import Dymo\nfrom dymopy.client import make_xml, make_params\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\ndef test_xml():\n label_params = make_params()\n label_xml = make_xml('This is working?')\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-5": "import pytest \nfrom dymopy.client import Dymo\nfrom dymopy.client import make_xml, make_params \n\ndef test_url(): \n dymo = Dymo()\n assert dymo.uri == \"https://127.0.0.1:41951/DYMO/DLS/Printing\"\n\ndef test_status(): \n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\ndef test_printer_name(): \n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\ndef test_xml(): \n label_params = make_params()\n label_xml = make_xml(\"This is working?\")\n \n\ndef test_printer_job(): \n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n \n # print_resp = dymo.print(label_xml=label_xml, label_params=label_params)\n # assert print_resp.status_code == 200\n \n ", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import argparse import subprocess import os def get_files(dir_path, ext='.png'): relative_paths = os.listdir(dir_path) relative_paths = list(filter(lambda fp: ext in fp, relative_paths)) return list(map(lambda rel_p: os.path.join(dir_path, rel_p), relative_paths)) def ipfs_add_local(file_path): 'Returns CID' proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True, text=True) stdout = proc.stdout try: return stdout.split()[1] except IndexError as e: print(e) print(stdout) return "" def pin_with_pinata(cid, name): proc = subprocess.run(['ipfs', 'pin', 'remote', 'add', '--service=pinata', f'--name={name}', str(cid)], capture_output=True, text=True) print(f'Uploaded cid: {cid}') # print(proc.stdout) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Batch IPFS file uploading') parser.add_argument('-i', '--input', help='Path to directory containing media to upload', required=True) args = vars(parser.parse_args()) files_to_upload = get_files(args['input']) info = {} for fp in files_to_upload: print(fp) cid = ipfs_add_local(fp) if cid == "": print(f'{fp} failed to upload!') continue name = os.path.basename(fp) info[name] = {'cid': cid} pin_with_pinata(cid, name) with open(f'{args["input"]}/result.csv', 'w') as f: for fn in sorted(info.keys()): cid = info[fn]['cid'] f.write(f'{fn}, {cid}\n') f.close()
normal
{ "blob_id": "7ca88d451ad702e5a8e532da3e3f5939cfaa7215", "index": 9571, "step-1": "<mask token>\n\n\ndef ipfs_add_local(file_path):\n \"\"\"Returns CID\"\"\"\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True,\n text=True)\n stdout = proc.stdout\n try:\n return stdout.split()[1]\n except IndexError as e:\n print(e)\n print(stdout)\n return ''\n\n\ndef pin_with_pinata(cid, name):\n proc = subprocess.run(['ipfs', 'pin', 'remote', 'add',\n '--service=pinata', f'--name={name}', str(cid)], capture_output=\n True, text=True)\n print(f'Uploaded cid: {cid}')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_files(dir_path, ext='.png'):\n relative_paths = os.listdir(dir_path)\n relative_paths = list(filter(lambda fp: ext in fp, relative_paths))\n return list(map(lambda rel_p: os.path.join(dir_path, rel_p),\n relative_paths))\n\n\ndef ipfs_add_local(file_path):\n \"\"\"Returns CID\"\"\"\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True,\n text=True)\n stdout = proc.stdout\n try:\n return stdout.split()[1]\n except IndexError as e:\n print(e)\n print(stdout)\n return ''\n\n\ndef pin_with_pinata(cid, name):\n proc = subprocess.run(['ipfs', 'pin', 'remote', 'add',\n '--service=pinata', f'--name={name}', str(cid)], capture_output=\n True, text=True)\n print(f'Uploaded cid: {cid}')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_files(dir_path, ext='.png'):\n relative_paths = os.listdir(dir_path)\n relative_paths = list(filter(lambda fp: ext in fp, relative_paths))\n return list(map(lambda rel_p: os.path.join(dir_path, rel_p),\n relative_paths))\n\n\ndef ipfs_add_local(file_path):\n \"\"\"Returns CID\"\"\"\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True,\n text=True)\n stdout = proc.stdout\n try:\n return stdout.split()[1]\n except IndexError as e:\n print(e)\n print(stdout)\n return ''\n\n\ndef pin_with_pinata(cid, name):\n proc = subprocess.run(['ipfs', 'pin', 'remote', 'add',\n '--service=pinata', f'--name={name}', str(cid)], capture_output=\n True, text=True)\n print(f'Uploaded cid: {cid}')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Batch IPFS file uploading')\n parser.add_argument('-i', '--input', help=\n 'Path to directory containing media to upload', required=True)\n args = vars(parser.parse_args())\n files_to_upload = get_files(args['input'])\n info = {}\n for fp in files_to_upload:\n print(fp)\n cid = ipfs_add_local(fp)\n if cid == '':\n print(f'{fp} failed to upload!')\n continue\n name = os.path.basename(fp)\n info[name] = {'cid': cid}\n pin_with_pinata(cid, name)\n with open(f\"{args['input']}/result.csv\", 'w') as f:\n for fn in sorted(info.keys()):\n cid = info[fn]['cid']\n f.write(f'{fn}, {cid}\\n')\n f.close()\n", "step-4": "import argparse\nimport subprocess\nimport os\n\n\ndef get_files(dir_path, ext='.png'):\n relative_paths = os.listdir(dir_path)\n relative_paths = list(filter(lambda fp: ext in fp, relative_paths))\n return list(map(lambda rel_p: os.path.join(dir_path, rel_p),\n relative_paths))\n\n\ndef ipfs_add_local(file_path):\n \"\"\"Returns CID\"\"\"\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True,\n text=True)\n stdout = proc.stdout\n try:\n return stdout.split()[1]\n except IndexError as e:\n print(e)\n print(stdout)\n return ''\n\n\ndef pin_with_pinata(cid, name):\n proc = subprocess.run(['ipfs', 'pin', 'remote', 'add',\n '--service=pinata', f'--name={name}', str(cid)], capture_output=\n True, text=True)\n print(f'Uploaded cid: {cid}')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Batch IPFS file uploading')\n parser.add_argument('-i', '--input', help=\n 'Path to directory containing media to upload', required=True)\n args = vars(parser.parse_args())\n files_to_upload = get_files(args['input'])\n info = {}\n for fp in files_to_upload:\n print(fp)\n cid = ipfs_add_local(fp)\n if cid == '':\n print(f'{fp} failed to upload!')\n continue\n name = os.path.basename(fp)\n info[name] = {'cid': cid}\n pin_with_pinata(cid, name)\n with open(f\"{args['input']}/result.csv\", 'w') as f:\n for fn in sorted(info.keys()):\n cid = info[fn]['cid']\n f.write(f'{fn}, {cid}\\n')\n f.close()\n", "step-5": "import argparse\nimport subprocess\nimport os\n\n\ndef get_files(dir_path, ext='.png'):\n relative_paths = os.listdir(dir_path)\n relative_paths = list(filter(lambda fp: ext in fp, relative_paths))\n return list(map(lambda rel_p: os.path.join(dir_path, rel_p), relative_paths))\n\n\ndef ipfs_add_local(file_path):\n 'Returns CID'\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True, text=True)\n stdout = proc.stdout\n try:\n return stdout.split()[1]\n except IndexError as e:\n print(e)\n print(stdout)\n return \"\"\n\n\ndef pin_with_pinata(cid, name):\n proc = subprocess.run(['ipfs', 'pin', 'remote', 'add', '--service=pinata', f'--name={name}', str(cid)], capture_output=True, text=True)\n print(f'Uploaded cid: {cid}')\n # print(proc.stdout)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Batch IPFS file uploading')\n parser.add_argument('-i', '--input', help='Path to directory containing media to upload', required=True)\n args = vars(parser.parse_args())\n\n files_to_upload = get_files(args['input'])\n\n info = {}\n\n for fp in files_to_upload:\n print(fp)\n cid = ipfs_add_local(fp)\n if cid == \"\":\n print(f'{fp} failed to upload!')\n continue\n name = os.path.basename(fp)\n info[name] = {'cid': cid}\n\n pin_with_pinata(cid, name)\n\n with open(f'{args[\"input\"]}/result.csv', 'w') as f:\n for fn in sorted(info.keys()):\n cid = info[fn]['cid']\n f.write(f'{fn}, {cid}\\n')\n\n f.close()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
x=input("Do you really want to run this program? (y/n) : ") x=x.upper() if x=="Y" or x=="N" or x=="Q": while x=="Y" or x=="N" or x=="Q": if x=="Q": print("Exiting the Program") import sys sys.exit() elif x=="N": print("You decided to leave. See you again!” ") break #elif x=="Y": #You can run the program.Enter the code required to run the program else: print("Invalid selection is entered")
normal
{ "blob_id": "7dff15a16ecc3ce3952f4b47290393ea3183807f", "index": 4414, "step-1": "<mask token>\n", "step-2": "<mask token>\nif x == 'Y' or x == 'N' or x == 'Q':\n while x == 'Y' or x == 'N' or x == 'Q':\n if x == 'Q':\n print('Exiting the Program')\n import sys\n sys.exit()\n elif x == 'N':\n print('You decided to leave. See you again!” ')\n break\nelse:\n print('Invalid selection is entered')\n", "step-3": "x = input('Do you really want to run this program? (y/n) : ')\nx = x.upper()\nif x == 'Y' or x == 'N' or x == 'Q':\n while x == 'Y' or x == 'N' or x == 'Q':\n if x == 'Q':\n print('Exiting the Program')\n import sys\n sys.exit()\n elif x == 'N':\n print('You decided to leave. See you again!” ')\n break\nelse:\n print('Invalid selection is entered')\n", "step-4": "x=input(\"Do you really want to run this program? (y/n) : \")\nx=x.upper()\n\nif x==\"Y\" or x==\"N\" or x==\"Q\":\n while x==\"Y\" or x==\"N\" or x==\"Q\":\n if x==\"Q\":\n print(\"Exiting the Program\")\n import sys\n sys.exit()\n elif x==\"N\":\n print(\"You decided to leave. See you again!” \")\n break\n #elif x==\"Y\":\n #You can run the program.Enter the code required to run the program\nelse:\n print(\"Invalid selection is entered\") \n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from functools import reduce with open("input.txt") as f: numbers = f.read().split("\n") n = sorted(list(map(lambda x: int(x), numbers))) n.insert(0, 0) n.append(n[-1] + 3) target = n[-1] memoize = {} def part2(number): if number == target: return 1 if number in memoize.keys(): return memoize[number] paths = 0 if number + 1 in n: paths += part2(number + 1) if number + 2 in n: paths += part2(number + 2) if number + 3 in n: paths += part2(number + 3) memoize[number] = paths print(number, paths) return paths print("Total:", part2(0))
normal
{ "blob_id": "3179c13968f7bcdccbd00ea35b9f098dc49b42d8", "index": 4450, "step-1": "<mask token>\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if number + 2 in n:\n paths += part2(number + 2)\n if number + 3 in n:\n paths += part2(number + 3)\n memoize[number] = paths\n print(number, paths)\n return paths\n\n\n<mask token>\n", "step-2": "<mask token>\nwith open('input.txt') as f:\n numbers = f.read().split('\\n')\n<mask token>\nn.insert(0, 0)\nn.append(n[-1] + 3)\n<mask token>\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if number + 2 in n:\n paths += part2(number + 2)\n if number + 3 in n:\n paths += part2(number + 3)\n memoize[number] = paths\n print(number, paths)\n return paths\n\n\nprint('Total:', part2(0))\n", "step-3": "<mask token>\nwith open('input.txt') as f:\n numbers = f.read().split('\\n')\nn = sorted(list(map(lambda x: int(x), numbers)))\nn.insert(0, 0)\nn.append(n[-1] + 3)\ntarget = n[-1]\nmemoize = {}\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if number + 2 in n:\n paths += part2(number + 2)\n if number + 3 in n:\n paths += part2(number + 3)\n memoize[number] = paths\n print(number, paths)\n return paths\n\n\nprint('Total:', part2(0))\n", "step-4": "from functools import reduce\nwith open('input.txt') as f:\n numbers = f.read().split('\\n')\nn = sorted(list(map(lambda x: int(x), numbers)))\nn.insert(0, 0)\nn.append(n[-1] + 3)\ntarget = n[-1]\nmemoize = {}\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if number + 2 in n:\n paths += part2(number + 2)\n if number + 3 in n:\n paths += part2(number + 3)\n memoize[number] = paths\n print(number, paths)\n return paths\n\n\nprint('Total:', part2(0))\n", "step-5": "from functools import reduce\n\nwith open(\"input.txt\") as f:\n numbers = f.read().split(\"\\n\")\n\nn = sorted(list(map(lambda x: int(x), numbers)))\nn.insert(0, 0)\nn.append(n[-1] + 3)\n\ntarget = n[-1]\n\nmemoize = {}\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if number + 2 in n:\n paths += part2(number + 2)\n if number + 3 in n:\n paths += part2(number + 3)\n memoize[number] = paths\n print(number, paths)\n return paths\n\n\nprint(\"Total:\", part2(0))\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from django.db import models class IssueManager(models.Manager): def open(self): return self.filter(status__is_closed=False) def closed(self): return self.filter(status__is_closed=True)
normal
{ "blob_id": "4c54cfefbaf90c1dd0648485e62bff1f2787ccfe", "index": 2784, "step-1": "<mask token>\n\n\nclass IssueManager(models.Manager):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass IssueManager(models.Manager):\n\n def open(self):\n return self.filter(status__is_closed=False)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass IssueManager(models.Manager):\n\n def open(self):\n return self.filter(status__is_closed=False)\n\n def closed(self):\n return self.filter(status__is_closed=True)\n", "step-4": "from django.db import models\n\n\nclass IssueManager(models.Manager):\n\n def open(self):\n return self.filter(status__is_closed=False)\n\n def closed(self):\n return self.filter(status__is_closed=True)\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
cassandra = {'nodes': ['localhost'], 'keyspace': 'coffee'}
normal
{ "blob_id": "0738fc48bc367f1df75567ab97ce20d3e747dc18", "index": 8897, "step-1": "<mask token>\n", "step-2": "cassandra = {'nodes': ['localhost'], 'keyspace': 'coffee'}\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# coding: utf-8 """ login.py ~~~~~~~~ 木犀官网登陆API """ from flask import jsonify, request from . import api from muxiwebsite.models import User from muxiwebsite import db @api.route('/login/', methods=['POST']) def login(): email = request.get_json().get("email") pwd = request.get_json().get("password") user = User.query.filter_by(email=email).first() if not user: return jsonify({}), 403 if not user.verify_password(pwd): return jsonify({}), 400 token = user.generate_auth_token() return jsonify ({ 'token': token, }), 200
normal
{ "blob_id": "a0dbb374f803cb05a35f823f54ef5f14eaf328b2", "index": 3688, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@api.route('/login/', methods=['POST'])\ndef login():\n email = request.get_json().get('email')\n pwd = request.get_json().get('password')\n user = User.query.filter_by(email=email).first()\n if not user:\n return jsonify({}), 403\n if not user.verify_password(pwd):\n return jsonify({}), 400\n token = user.generate_auth_token()\n return jsonify({'token': token}), 200\n", "step-3": "<mask token>\nfrom flask import jsonify, request\nfrom . import api\nfrom muxiwebsite.models import User\nfrom muxiwebsite import db\n\n\n@api.route('/login/', methods=['POST'])\ndef login():\n email = request.get_json().get('email')\n pwd = request.get_json().get('password')\n user = User.query.filter_by(email=email).first()\n if not user:\n return jsonify({}), 403\n if not user.verify_password(pwd):\n return jsonify({}), 400\n token = user.generate_auth_token()\n return jsonify({'token': token}), 200\n", "step-4": "# coding: utf-8\n\n\"\"\"\n login.py\n ~~~~~~~~\n\n 木犀官网登陆API\n\n\"\"\"\n\nfrom flask import jsonify, request\nfrom . import api\nfrom muxiwebsite.models import User\nfrom muxiwebsite import db\n\n@api.route('/login/', methods=['POST'])\ndef login():\n email = request.get_json().get(\"email\")\n pwd = request.get_json().get(\"password\")\n\n user = User.query.filter_by(email=email).first()\n if not user:\n return jsonify({}), 403\n if not user.verify_password(pwd):\n return jsonify({}), 400\n\n token = user.generate_auth_token()\n return jsonify ({\n 'token': token,\n }), 200\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
class Solution: def eventualSafeNodes(self, graph: List[List[int]]) ->List[int]: res = [] d = {} def dfs(node): if graph[node] == []: return True if node in d: return d[node] if node in visit: return False visit.add(node) for nei in graph[node]: if dfs(nei) == False: d[node] = False return False d[node] = True return True visit = set() for i in range(len(graph)): if dfs(i): res.append(i) return res
normal
{ "blob_id": "b815f72e2cad351fd9411361a0e7cc75d39ae826", "index": 9270, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def eventualSafeNodes(self, graph: List[List[int]]) ->List[int]:\n res = []\n d = {}\n\n def dfs(node):\n if graph[node] == []:\n return True\n if node in d:\n return d[node]\n if node in visit:\n return False\n visit.add(node)\n for nei in graph[node]:\n if dfs(nei) == False:\n d[node] = False\n return False\n d[node] = True\n return True\n visit = set()\n for i in range(len(graph)):\n if dfs(i):\n res.append(i)\n return res\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#!/usr/bin/env python """ Script that generates the photon efficiency curves and stores them in a root file. For the moment only the pT curves for the different eta bins are created """ import re import json import ROOT as r r.PyConfig.IgnoreCommandLineOptions = True import numpy as np import sympy as sp from utils.symbolic import func_cov from utils.graph_utils import get_lower_band, get_upper_band from common_func import get_name # Covariance matrix from the fit integrated over the whole eta range, where # alpha and beta were fixed. This will be used to calculate the correlation # coefficients between the fitted parameters, which will then be used to get # the uncertainty bands for the parametrization COVARIANCE = np.array([ [1.181e-06, 1.545e-06, -4.328e-06, 4.156e-06], [1.545e-06, 7.215e-06, -1.714e-05, 5.177e-06], [-4.328e-06, -1.714e-05, 4.228e-05, -1.481e-05], [4.156e-06, 5.177e-06, -1.481e-05, 1.506e-05], ]) # corr = diag(cov)^{-1/2} * cov * diag(cov)^{-1/2} CORRELATIONS = np.matmul( np.matmul( np.diag(1/np.sqrt(np.diag(COVARIANCE))), COVARIANCE, ), np.diag(1/np.sqrt(np.diag(COVARIANCE))) ) def eff_param_string(): """ The parametrization of the efficiencies from AN-2015-11 as a string that can be used in a TF1 constructor. p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3)))) """ return '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))' def eff_param(): """ Get the parametrization as ROOT.TF1 """ return r.TF1('photon_eff_param', eff_param_string(), 0, 7) def eff_param_sym(): """ Get the parametrization as sympy symbolic expression by doing some string manipulation on the parametrization and then using sympy.sympify """ param_str = eff_param_string() # replace call to ROOTs erf and give x[0] a parseable name param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x') # convert parameters from [x] notation to px notation param_str = re.sub(r'\[([0-9])\]', r'p\1', param_str) # replace pow(x, y) with x**y (pythonic) syntax param_str = re.sub(r'pow\((.*?)\s*?,\s*?([0-9])\)', r'\1**\2', param_str) return sp.sympify(param_str) def get_corr_subs_values(corr): """ Get the dictionary of substitution values for the correlation matrix """ subs_dict = {} n_dim = corr.shape[0] for irow in xrange(0, n_dim): for icol in xrange(irow + 1, n_dim): subs_dict['rho_p{}p{}'.format(irow, icol)] = corr[irow, icol] return subs_dict def get_cov_func(params, corr): """ Get the uncertainty function where only pT is left as a free parameter. This will return a python function that can be evaluated at any given point """ eff = eff_param_sym() # get the list of free parameters free_params = [] for sym in eff.free_symbols: if sym.name in params and params[sym.name][1] != 0: free_params.append(sym) # sort the parameters according to their name, such that the correlation # coefficients actually match free_params.sort(key=lambda x: int(x.name.replace('p', ''))) cov_eff = func_cov(eff, free_params) # build up the dictionary of symbol -> value that will be substituted. # In the end the returned function will only have one free parameter left subst_vals = { p: v[0] for p, v in params.iteritems() } subst_vals.update({ 'sigma_' + p: v[1] for p, v in params.iteritems() }) subst_vals.update( get_corr_subs_values(corr) ) # NOTE: here it is assumed that 'x' is the only free parameter left return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals)) def get_graph_err(params, corr, n_sigma=1.0, n_points=100): """ Get the function evaluated at n_points with uncertainties taking into account correlations between the parameters """ # central function eff_f = eff_param_sym() eff_f = eff_f.subs({p: v[0] for p, v in params.iteritems()}) # NOTE: assume that 'x' is the only free parameter left eff_f = sp.lambdify(sp.symbols('x'), eff_f) # uncertainty function (as function of pT) var_f = get_cov_func(params, corr) x_bins = np.linspace(0.4, 7, n_points + 1) x_cent = 0.5 * (x_bins[1:] + x_bins[:-1]) # bin centers x_err = np.diff(x_bins) # "uncertainties" in x y_cent = np.array([eff_f(x) for x in x_cent]) y_err = np.sqrt(np.array([var_f(x) for x in x_cent])) * n_sigma return r.TGraphErrors(len(x_cent), x_cent, y_cent, x_err, y_err) def set_params_errors(func, *params): """ Set all the parameters as pairs of value and uncertainty (in the order they) are in the params list. If uncertainty = 0, the parameter is fixed """ central = np.array([p[0] for p in params]) uncer = np.array([p[1] for p in params]) func.SetParameters(central) func.SetParErrors(uncer) for idx, err in enumerate(uncer): if err == 0: func.FixParameter(idx, func.GetParameter(idx)) def load_params(param_file): """ Load the parameter file and return the list of dicts stored in it """ with open(param_file, 'r') as pfile: eff_params = json.load(pfile) return eff_params def create_param(params, sigma_shift, uncorrelated): """ Create the function from the passed params and give it an appropriate name """ # if the central results are desired. Use the exact parametrization as TF1 if sigma_shift == 0: func = eff_param() set_params_errors(func, params["p0"], params["p1"], params["p2"], params["p3"], params["alpha"], params["beta"]) func.SetName(get_name(params["eta"], 'photon_eff_pt')) return func # else get an aproximation by evaluating the function at a given number of # points and determine the uncertainties at these points, then store the # points as a TGraph where the y-values are the central + uncertainty values # at each evaluation point # NOTE: Since eff_param_sym names alpha and beta p4 and p5 respectively # (can't use beta in an expression that goes through sympy.sympify), we have # to clone them here. We can leave the original values in, since they will # not be picked up by the substitution command params['p4'] = params['alpha'] params['p5'] = params['beta'] # use the global correlation matrix or an identity matrix if uncorrelated # parameters are desired corr = np.identity(4) if uncorrelated else CORRELATIONS graph = get_graph_err(params, corr, np.abs(sigma_shift), 200) if sigma_shift < 0: graph = get_lower_band(graph) else: graph = get_upper_band(graph) graph.SetName(get_name(params['eta'], 'photon_eff_pt')) return graph def main(args): """Main""" file_option = 'update' if args.update else 'recreate' outfile = r.TFile.Open(args.outfile, file_option) all_params = load_params(args.paramfile) for params in all_params: eff = create_param(params, args.sigma, args.uncorrelated) eff.Write() outfile.Close() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='script to generate TF1 ' 'photon efficiency parametrizations from ' 'json file holding the fit parameters') parser.add_argument('paramfile', help='json file containing the fitted ' 'parameters') parser.add_argument('-o', '--outfile', help='root file into which the TF1 ' 'should be stored', default='photon_effs_param.root') parser.add_argument('-u', '--update', help='update the output file instead ' 'of recreating it', default=False, action='store_true') parser.add_argument('-s', '--sigma', help='Use the central value + [sigma] ' '* uncertainty for each parameter', type=float, default=0) parser.add_argument('--uncorrelated', default=False, action='store_true', help='Assume that the free parameters are uncorrelated ' 'instead of using correlation parameters from a global ' 'fit') clargs = parser.parse_args() main(clargs)
normal
{ "blob_id": "fd450b5454b65ed69b411028788c587f9674760c", "index": 966, "step-1": "<mask token>\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3))))\n \"\"\"\n return (\n '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))'\n )\n\n\ndef eff_param():\n \"\"\"\n Get the parametrization as ROOT.TF1\n \"\"\"\n return r.TF1('photon_eff_param', eff_param_string(), 0, 7)\n\n\ndef eff_param_sym():\n \"\"\"\n Get the parametrization as sympy symbolic expression by doing some string\n manipulation on the parametrization and then using sympy.sympify\n \"\"\"\n param_str = eff_param_string()\n param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x')\n param_str = re.sub('\\\\[([0-9])\\\\]', 'p\\\\1', param_str)\n param_str = re.sub('pow\\\\((.*?)\\\\s*?,\\\\s*?([0-9])\\\\)', '\\\\1**\\\\2',\n param_str)\n return sp.sympify(param_str)\n\n\n<mask token>\n\n\ndef get_cov_func(params, corr):\n \"\"\"\n Get the uncertainty function where only pT is left as a free parameter.\n\n This will return a python function that can be evaluated at any given point\n \"\"\"\n eff = eff_param_sym()\n free_params = []\n for sym in eff.free_symbols:\n if sym.name in params and params[sym.name][1] != 0:\n free_params.append(sym)\n free_params.sort(key=lambda x: int(x.name.replace('p', '')))\n cov_eff = func_cov(eff, free_params)\n subst_vals = {p: v[0] for p, v in params.iteritems()}\n subst_vals.update({('sigma_' + p): v[1] for p, v in params.iteritems()})\n subst_vals.update(get_corr_subs_values(corr))\n return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals))\n\n\n<mask token>\n\n\ndef set_params_errors(func, *params):\n \"\"\"\n Set all the parameters as pairs of value and uncertainty (in the order they)\n are in the params list. If uncertainty = 0, the parameter is fixed\n \"\"\"\n central = np.array([p[0] for p in params])\n uncer = np.array([p[1] for p in params])\n func.SetParameters(central)\n func.SetParErrors(uncer)\n for idx, err in enumerate(uncer):\n if err == 0:\n func.FixParameter(idx, func.GetParameter(idx))\n\n\ndef load_params(param_file):\n \"\"\"\n Load the parameter file and return the list of dicts stored in it\n \"\"\"\n with open(param_file, 'r') as pfile:\n eff_params = json.load(pfile)\n return eff_params\n\n\ndef create_param(params, sigma_shift, uncorrelated):\n \"\"\"\n Create the function from the passed params and give it an appropriate name\n \"\"\"\n if sigma_shift == 0:\n func = eff_param()\n set_params_errors(func, params['p0'], params['p1'], params['p2'],\n params['p3'], params['alpha'], params['beta'])\n func.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return func\n params['p4'] = params['alpha']\n params['p5'] = params['beta']\n corr = np.identity(4) if uncorrelated else CORRELATIONS\n graph = get_graph_err(params, corr, np.abs(sigma_shift), 200)\n if sigma_shift < 0:\n graph = get_lower_band(graph)\n else:\n graph = get_upper_band(graph)\n graph.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return graph\n\n\ndef main(args):\n \"\"\"Main\"\"\"\n file_option = 'update' if args.update else 'recreate'\n outfile = r.TFile.Open(args.outfile, file_option)\n all_params = load_params(args.paramfile)\n for params in all_params:\n eff = create_param(params, args.sigma, args.uncorrelated)\n eff.Write()\n outfile.Close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3))))\n \"\"\"\n return (\n '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))'\n )\n\n\ndef eff_param():\n \"\"\"\n Get the parametrization as ROOT.TF1\n \"\"\"\n return r.TF1('photon_eff_param', eff_param_string(), 0, 7)\n\n\ndef eff_param_sym():\n \"\"\"\n Get the parametrization as sympy symbolic expression by doing some string\n manipulation on the parametrization and then using sympy.sympify\n \"\"\"\n param_str = eff_param_string()\n param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x')\n param_str = re.sub('\\\\[([0-9])\\\\]', 'p\\\\1', param_str)\n param_str = re.sub('pow\\\\((.*?)\\\\s*?,\\\\s*?([0-9])\\\\)', '\\\\1**\\\\2',\n param_str)\n return sp.sympify(param_str)\n\n\n<mask token>\n\n\ndef get_cov_func(params, corr):\n \"\"\"\n Get the uncertainty function where only pT is left as a free parameter.\n\n This will return a python function that can be evaluated at any given point\n \"\"\"\n eff = eff_param_sym()\n free_params = []\n for sym in eff.free_symbols:\n if sym.name in params and params[sym.name][1] != 0:\n free_params.append(sym)\n free_params.sort(key=lambda x: int(x.name.replace('p', '')))\n cov_eff = func_cov(eff, free_params)\n subst_vals = {p: v[0] for p, v in params.iteritems()}\n subst_vals.update({('sigma_' + p): v[1] for p, v in params.iteritems()})\n subst_vals.update(get_corr_subs_values(corr))\n return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals))\n\n\ndef get_graph_err(params, corr, n_sigma=1.0, n_points=100):\n \"\"\"\n Get the function evaluated at n_points with uncertainties taking into\n account correlations between the parameters\n \"\"\"\n eff_f = eff_param_sym()\n eff_f = eff_f.subs({p: v[0] for p, v in params.iteritems()})\n eff_f = sp.lambdify(sp.symbols('x'), eff_f)\n var_f = get_cov_func(params, corr)\n x_bins = np.linspace(0.4, 7, n_points + 1)\n x_cent = 0.5 * (x_bins[1:] + x_bins[:-1])\n x_err = np.diff(x_bins)\n y_cent = np.array([eff_f(x) for x in x_cent])\n y_err = np.sqrt(np.array([var_f(x) for x in x_cent])) * n_sigma\n return r.TGraphErrors(len(x_cent), x_cent, y_cent, x_err, y_err)\n\n\ndef set_params_errors(func, *params):\n \"\"\"\n Set all the parameters as pairs of value and uncertainty (in the order they)\n are in the params list. If uncertainty = 0, the parameter is fixed\n \"\"\"\n central = np.array([p[0] for p in params])\n uncer = np.array([p[1] for p in params])\n func.SetParameters(central)\n func.SetParErrors(uncer)\n for idx, err in enumerate(uncer):\n if err == 0:\n func.FixParameter(idx, func.GetParameter(idx))\n\n\ndef load_params(param_file):\n \"\"\"\n Load the parameter file and return the list of dicts stored in it\n \"\"\"\n with open(param_file, 'r') as pfile:\n eff_params = json.load(pfile)\n return eff_params\n\n\ndef create_param(params, sigma_shift, uncorrelated):\n \"\"\"\n Create the function from the passed params and give it an appropriate name\n \"\"\"\n if sigma_shift == 0:\n func = eff_param()\n set_params_errors(func, params['p0'], params['p1'], params['p2'],\n params['p3'], params['alpha'], params['beta'])\n func.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return func\n params['p4'] = params['alpha']\n params['p5'] = params['beta']\n corr = np.identity(4) if uncorrelated else CORRELATIONS\n graph = get_graph_err(params, corr, np.abs(sigma_shift), 200)\n if sigma_shift < 0:\n graph = get_lower_band(graph)\n else:\n graph = get_upper_band(graph)\n graph.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return graph\n\n\ndef main(args):\n \"\"\"Main\"\"\"\n file_option = 'update' if args.update else 'recreate'\n outfile = r.TFile.Open(args.outfile, file_option)\n all_params = load_params(args.paramfile)\n for params in all_params:\n eff = create_param(params, args.sigma, args.uncorrelated)\n eff.Write()\n outfile.Close()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3))))\n \"\"\"\n return (\n '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))'\n )\n\n\ndef eff_param():\n \"\"\"\n Get the parametrization as ROOT.TF1\n \"\"\"\n return r.TF1('photon_eff_param', eff_param_string(), 0, 7)\n\n\ndef eff_param_sym():\n \"\"\"\n Get the parametrization as sympy symbolic expression by doing some string\n manipulation on the parametrization and then using sympy.sympify\n \"\"\"\n param_str = eff_param_string()\n param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x')\n param_str = re.sub('\\\\[([0-9])\\\\]', 'p\\\\1', param_str)\n param_str = re.sub('pow\\\\((.*?)\\\\s*?,\\\\s*?([0-9])\\\\)', '\\\\1**\\\\2',\n param_str)\n return sp.sympify(param_str)\n\n\ndef get_corr_subs_values(corr):\n \"\"\"\n Get the dictionary of substitution values for the correlation matrix\n \"\"\"\n subs_dict = {}\n n_dim = corr.shape[0]\n for irow in xrange(0, n_dim):\n for icol in xrange(irow + 1, n_dim):\n subs_dict['rho_p{}p{}'.format(irow, icol)] = corr[irow, icol]\n return subs_dict\n\n\ndef get_cov_func(params, corr):\n \"\"\"\n Get the uncertainty function where only pT is left as a free parameter.\n\n This will return a python function that can be evaluated at any given point\n \"\"\"\n eff = eff_param_sym()\n free_params = []\n for sym in eff.free_symbols:\n if sym.name in params and params[sym.name][1] != 0:\n free_params.append(sym)\n free_params.sort(key=lambda x: int(x.name.replace('p', '')))\n cov_eff = func_cov(eff, free_params)\n subst_vals = {p: v[0] for p, v in params.iteritems()}\n subst_vals.update({('sigma_' + p): v[1] for p, v in params.iteritems()})\n subst_vals.update(get_corr_subs_values(corr))\n return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals))\n\n\ndef get_graph_err(params, corr, n_sigma=1.0, n_points=100):\n \"\"\"\n Get the function evaluated at n_points with uncertainties taking into\n account correlations between the parameters\n \"\"\"\n eff_f = eff_param_sym()\n eff_f = eff_f.subs({p: v[0] for p, v in params.iteritems()})\n eff_f = sp.lambdify(sp.symbols('x'), eff_f)\n var_f = get_cov_func(params, corr)\n x_bins = np.linspace(0.4, 7, n_points + 1)\n x_cent = 0.5 * (x_bins[1:] + x_bins[:-1])\n x_err = np.diff(x_bins)\n y_cent = np.array([eff_f(x) for x in x_cent])\n y_err = np.sqrt(np.array([var_f(x) for x in x_cent])) * n_sigma\n return r.TGraphErrors(len(x_cent), x_cent, y_cent, x_err, y_err)\n\n\ndef set_params_errors(func, *params):\n \"\"\"\n Set all the parameters as pairs of value and uncertainty (in the order they)\n are in the params list. If uncertainty = 0, the parameter is fixed\n \"\"\"\n central = np.array([p[0] for p in params])\n uncer = np.array([p[1] for p in params])\n func.SetParameters(central)\n func.SetParErrors(uncer)\n for idx, err in enumerate(uncer):\n if err == 0:\n func.FixParameter(idx, func.GetParameter(idx))\n\n\ndef load_params(param_file):\n \"\"\"\n Load the parameter file and return the list of dicts stored in it\n \"\"\"\n with open(param_file, 'r') as pfile:\n eff_params = json.load(pfile)\n return eff_params\n\n\ndef create_param(params, sigma_shift, uncorrelated):\n \"\"\"\n Create the function from the passed params and give it an appropriate name\n \"\"\"\n if sigma_shift == 0:\n func = eff_param()\n set_params_errors(func, params['p0'], params['p1'], params['p2'],\n params['p3'], params['alpha'], params['beta'])\n func.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return func\n params['p4'] = params['alpha']\n params['p5'] = params['beta']\n corr = np.identity(4) if uncorrelated else CORRELATIONS\n graph = get_graph_err(params, corr, np.abs(sigma_shift), 200)\n if sigma_shift < 0:\n graph = get_lower_band(graph)\n else:\n graph = get_upper_band(graph)\n graph.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return graph\n\n\ndef main(args):\n \"\"\"Main\"\"\"\n file_option = 'update' if args.update else 'recreate'\n outfile = r.TFile.Open(args.outfile, file_option)\n all_params = load_params(args.paramfile)\n for params in all_params:\n eff = create_param(params, args.sigma, args.uncorrelated)\n eff.Write()\n outfile.Close()\n\n\n<mask token>\n", "step-4": "<mask token>\nr.PyConfig.IgnoreCommandLineOptions = True\n<mask token>\nCOVARIANCE = np.array([[1.181e-06, 1.545e-06, -4.328e-06, 4.156e-06], [\n 1.545e-06, 7.215e-06, -1.714e-05, 5.177e-06], [-4.328e-06, -1.714e-05, \n 4.228e-05, -1.481e-05], [4.156e-06, 5.177e-06, -1.481e-05, 1.506e-05]])\nCORRELATIONS = np.matmul(np.matmul(np.diag(1 / np.sqrt(np.diag(COVARIANCE))\n ), COVARIANCE), np.diag(1 / np.sqrt(np.diag(COVARIANCE))))\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3))))\n \"\"\"\n return (\n '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))'\n )\n\n\ndef eff_param():\n \"\"\"\n Get the parametrization as ROOT.TF1\n \"\"\"\n return r.TF1('photon_eff_param', eff_param_string(), 0, 7)\n\n\ndef eff_param_sym():\n \"\"\"\n Get the parametrization as sympy symbolic expression by doing some string\n manipulation on the parametrization and then using sympy.sympify\n \"\"\"\n param_str = eff_param_string()\n param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x')\n param_str = re.sub('\\\\[([0-9])\\\\]', 'p\\\\1', param_str)\n param_str = re.sub('pow\\\\((.*?)\\\\s*?,\\\\s*?([0-9])\\\\)', '\\\\1**\\\\2',\n param_str)\n return sp.sympify(param_str)\n\n\ndef get_corr_subs_values(corr):\n \"\"\"\n Get the dictionary of substitution values for the correlation matrix\n \"\"\"\n subs_dict = {}\n n_dim = corr.shape[0]\n for irow in xrange(0, n_dim):\n for icol in xrange(irow + 1, n_dim):\n subs_dict['rho_p{}p{}'.format(irow, icol)] = corr[irow, icol]\n return subs_dict\n\n\ndef get_cov_func(params, corr):\n \"\"\"\n Get the uncertainty function where only pT is left as a free parameter.\n\n This will return a python function that can be evaluated at any given point\n \"\"\"\n eff = eff_param_sym()\n free_params = []\n for sym in eff.free_symbols:\n if sym.name in params and params[sym.name][1] != 0:\n free_params.append(sym)\n free_params.sort(key=lambda x: int(x.name.replace('p', '')))\n cov_eff = func_cov(eff, free_params)\n subst_vals = {p: v[0] for p, v in params.iteritems()}\n subst_vals.update({('sigma_' + p): v[1] for p, v in params.iteritems()})\n subst_vals.update(get_corr_subs_values(corr))\n return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals))\n\n\ndef get_graph_err(params, corr, n_sigma=1.0, n_points=100):\n \"\"\"\n Get the function evaluated at n_points with uncertainties taking into\n account correlations between the parameters\n \"\"\"\n eff_f = eff_param_sym()\n eff_f = eff_f.subs({p: v[0] for p, v in params.iteritems()})\n eff_f = sp.lambdify(sp.symbols('x'), eff_f)\n var_f = get_cov_func(params, corr)\n x_bins = np.linspace(0.4, 7, n_points + 1)\n x_cent = 0.5 * (x_bins[1:] + x_bins[:-1])\n x_err = np.diff(x_bins)\n y_cent = np.array([eff_f(x) for x in x_cent])\n y_err = np.sqrt(np.array([var_f(x) for x in x_cent])) * n_sigma\n return r.TGraphErrors(len(x_cent), x_cent, y_cent, x_err, y_err)\n\n\ndef set_params_errors(func, *params):\n \"\"\"\n Set all the parameters as pairs of value and uncertainty (in the order they)\n are in the params list. If uncertainty = 0, the parameter is fixed\n \"\"\"\n central = np.array([p[0] for p in params])\n uncer = np.array([p[1] for p in params])\n func.SetParameters(central)\n func.SetParErrors(uncer)\n for idx, err in enumerate(uncer):\n if err == 0:\n func.FixParameter(idx, func.GetParameter(idx))\n\n\ndef load_params(param_file):\n \"\"\"\n Load the parameter file and return the list of dicts stored in it\n \"\"\"\n with open(param_file, 'r') as pfile:\n eff_params = json.load(pfile)\n return eff_params\n\n\ndef create_param(params, sigma_shift, uncorrelated):\n \"\"\"\n Create the function from the passed params and give it an appropriate name\n \"\"\"\n if sigma_shift == 0:\n func = eff_param()\n set_params_errors(func, params['p0'], params['p1'], params['p2'],\n params['p3'], params['alpha'], params['beta'])\n func.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return func\n params['p4'] = params['alpha']\n params['p5'] = params['beta']\n corr = np.identity(4) if uncorrelated else CORRELATIONS\n graph = get_graph_err(params, corr, np.abs(sigma_shift), 200)\n if sigma_shift < 0:\n graph = get_lower_band(graph)\n else:\n graph = get_upper_band(graph)\n graph.SetName(get_name(params['eta'], 'photon_eff_pt'))\n return graph\n\n\ndef main(args):\n \"\"\"Main\"\"\"\n file_option = 'update' if args.update else 'recreate'\n outfile = r.TFile.Open(args.outfile, file_option)\n all_params = load_params(args.paramfile)\n for params in all_params:\n eff = create_param(params, args.sigma, args.uncorrelated)\n eff.Write()\n outfile.Close()\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description=\n 'script to generate TF1 photon efficiency parametrizations from json file holding the fit parameters'\n )\n parser.add_argument('paramfile', help=\n 'json file containing the fitted parameters')\n parser.add_argument('-o', '--outfile', help=\n 'root file into which the TF1 should be stored', default=\n 'photon_effs_param.root')\n parser.add_argument('-u', '--update', help=\n 'update the output file instead of recreating it', default=False,\n action='store_true')\n parser.add_argument('-s', '--sigma', help=\n 'Use the central value + [sigma] * uncertainty for each parameter',\n type=float, default=0)\n parser.add_argument('--uncorrelated', default=False, action=\n 'store_true', help=\n 'Assume that the free parameters are uncorrelated instead of using correlation parameters from a global fit'\n )\n clargs = parser.parse_args()\n main(clargs)\n", "step-5": "#!/usr/bin/env python\n\"\"\"\nScript that generates the photon efficiency curves and stores them in a root\nfile.\n\nFor the moment only the pT curves for the different eta bins are created\n\"\"\"\n\nimport re\nimport json\nimport ROOT as r\nr.PyConfig.IgnoreCommandLineOptions = True\n\nimport numpy as np\nimport sympy as sp\n\nfrom utils.symbolic import func_cov\nfrom utils.graph_utils import get_lower_band, get_upper_band\n\nfrom common_func import get_name\n\n# Covariance matrix from the fit integrated over the whole eta range, where\n# alpha and beta were fixed. This will be used to calculate the correlation\n# coefficients between the fitted parameters, which will then be used to get\n# the uncertainty bands for the parametrization\nCOVARIANCE = np.array([\n [1.181e-06, 1.545e-06, -4.328e-06, 4.156e-06],\n [1.545e-06, 7.215e-06, -1.714e-05, 5.177e-06],\n [-4.328e-06, -1.714e-05, 4.228e-05, -1.481e-05],\n [4.156e-06, 5.177e-06, -1.481e-05, 1.506e-05],\n])\n\n# corr = diag(cov)^{-1/2} * cov * diag(cov)^{-1/2}\nCORRELATIONS = np.matmul(\n np.matmul(\n np.diag(1/np.sqrt(np.diag(COVARIANCE))), COVARIANCE,\n ), np.diag(1/np.sqrt(np.diag(COVARIANCE)))\n)\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 * (pT^2 - p3 / beta * pT^3))))\n \"\"\"\n return '[0] * (1 - [1] * (TMath::Erf(x[0] + [2]) - [1] / [4] * (x[0] - [3] * (pow(x[0], 2) - [3] / [5] * pow(x[0], 3)))))'\n\n\ndef eff_param():\n \"\"\"\n Get the parametrization as ROOT.TF1\n \"\"\"\n return r.TF1('photon_eff_param', eff_param_string(), 0, 7)\n\n\ndef eff_param_sym():\n \"\"\"\n Get the parametrization as sympy symbolic expression by doing some string\n manipulation on the parametrization and then using sympy.sympify\n \"\"\"\n param_str = eff_param_string()\n # replace call to ROOTs erf and give x[0] a parseable name\n param_str = param_str.replace('TMath::Erf', 'erf').replace('x[0]', 'x')\n # convert parameters from [x] notation to px notation\n param_str = re.sub(r'\\[([0-9])\\]', r'p\\1', param_str)\n # replace pow(x, y) with x**y (pythonic) syntax\n param_str = re.sub(r'pow\\((.*?)\\s*?,\\s*?([0-9])\\)', r'\\1**\\2', param_str)\n\n return sp.sympify(param_str)\n\n\ndef get_corr_subs_values(corr):\n \"\"\"\n Get the dictionary of substitution values for the correlation matrix\n \"\"\"\n subs_dict = {}\n n_dim = corr.shape[0]\n for irow in xrange(0, n_dim):\n for icol in xrange(irow + 1, n_dim):\n subs_dict['rho_p{}p{}'.format(irow, icol)] = corr[irow, icol]\n\n return subs_dict\n\n\ndef get_cov_func(params, corr):\n \"\"\"\n Get the uncertainty function where only pT is left as a free parameter.\n\n This will return a python function that can be evaluated at any given point\n \"\"\"\n eff = eff_param_sym()\n # get the list of free parameters\n free_params = []\n for sym in eff.free_symbols:\n if sym.name in params and params[sym.name][1] != 0:\n free_params.append(sym)\n\n # sort the parameters according to their name, such that the correlation\n # coefficients actually match\n free_params.sort(key=lambda x: int(x.name.replace('p', '')))\n\n cov_eff = func_cov(eff, free_params)\n\n # build up the dictionary of symbol -> value that will be substituted.\n # In the end the returned function will only have one free parameter left\n subst_vals = {\n p: v[0] for p, v in params.iteritems()\n }\n subst_vals.update({\n 'sigma_' + p: v[1] for p, v in params.iteritems()\n })\n subst_vals.update(\n get_corr_subs_values(corr)\n )\n\n # NOTE: here it is assumed that 'x' is the only free parameter left\n return sp.lambdify(sp.symbols('x'), cov_eff.subs(subst_vals))\n\n\ndef get_graph_err(params, corr, n_sigma=1.0, n_points=100):\n \"\"\"\n Get the function evaluated at n_points with uncertainties taking into\n account correlations between the parameters\n \"\"\"\n # central function\n eff_f = eff_param_sym()\n eff_f = eff_f.subs({p: v[0] for p, v in params.iteritems()})\n # NOTE: assume that 'x' is the only free parameter left\n eff_f = sp.lambdify(sp.symbols('x'), eff_f)\n\n # uncertainty function (as function of pT)\n var_f = get_cov_func(params, corr)\n\n x_bins = np.linspace(0.4, 7, n_points + 1)\n x_cent = 0.5 * (x_bins[1:] + x_bins[:-1]) # bin centers\n x_err = np.diff(x_bins) # \"uncertainties\" in x\n\n y_cent = np.array([eff_f(x) for x in x_cent])\n y_err = np.sqrt(np.array([var_f(x) for x in x_cent])) * n_sigma\n\n return r.TGraphErrors(len(x_cent), x_cent, y_cent, x_err, y_err)\n\n\ndef set_params_errors(func, *params):\n \"\"\"\n Set all the parameters as pairs of value and uncertainty (in the order they)\n are in the params list. If uncertainty = 0, the parameter is fixed\n \"\"\"\n central = np.array([p[0] for p in params])\n uncer = np.array([p[1] for p in params])\n\n func.SetParameters(central)\n func.SetParErrors(uncer)\n\n for idx, err in enumerate(uncer):\n if err == 0:\n func.FixParameter(idx, func.GetParameter(idx))\n\n\ndef load_params(param_file):\n \"\"\"\n Load the parameter file and return the list of dicts stored in it\n \"\"\"\n with open(param_file, 'r') as pfile:\n eff_params = json.load(pfile)\n return eff_params\n\n\ndef create_param(params, sigma_shift, uncorrelated):\n \"\"\"\n Create the function from the passed params and give it an appropriate name\n \"\"\"\n # if the central results are desired. Use the exact parametrization as TF1\n if sigma_shift == 0:\n func = eff_param()\n set_params_errors(func, params[\"p0\"], params[\"p1\"], params[\"p2\"],\n params[\"p3\"], params[\"alpha\"], params[\"beta\"])\n\n func.SetName(get_name(params[\"eta\"], 'photon_eff_pt'))\n return func\n\n # else get an aproximation by evaluating the function at a given number of\n # points and determine the uncertainties at these points, then store the\n # points as a TGraph where the y-values are the central + uncertainty values\n # at each evaluation point\n\n # NOTE: Since eff_param_sym names alpha and beta p4 and p5 respectively\n # (can't use beta in an expression that goes through sympy.sympify), we have\n # to clone them here. We can leave the original values in, since they will\n # not be picked up by the substitution command\n params['p4'] = params['alpha']\n params['p5'] = params['beta']\n\n # use the global correlation matrix or an identity matrix if uncorrelated\n # parameters are desired\n corr = np.identity(4) if uncorrelated else CORRELATIONS\n graph = get_graph_err(params, corr, np.abs(sigma_shift), 200)\n\n if sigma_shift < 0:\n graph = get_lower_band(graph)\n else:\n graph = get_upper_band(graph)\n\n graph.SetName(get_name(params['eta'], 'photon_eff_pt'))\n\n return graph\n\n\ndef main(args):\n \"\"\"Main\"\"\"\n file_option = 'update' if args.update else 'recreate'\n outfile = r.TFile.Open(args.outfile, file_option)\n\n all_params = load_params(args.paramfile)\n for params in all_params:\n eff = create_param(params, args.sigma, args.uncorrelated)\n eff.Write()\n\n outfile.Close()\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='script to generate TF1 '\n 'photon efficiency parametrizations from '\n 'json file holding the fit parameters')\n parser.add_argument('paramfile', help='json file containing the fitted '\n 'parameters')\n parser.add_argument('-o', '--outfile', help='root file into which the TF1 '\n 'should be stored', default='photon_effs_param.root')\n parser.add_argument('-u', '--update', help='update the output file instead '\n 'of recreating it', default=False, action='store_true')\n parser.add_argument('-s', '--sigma', help='Use the central value + [sigma] '\n '* uncertainty for each parameter', type=float,\n default=0)\n parser.add_argument('--uncorrelated', default=False, action='store_true',\n help='Assume that the free parameters are uncorrelated '\n 'instead of using correlation parameters from a global '\n 'fit')\n\n clargs = parser.parse_args()\n main(clargs)\n", "step-ids": [ 8, 9, 10, 12, 14 ] }
[ 8, 9, 10, 12, 14 ]
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal. """ def largo (l, n): i=0 cuenta=1 valor1=0 valor2=0 while cuenta < n+1 or cuenta==n+1: a=l[i] b=l[i+1] if a==b: cuenta+= 1 valor1=a i+=1 cuenta=1 while cuenta < n or cuenta == n and i<len(l)-1: c=l[i] d=l[i+1] if c==d: cuenta+= 1 valor2=c i+=1 alto=abs(valor1-valor2) return alto def hayBorde(l,n,h): if largo(l,n)==h: return True else: return False print(hayBorde([2,4,4,4,6,6,6,10,10],2,4))
normal
{ "blob_id": "f3b697e20f60e51d80d655ddf4809aa9afdfcd69", "index": 7495, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef largo(l, n):\n i = 0\n cuenta = 1\n valor1 = 0\n valor2 = 0\n while cuenta < n + 1 or cuenta == n + 1:\n a = l[i]\n b = l[i + 1]\n if a == b:\n cuenta += 1\n valor1 = a\n i += 1\n cuenta = 1\n while cuenta < n or cuenta == n and i < len(l) - 1:\n c = l[i]\n d = l[i + 1]\n if c == d:\n cuenta += 1\n valor2 = c\n i += 1\n alto = abs(valor1 - valor2)\n return alto\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef largo(l, n):\n i = 0\n cuenta = 1\n valor1 = 0\n valor2 = 0\n while cuenta < n + 1 or cuenta == n + 1:\n a = l[i]\n b = l[i + 1]\n if a == b:\n cuenta += 1\n valor1 = a\n i += 1\n cuenta = 1\n while cuenta < n or cuenta == n and i < len(l) - 1:\n c = l[i]\n d = l[i + 1]\n if c == d:\n cuenta += 1\n valor2 = c\n i += 1\n alto = abs(valor1 - valor2)\n return alto\n\n\ndef hayBorde(l, n, h):\n if largo(l, n) == h:\n return True\n else:\n return False\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef largo(l, n):\n i = 0\n cuenta = 1\n valor1 = 0\n valor2 = 0\n while cuenta < n + 1 or cuenta == n + 1:\n a = l[i]\n b = l[i + 1]\n if a == b:\n cuenta += 1\n valor1 = a\n i += 1\n cuenta = 1\n while cuenta < n or cuenta == n and i < len(l) - 1:\n c = l[i]\n d = l[i + 1]\n if c == d:\n cuenta += 1\n valor2 = c\n i += 1\n alto = abs(valor1 - valor2)\n return alto\n\n\ndef hayBorde(l, n, h):\n if largo(l, n) == h:\n return True\n else:\n return False\n\n\nprint(hayBorde([2, 4, 4, 4, 6, 6, 6, 10, 10], 2, 4))\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nEditor de Spyder\n\nEste es un archivo temporal.\n\"\"\"\n\ndef largo (l, n):\n i=0\n cuenta=1\n valor1=0\n valor2=0\n while cuenta < n+1 or cuenta==n+1:\n a=l[i]\n b=l[i+1]\n if a==b:\n cuenta+= 1\n valor1=a\n i+=1\n cuenta=1\n while cuenta < n or cuenta == n and i<len(l)-1:\n c=l[i]\n d=l[i+1]\n if c==d:\n cuenta+= 1\n valor2=c\n i+=1\n alto=abs(valor1-valor2)\n return alto\n\ndef hayBorde(l,n,h):\n if largo(l,n)==h:\n return True\n else:\n return False\n\nprint(hayBorde([2,4,4,4,6,6,6,10,10],2,4))\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import os from linkedin_scraper import get_jobs chrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver') df = get_jobs('Data Scientist', 40, False, chrome_driver_path) df.to_csv('linkedin_jobs.csv', index=False)
normal
{ "blob_id": "6ae529a5e5658ba409ec3e7284d8b2911c60dd00", "index": 906, "step-1": "<mask token>\n", "step-2": "<mask token>\ndf.to_csv('linkedin_jobs.csv', index=False)\n", "step-3": "<mask token>\nchrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver')\ndf = get_jobs('Data Scientist', 40, False, chrome_driver_path)\ndf.to_csv('linkedin_jobs.csv', index=False)\n", "step-4": "import os\nfrom linkedin_scraper import get_jobs\nchrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver')\ndf = get_jobs('Data Scientist', 40, False, chrome_driver_path)\ndf.to_csv('linkedin_jobs.csv', index=False)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import json from gamestate.gamestate_module import Gamestate from time import time from gamestate import action_getter as action_getter def test_action_getter(): path = "./../Version_1.0/Tests/General/Action_1.json" document = json.loads(open(path).read()) gamestate = Gamestate.from_document(document["gamestate"]) nloops = 100 total_time = 0 for _ in range(nloops): t = time() action_getter.get_actions(gamestate) total_time += time() - t print("Time used to find all actions", str(nloops), "times:", str(round(total_time, 3)))
normal
{ "blob_id": "b16691429d83f6909a08b10cc0b310bb62cd550d", "index": 3985, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_action_getter():\n path = './../Version_1.0/Tests/General/Action_1.json'\n document = json.loads(open(path).read())\n gamestate = Gamestate.from_document(document['gamestate'])\n nloops = 100\n total_time = 0\n for _ in range(nloops):\n t = time()\n action_getter.get_actions(gamestate)\n total_time += time() - t\n print('Time used to find all actions', str(nloops), 'times:', str(round\n (total_time, 3)))\n", "step-3": "import json\nfrom gamestate.gamestate_module import Gamestate\nfrom time import time\nfrom gamestate import action_getter as action_getter\n\n\ndef test_action_getter():\n path = './../Version_1.0/Tests/General/Action_1.json'\n document = json.loads(open(path).read())\n gamestate = Gamestate.from_document(document['gamestate'])\n nloops = 100\n total_time = 0\n for _ in range(nloops):\n t = time()\n action_getter.get_actions(gamestate)\n total_time += time() - t\n print('Time used to find all actions', str(nloops), 'times:', str(round\n (total_time, 3)))\n", "step-4": "import json\nfrom gamestate.gamestate_module import Gamestate\nfrom time import time\nfrom gamestate import action_getter as action_getter\n\n\ndef test_action_getter():\n path = \"./../Version_1.0/Tests/General/Action_1.json\"\n document = json.loads(open(path).read())\n gamestate = Gamestate.from_document(document[\"gamestate\"])\n\n nloops = 100\n total_time = 0\n for _ in range(nloops):\n t = time()\n action_getter.get_actions(gamestate)\n total_time += time() - t\n\n print(\"Time used to find all actions\", str(nloops), \"times:\", str(round(total_time, 3)))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
def intersection(nums1, nums2): return list(set(nums1)&set(nums2)) if __name__=="__main__": print intersection([1, 2, 2, 1],[2, 2])
normal
{ "blob_id": "0081ffc2a1de7fb71515fd0070aaebfef806f6ef", "index": 4230, "step-1": "def intersection(nums1, nums2):\n return list(set(nums1)&set(nums2))\n \n \nif __name__==\"__main__\":\n print intersection([1, 2, 2, 1],[2, 2])", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
"""! @brief Example 04 @details pyAudioAnalysis spectrogram calculation and visualization example @author Theodoros Giannakopoulos {tyiannak@gmail.com} """ import numpy as np import scipy.io.wavfile as wavfile import plotly import plotly.graph_objs as go from pyAudioAnalysis import ShortTermFeatures as aF layout = go.Layout(title='Spectrogram Extraction Example using pyAudioAnalysis', xaxis=dict(title='time (sec)',), yaxis=dict(title='Freqs (Hz)',)) def normalize_signal(signal): signal = np.double(signal) signal = signal / (2.0 ** 15) signal = (signal - signal.mean()) return signal / ((np.abs(signal)).max() + 0.0000000001) if __name__ == '__main__': [Fs, s] = wavfile.read("../data/sample_music.wav") s = normalize_signal(s) [S, t, f] = aF.spectrogram(s, Fs, int(Fs * 0.020), int(Fs * 0.020)) heatmap = go.Heatmap(z=S.T, y=f, x=t) plotly.offline.plot(go.Figure(data=[heatmap], layout=layout), filename="temp.html", auto_open=True)
normal
{ "blob_id": "cb40141eddce9ce11fbd8475fc7c3d37438208a6", "index": 6862, "step-1": "<mask token>\n\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / 2.0 ** 15\n signal = signal - signal.mean()\n return signal / (np.abs(signal).max() + 1e-10)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / 2.0 ** 15\n signal = signal - signal.mean()\n return signal / (np.abs(signal).max() + 1e-10)\n\n\nif __name__ == '__main__':\n [Fs, s] = wavfile.read('../data/sample_music.wav')\n s = normalize_signal(s)\n [S, t, f] = aF.spectrogram(s, Fs, int(Fs * 0.02), int(Fs * 0.02))\n heatmap = go.Heatmap(z=S.T, y=f, x=t)\n plotly.offline.plot(go.Figure(data=[heatmap], layout=layout), filename=\n 'temp.html', auto_open=True)\n", "step-3": "<mask token>\nlayout = go.Layout(title=\n 'Spectrogram Extraction Example using pyAudioAnalysis', xaxis=dict(\n title='time (sec)'), yaxis=dict(title='Freqs (Hz)'))\n\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / 2.0 ** 15\n signal = signal - signal.mean()\n return signal / (np.abs(signal).max() + 1e-10)\n\n\nif __name__ == '__main__':\n [Fs, s] = wavfile.read('../data/sample_music.wav')\n s = normalize_signal(s)\n [S, t, f] = aF.spectrogram(s, Fs, int(Fs * 0.02), int(Fs * 0.02))\n heatmap = go.Heatmap(z=S.T, y=f, x=t)\n plotly.offline.plot(go.Figure(data=[heatmap], layout=layout), filename=\n 'temp.html', auto_open=True)\n", "step-4": "<mask token>\nimport numpy as np\nimport scipy.io.wavfile as wavfile\nimport plotly\nimport plotly.graph_objs as go\nfrom pyAudioAnalysis import ShortTermFeatures as aF\nlayout = go.Layout(title=\n 'Spectrogram Extraction Example using pyAudioAnalysis', xaxis=dict(\n title='time (sec)'), yaxis=dict(title='Freqs (Hz)'))\n\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / 2.0 ** 15\n signal = signal - signal.mean()\n return signal / (np.abs(signal).max() + 1e-10)\n\n\nif __name__ == '__main__':\n [Fs, s] = wavfile.read('../data/sample_music.wav')\n s = normalize_signal(s)\n [S, t, f] = aF.spectrogram(s, Fs, int(Fs * 0.02), int(Fs * 0.02))\n heatmap = go.Heatmap(z=S.T, y=f, x=t)\n plotly.offline.plot(go.Figure(data=[heatmap], layout=layout), filename=\n 'temp.html', auto_open=True)\n", "step-5": "\"\"\"! \n@brief Example 04\n@details pyAudioAnalysis spectrogram calculation and visualization example\n@author Theodoros Giannakopoulos {tyiannak@gmail.com}\n\"\"\"\nimport numpy as np\nimport scipy.io.wavfile as wavfile\nimport plotly\nimport plotly.graph_objs as go\nfrom pyAudioAnalysis import ShortTermFeatures as aF\nlayout = go.Layout(title='Spectrogram Extraction Example using pyAudioAnalysis',\n xaxis=dict(title='time (sec)',),\n yaxis=dict(title='Freqs (Hz)',))\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / (2.0 ** 15)\n signal = (signal - signal.mean())\n return signal / ((np.abs(signal)).max() + 0.0000000001)\n\nif __name__ == '__main__':\n [Fs, s] = wavfile.read(\"../data/sample_music.wav\")\n s = normalize_signal(s)\n [S, t, f] = aF.spectrogram(s, Fs, int(Fs * 0.020), int(Fs * 0.020))\n heatmap = go.Heatmap(z=S.T, y=f, x=t)\n plotly.offline.plot(go.Figure(data=[heatmap], layout=layout),\n filename=\"temp.html\", auto_open=True)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- # Copyright 2013, Achim Köhler # All rights reserved, see accompanied file license.txt for details. # $REV$ import argparse import traylauncher if __name__ == "__main__": args = argparse.Namespace() args.notray = False traylauncher.start(args)
normal
{ "blob_id": "8faaf9eb2e78b7921dd1cac4772e2415671201c7", "index": 8481, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n args = argparse.Namespace()\n args.notray = False\n traylauncher.start(args)\n", "step-3": "import argparse\nimport traylauncher\nif __name__ == '__main__':\n args = argparse.Namespace()\n args.notray = False\n traylauncher.start(args)\n", "step-4": "# -*- coding: utf-8 -*-\n# Copyright 2013, Achim Köhler\n# All rights reserved, see accompanied file license.txt for details.\n\n# $REV$\n\nimport argparse\nimport traylauncher\n\nif __name__ == \"__main__\":\n\targs = argparse.Namespace()\n\targs.notray = False\n\ttraylauncher.start(args)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.urls import path,include from . import views urlpatterns = [ path('register_curier/',views.curier_register,name="register_curier"), path('private_сurier/',views.private_сurier,name="private_сurier"), path('private_сurier2/',views.private_сurier2,name="private_сurier2"), path('private_curier/select/<int:id>',views.curier_select,name="curier_select"), path('private_curier/cancel/<int:id>',views.curier_cancel,name="curier_cancel"), path("private_curier_raschet/<str:day>",views.rashet_view,name="curier_rashet"), path("private_curier_history/",views.curier_history,name="curier_history"), ]
normal
{ "blob_id": "c1a83c9551e83e395a365210a99330fee7877dff", "index": 6881, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('register_curier/', views.curier_register, name=\n 'register_curier'), path('private_сurier/', views.private_сurier, name=\n 'private_сurier'), path('private_сurier2/', views.private_сurier2, name\n ='private_сurier2'), path('private_curier/select/<int:id>', views.\n curier_select, name='curier_select'), path(\n 'private_curier/cancel/<int:id>', views.curier_cancel, name=\n 'curier_cancel'), path('private_curier_raschet/<str:day>', views.\n rashet_view, name='curier_rashet'), path('private_curier_history/',\n views.curier_history, name='curier_history')]\n", "step-3": "from django.urls import path, include\nfrom . import views\nurlpatterns = [path('register_curier/', views.curier_register, name=\n 'register_curier'), path('private_сurier/', views.private_сurier, name=\n 'private_сurier'), path('private_сurier2/', views.private_сurier2, name\n ='private_сurier2'), path('private_curier/select/<int:id>', views.\n curier_select, name='curier_select'), path(\n 'private_curier/cancel/<int:id>', views.curier_cancel, name=\n 'curier_cancel'), path('private_curier_raschet/<str:day>', views.\n rashet_view, name='curier_rashet'), path('private_curier_history/',\n views.curier_history, name='curier_history')]\n", "step-4": "from django.urls import path,include\nfrom . import views\n\nurlpatterns = [\n path('register_curier/',views.curier_register,name=\"register_curier\"),\n path('private_сurier/',views.private_сurier,name=\"private_сurier\"),\n path('private_сurier2/',views.private_сurier2,name=\"private_сurier2\"),\n path('private_curier/select/<int:id>',views.curier_select,name=\"curier_select\"),\n path('private_curier/cancel/<int:id>',views.curier_cancel,name=\"curier_cancel\"),\n path(\"private_curier_raschet/<str:day>\",views.rashet_view,name=\"curier_rashet\"),\n path(\"private_curier_history/\",views.curier_history,name=\"curier_history\"),\n\n]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from . import * from module import * from transfer import * from dataset import *
normal
{ "blob_id": "94d992ef4b9015aa8f42071bb1409703d509c313", "index": 9810, "step-1": "<mask token>\n", "step-2": "from . import *\nfrom module import *\nfrom transfer import *\nfrom dataset import *\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# -------------------------------------------------------------------------------------------------- # Property of UAH # IDS module for ladder logic monitoring # This codes is Written by Rishabh Das # Date:- 18th June 2018 # -------------------------------------------------------------------------------------------------- import hashlib import os # --------------------------------------------------------------------------------------------------- # This section declares the Global variables of the project # --------------------------------------------------------------------------------------------------- Monitoredlist=[] list_create=[] list_compare=[] # --------------------------------------------------------------------------------------------------- # This section notes the number of files in the directory and creates the list of the files that needs # to be monitored # --------------------------------------------------------------------------------------------------- def Create_list(): i=0 for file in os.listdir(os.getcwd()): if file.endswith("openplc"): Monitoredlist.append(file) i += 1 if i==0: print("No Files are being monitored!") else: print("The files being monitored are as follows") print(Monitoredlist) # --------------------------------------------------------------------------------------------------- # This is the Hasher module that creates the hash for the files and maintains a table of the file # hashes # --------------------------------------------------------------------------------------------------- def Hasher(): BLOCKSIZE = 65536 hasher = hashlib.sha1() del list_create[:] for i in range(len(Monitoredlist)): list_create.append(Monitoredlist[i]) with open(Monitoredlist[i], 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) list_create.append(hasher.hexdigest()) #print(list_create) # -------------------------------------------------------------------------------------------------- # This Function records the hash of the files being monitored to a text file. This should only be # called when the program is being executed for the first time # -------------------------------------------------------------------------------------------------- def Create_record(): progpath = os.getcwd() dirpath = progpath + '/Details' if not os.path.exists(dirpath): os.makedirs(dirpath) os.chdir(dirpath) file = open('Record.txt',"w") for item in list_create: file.write("%s\n" % item) file.close() os.chdir(progpath) # -------------------------------------------------------------------------------------------------- # This module parses the stored hashes and stores them into a fresh python list # -------------------------------------------------------------------------------------------------- def Read_hash(): progpath = os.getcwd() dirpath = progpath + '/Details' os.chdir(dirpath) file = open('Record.txt', 'r') list_compare=[] list_compare = file.readlines() list_compare = [x[:-1] for x in list_compare] os.chdir(progpath) #print(list_compare) #print(list_create) if list_compare == list_create: Response(0) else: Response(1) # -------------------------------------------------------------------------------------------------- # Once the change is detected this module is used to respond to the threat # flag ->>>> 1 Change is detected # flag ->>>> 0 No change # -------------------------------------------------------------------------------------------------- def Response(flag): if flag==1: print("Ladder Logic Tampered") #Launch recovery routine else: print("Ladder Logic is Secure") # -------------------------------------------------------------------------------------------------- # The main Function # -------------------------------------------------------------------------------------------------- def main(): Create_list() Hasher() print(list_create) Create_record() Read_hash() # First call with 0 argument while(1): Hasher() Read_hash() # Next calls are all performed by argument # 1. Create the folder for storing the new file->Done # 2. Module to compare the files with a new file->Done # 3. Module to backup the ladder logics # 4. Module to restore the ladder logic # 5. Reporting unit->Done # 6. Push code to GitHub->Done if __name__ == "__main__": main()
normal
{ "blob_id": "6f8ce77dd45f555ca092482715b6ccaa33414fd8", "index": 4176, "step-1": "<mask token>\n\n\ndef Create_list():\n i = 0\n for file in os.listdir(os.getcwd()):\n if file.endswith('openplc'):\n Monitoredlist.append(file)\n i += 1\n if i == 0:\n print('No Files are being monitored!')\n else:\n print('The files being monitored are as follows')\n print(Monitoredlist)\n\n\ndef Hasher():\n BLOCKSIZE = 65536\n hasher = hashlib.sha1()\n del list_create[:]\n for i in range(len(Monitoredlist)):\n list_create.append(Monitoredlist[i])\n with open(Monitoredlist[i], 'rb') as afile:\n buf = afile.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(BLOCKSIZE)\n list_create.append(hasher.hexdigest())\n\n\n<mask token>\n\n\ndef Read_hash():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n os.chdir(dirpath)\n file = open('Record.txt', 'r')\n list_compare = []\n list_compare = file.readlines()\n list_compare = [x[:-1] for x in list_compare]\n os.chdir(progpath)\n if list_compare == list_create:\n Response(0)\n else:\n Response(1)\n\n\ndef Response(flag):\n if flag == 1:\n print('Ladder Logic Tampered')\n else:\n print('Ladder Logic is Secure')\n\n\ndef main():\n Create_list()\n Hasher()\n print(list_create)\n Create_record()\n Read_hash()\n while 1:\n Hasher()\n Read_hash()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef Create_list():\n i = 0\n for file in os.listdir(os.getcwd()):\n if file.endswith('openplc'):\n Monitoredlist.append(file)\n i += 1\n if i == 0:\n print('No Files are being monitored!')\n else:\n print('The files being monitored are as follows')\n print(Monitoredlist)\n\n\ndef Hasher():\n BLOCKSIZE = 65536\n hasher = hashlib.sha1()\n del list_create[:]\n for i in range(len(Monitoredlist)):\n list_create.append(Monitoredlist[i])\n with open(Monitoredlist[i], 'rb') as afile:\n buf = afile.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(BLOCKSIZE)\n list_create.append(hasher.hexdigest())\n\n\ndef Create_record():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n os.chdir(dirpath)\n file = open('Record.txt', 'w')\n for item in list_create:\n file.write('%s\\n' % item)\n file.close()\n os.chdir(progpath)\n\n\ndef Read_hash():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n os.chdir(dirpath)\n file = open('Record.txt', 'r')\n list_compare = []\n list_compare = file.readlines()\n list_compare = [x[:-1] for x in list_compare]\n os.chdir(progpath)\n if list_compare == list_create:\n Response(0)\n else:\n Response(1)\n\n\ndef Response(flag):\n if flag == 1:\n print('Ladder Logic Tampered')\n else:\n print('Ladder Logic is Secure')\n\n\ndef main():\n Create_list()\n Hasher()\n print(list_create)\n Create_record()\n Read_hash()\n while 1:\n Hasher()\n Read_hash()\n\n\n<mask token>\n", "step-3": "<mask token>\nMonitoredlist = []\nlist_create = []\nlist_compare = []\n\n\ndef Create_list():\n i = 0\n for file in os.listdir(os.getcwd()):\n if file.endswith('openplc'):\n Monitoredlist.append(file)\n i += 1\n if i == 0:\n print('No Files are being monitored!')\n else:\n print('The files being monitored are as follows')\n print(Monitoredlist)\n\n\ndef Hasher():\n BLOCKSIZE = 65536\n hasher = hashlib.sha1()\n del list_create[:]\n for i in range(len(Monitoredlist)):\n list_create.append(Monitoredlist[i])\n with open(Monitoredlist[i], 'rb') as afile:\n buf = afile.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(BLOCKSIZE)\n list_create.append(hasher.hexdigest())\n\n\ndef Create_record():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n os.chdir(dirpath)\n file = open('Record.txt', 'w')\n for item in list_create:\n file.write('%s\\n' % item)\n file.close()\n os.chdir(progpath)\n\n\ndef Read_hash():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n os.chdir(dirpath)\n file = open('Record.txt', 'r')\n list_compare = []\n list_compare = file.readlines()\n list_compare = [x[:-1] for x in list_compare]\n os.chdir(progpath)\n if list_compare == list_create:\n Response(0)\n else:\n Response(1)\n\n\ndef Response(flag):\n if flag == 1:\n print('Ladder Logic Tampered')\n else:\n print('Ladder Logic is Secure')\n\n\ndef main():\n Create_list()\n Hasher()\n print(list_create)\n Create_record()\n Read_hash()\n while 1:\n Hasher()\n Read_hash()\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import hashlib\nimport os\nMonitoredlist = []\nlist_create = []\nlist_compare = []\n\n\ndef Create_list():\n i = 0\n for file in os.listdir(os.getcwd()):\n if file.endswith('openplc'):\n Monitoredlist.append(file)\n i += 1\n if i == 0:\n print('No Files are being monitored!')\n else:\n print('The files being monitored are as follows')\n print(Monitoredlist)\n\n\ndef Hasher():\n BLOCKSIZE = 65536\n hasher = hashlib.sha1()\n del list_create[:]\n for i in range(len(Monitoredlist)):\n list_create.append(Monitoredlist[i])\n with open(Monitoredlist[i], 'rb') as afile:\n buf = afile.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(BLOCKSIZE)\n list_create.append(hasher.hexdigest())\n\n\ndef Create_record():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n os.chdir(dirpath)\n file = open('Record.txt', 'w')\n for item in list_create:\n file.write('%s\\n' % item)\n file.close()\n os.chdir(progpath)\n\n\ndef Read_hash():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n os.chdir(dirpath)\n file = open('Record.txt', 'r')\n list_compare = []\n list_compare = file.readlines()\n list_compare = [x[:-1] for x in list_compare]\n os.chdir(progpath)\n if list_compare == list_create:\n Response(0)\n else:\n Response(1)\n\n\ndef Response(flag):\n if flag == 1:\n print('Ladder Logic Tampered')\n else:\n print('Ladder Logic is Secure')\n\n\ndef main():\n Create_list()\n Hasher()\n print(list_create)\n Create_record()\n Read_hash()\n while 1:\n Hasher()\n Read_hash()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "# --------------------------------------------------------------------------------------------------\n# Property of UAH\n# IDS module for ladder logic monitoring\n# This codes is Written by Rishabh Das\n# Date:- 18th June 2018\n# --------------------------------------------------------------------------------------------------\nimport hashlib\nimport os\n\n# ---------------------------------------------------------------------------------------------------\n# This section declares the Global variables of the project\n# ---------------------------------------------------------------------------------------------------\nMonitoredlist=[]\nlist_create=[]\nlist_compare=[]\n\n\n# ---------------------------------------------------------------------------------------------------\n# This section notes the number of files in the directory and creates the list of the files that needs\n# to be monitored\n# ---------------------------------------------------------------------------------------------------\ndef Create_list():\n i=0\n for file in os.listdir(os.getcwd()):\n if file.endswith(\"openplc\"):\n Monitoredlist.append(file)\n i += 1\n if i==0:\n print(\"No Files are being monitored!\")\n else:\n print(\"The files being monitored are as follows\")\n print(Monitoredlist)\n# ---------------------------------------------------------------------------------------------------\n# This is the Hasher module that creates the hash for the files and maintains a table of the file\n# hashes\n# ---------------------------------------------------------------------------------------------------\ndef Hasher():\n BLOCKSIZE = 65536\n hasher = hashlib.sha1()\n del list_create[:]\n for i in range(len(Monitoredlist)):\n list_create.append(Monitoredlist[i])\n with open(Monitoredlist[i], 'rb') as afile:\n buf = afile.read(BLOCKSIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(BLOCKSIZE)\n list_create.append(hasher.hexdigest())\n #print(list_create)\n# --------------------------------------------------------------------------------------------------\n# This Function records the hash of the files being monitored to a text file. This should only be\n# called when the program is being executed for the first time\n# --------------------------------------------------------------------------------------------------\ndef Create_record():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n os.chdir(dirpath)\n file = open('Record.txt',\"w\")\n for item in list_create:\n file.write(\"%s\\n\" % item)\n file.close()\n os.chdir(progpath)\n# --------------------------------------------------------------------------------------------------\n# This module parses the stored hashes and stores them into a fresh python list\n# --------------------------------------------------------------------------------------------------\ndef Read_hash():\n progpath = os.getcwd()\n dirpath = progpath + '/Details'\n os.chdir(dirpath) \n file = open('Record.txt', 'r')\n list_compare=[]\n list_compare = file.readlines()\n list_compare = [x[:-1] for x in list_compare]\n os.chdir(progpath)\n #print(list_compare)\n #print(list_create)\n if list_compare == list_create:\n Response(0)\n else:\n Response(1)\n# --------------------------------------------------------------------------------------------------\n# Once the change is detected this module is used to respond to the threat\n# flag ->>>> 1 Change is detected\n# flag ->>>> 0 No change\n# --------------------------------------------------------------------------------------------------\ndef Response(flag):\n if flag==1:\n print(\"Ladder Logic Tampered\")\n #Launch recovery routine\n else:\n print(\"Ladder Logic is Secure\")\n# --------------------------------------------------------------------------------------------------\n# The main Function\n# --------------------------------------------------------------------------------------------------\ndef main():\n Create_list()\n Hasher()\n print(list_create)\n Create_record()\n Read_hash() # First call with 0 argument\n while(1):\n Hasher()\n Read_hash() # Next calls are all performed by argument\n \n\n# 1. Create the folder for storing the new file->Done\n# 2. Module to compare the files with a new file->Done\n# 3. Module to backup the ladder logics\n# 4. Module to restore the ladder logic\n# 5. Reporting unit->Done\n# 6. Push code to GitHub->Done\n\nif __name__ == \"__main__\": main()\n", "step-ids": [ 5, 6, 8, 9, 10 ] }
[ 5, 6, 8, 9, 10 ]
import sys sys.path.append("../") import numpy as np import tensorflow as tf from utils import eval_accuracy_main_cdan from models import mnist2mnistm_shared_discrepancy, mnist2mnistm_predictor_discrepancy import keras import argparse import pickle as pkl parser = argparse.ArgumentParser(description='Training', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--USE_POISON', type=int, default=1, help='POISON used or not') args = parser.parse_args() USE_POISON = bool(args.USE_POISON) METHOD = "mcd" IMG_WIDTH = 28 IMG_HEIGHT = 28 NCH = 3 NUM_CLASSES_MAIN = 2 NUM_CLASSES_DC = 2 EPOCHS = 101 BATCH_SIZE = 64 PLOT_POINTS = 100 NUM_MODELS = 5 ce_loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True) shared = [mnist2mnistm_shared_discrepancy([50000, IMG_HEIGHT, IMG_WIDTH, NCH]) for i in range(NUM_MODELS)] main_classifier_1 = [mnist2mnistm_predictor_discrepancy(shared[i], NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)]#48*4*4, 500 main_classifier_2 = [mnist2mnistm_predictor_discrepancy(shared[i], NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)] optimizer_shared = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)] optimizer_main_classifier_1 = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)] optimizer_main_classifier_2 = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)] @tf.function def train_discrepancy_1(main_data, main_labels, target_data): # persistent is set to True because the tape is used more than # once to calculate the gradients. with tf.GradientTape(persistent=True) as tape: shared_main = [shared[i](main_data, training=True) for i in range(NUM_MODELS)] main_logits_1 = [main_classifier_1[i](shared_main[i], training=True) for i in range(NUM_MODELS)] main_logits_2 = [main_classifier_2[i](shared_main[i], training=True) for i in range(NUM_MODELS)] main_loss = [ce_loss(main_labels, main_logits_1[i]) + ce_loss(main_labels, main_logits_2[i]) for i in range(NUM_MODELS)] shared_target = [shared[i](target_data, training=True) for i in range(NUM_MODELS)] target_logits_1 = [main_classifier_1[i](shared_target[i], training=True) for i in range(NUM_MODELS)] target_logits_2 = [main_classifier_2[i](shared_target[i], training=True) for i in range(NUM_MODELS)] adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for i in range(NUM_MODELS)] loss = [main_loss[i] - adv_loss[i] for i in range(NUM_MODELS)] gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1[i].trainable_variables) for i in range(NUM_MODELS)] gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2[i].trainable_variables) for i in range(NUM_MODELS)] [optimizer_main_classifier_1[i].apply_gradients(zip(gradients_main_classifier_1[i], main_classifier_1[i].trainable_variables)) for i in range(NUM_MODELS)] [optimizer_main_classifier_2[i].apply_gradients(zip(gradients_main_classifier_2[i], main_classifier_2[i].trainable_variables)) for i in range(NUM_MODELS)] return adv_loss @tf.function def train_discrepancy_2(target_data): # persistent is set to True because the tape is used more than # once to calculate the gradients. with tf.GradientTape(persistent=True) as tape: shared_target = [shared[i](target_data, training=True) for i in range(NUM_MODELS)] target_logits_1 = [main_classifier_1[i](shared_target[i], training=True) for i in range(NUM_MODELS)] target_logits_2 = [main_classifier_2[i](shared_target[i], training=True) for i in range(NUM_MODELS)] adv_loss = [tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) - tf.nn.softmax(target_logits_2[i]))) for i in range(NUM_MODELS)] gradients_shared = [tape.gradient(adv_loss[i], shared[i].trainable_variables) for i in range(NUM_MODELS)] [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i].trainable_variables)) for i in range(NUM_MODELS)] return adv_loss @tf.function def train_step_erm(main_data, main_labels): # persistent is set to True because the tape is used more than # once to calculate the gradients. with tf.GradientTape(persistent=True) as tape: shared_main = [shared[i](main_data, training=True) for i in range(NUM_MODELS)] main_logits_1 = [main_classifier_1[i](shared_main[i], training=True) for i in range(NUM_MODELS)] main_logits_2 = [main_classifier_2[i](shared_main[i], training=True) for i in range(NUM_MODELS)] loss = [ce_loss(main_labels, main_logits_1[i]) + ce_loss(main_labels, main_logits_2[i]) for i in range(NUM_MODELS)] gradients_shared = [tape.gradient(loss[i], shared[i].trainable_variables) for i in range(NUM_MODELS)] gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1[i].trainable_variables) for i in range(NUM_MODELS)] gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2[i].trainable_variables) for i in range(NUM_MODELS)] [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i].trainable_variables)) for i in range(NUM_MODELS)] [optimizer_main_classifier_1[i].apply_gradients(zip(gradients_main_classifier_1[i], main_classifier_1[i].trainable_variables)) for i in range(NUM_MODELS)] [optimizer_main_classifier_2[i].apply_gradients(zip(gradients_main_classifier_2[i], main_classifier_2[i].trainable_variables)) for i in range(NUM_MODELS)] return loss mnist = tf.keras.datasets.mnist (x_train_mnist_all, y_train_mnist_all), (x_test_mnist_all, y_test_mnist_all) = mnist.load_data() x_train_mnist_all = np.stack((x_train_mnist_all,)*3, axis=-1)/255. x_test_mnist_all = np.stack((x_test_mnist_all,)*3, axis=-1)/255. mnistm = pkl.load(open('../../../../MNIST_MNIST-m/mnistm_data.pkl', 'rb')) x_train_mnistm_all = mnistm['train']/255. x_test_mnistm_all = mnistm['test']/255. picked_class = 3 picked_class_next = 8 train_points_class_0 = np.argwhere(y_train_mnist_all == picked_class).flatten() train_points_class_1 = np.argwhere(y_train_mnist_all == picked_class_next).flatten() test_points_class_0 = np.argwhere(y_test_mnist_all == picked_class).flatten() test_points_class_1 = np.argwhere(y_test_mnist_all == picked_class_next).flatten() x_train_mnist = x_train_mnist_all[np.concatenate([train_points_class_0, train_points_class_1])] y_train_mnist = y_train_mnist_all[np.concatenate([train_points_class_0, train_points_class_1])] x_test_mnist = x_test_mnist_all[np.concatenate([test_points_class_0, test_points_class_1])] y_test_mnist = y_test_mnist_all[np.concatenate([test_points_class_0, test_points_class_1])] x_train_mnistm = x_train_mnistm_all[np.concatenate([train_points_class_0, train_points_class_1])] x_test_mnistm = x_test_mnistm_all[np.concatenate([test_points_class_0, test_points_class_1])] zeros_train = np.argwhere(y_train_mnist == picked_class).flatten() ones_train = np.argwhere(y_train_mnist == picked_class_next).flatten() zeros_test = np.argwhere(y_test_mnist == picked_class).flatten() ones_test = np.argwhere(y_test_mnist == picked_class_next).flatten() y_train_mnist[zeros_train] = 0 y_train_mnist[ones_train] = 1 y_test_mnist[zeros_test] = 0 y_test_mnist[ones_test] = 1 y_train_mnist = keras.utils.to_categorical(y_train_mnist, NUM_CLASSES_MAIN) y_test_mnist = keras.utils.to_categorical(y_test_mnist, NUM_CLASSES_MAIN) x_target_test = np.load("data/" + METHOD + "_TARGET_DATA.npy") y_target_test = np.load("data/" + METHOD + "_TARGET_LABEL.npy") y_target_test_incorrect_label = np.zeros([1, NUM_CLASSES_MAIN]) target_correct_label = np.argmax(y_target_test,1).flatten()[0] y_target_test_incorrect_label[0][(target_correct_label+1)%NUM_CLASSES_MAIN]=1 if USE_POISON: x_poison = np.load("data/" + METHOD + "_GENERATED_POISON_DATA.npy") y_poison = np.load("data/" + METHOD + "_GENERATED_POISON_LABELS.npy") x_train_mnist = np.concatenate([x_train_mnist, x_poison]) y_train_mnist = np.concatenate([y_train_mnist, y_poison]) for epoch in range(EPOCHS): nb_batches_train = int(len(x_train_mnist)/BATCH_SIZE) if len(x_train_mnist) % BATCH_SIZE != 0: nb_batches_train += 1 ind_shuf = np.arange(len(x_train_mnist)) np.random.shuffle(ind_shuf) for batch in range(nb_batches_train): ind_batch = range(BATCH_SIZE * batch, min(BATCH_SIZE * (1+batch), len(x_train_mnist))) ind_source = ind_shuf[ind_batch] ind_target = np.random.choice(len(x_train_mnistm), size=len(ind_source), replace=False) x_source_batch = x_train_mnist[ind_source] y_source_batch = y_train_mnist[ind_source] x_target_batch = x_train_mnistm[ind_target] train_step_erm(x_source_batch, y_source_batch) train_discrepancy_1(x_source_batch, y_source_batch, x_target_batch) train_discrepancy_2(x_target_batch) if epoch % 20 == 0: print("Full training Poisoning:", USE_POISON, "MNIST->MNIST_M:", epoch, "METHOD:", METHOD, "\n") print([eval_accuracy_main_cdan(x_target_test, y_target_test_incorrect_label, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)]) print([eval_accuracy_main_cdan(x_target_test, y_target_test, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)]) print([eval_accuracy_main_cdan(x_test_mnistm, y_test_mnist, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)]) if USE_POISON: print([eval_accuracy_main_cdan(x_poison, y_poison, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)]) print("\n")
normal
{ "blob_id": "465d5baae8d5be77fbf3d550d10667da420a8fbe", "index": 8608, "step-1": "<mask token>\n\n\n@tf.function\ndef train_discrepancy_1(main_data, main_labels, target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(\n target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for\n i in range(NUM_MODELS)]\n loss = [(main_loss[i] - adv_loss[i]) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@tf.function\ndef train_discrepancy_1(main_data, main_labels, target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(\n target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for\n i in range(NUM_MODELS)]\n loss = [(main_loss[i] - adv_loss[i]) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_discrepancy_2(target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) -\n tf.nn.softmax(target_logits_2[i]))) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(adv_loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_step_erm(main_data, main_labels):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return loss\n\n\n<mask token>\n", "step-3": "<mask token>\nsys.path.append('../')\n<mask token>\nparser.add_argument('--USE_POISON', type=int, default=1, help=\n 'POISON used or not')\n<mask token>\n\n\n@tf.function\ndef train_discrepancy_1(main_data, main_labels, target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(\n target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for\n i in range(NUM_MODELS)]\n loss = [(main_loss[i] - adv_loss[i]) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_discrepancy_2(target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) -\n tf.nn.softmax(target_logits_2[i]))) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(adv_loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_step_erm(main_data, main_labels):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return loss\n\n\n<mask token>\nif USE_POISON:\n x_poison = np.load('data/' + METHOD + '_GENERATED_POISON_DATA.npy')\n y_poison = np.load('data/' + METHOD + '_GENERATED_POISON_LABELS.npy')\n x_train_mnist = np.concatenate([x_train_mnist, x_poison])\n y_train_mnist = np.concatenate([y_train_mnist, y_poison])\nfor epoch in range(EPOCHS):\n nb_batches_train = int(len(x_train_mnist) / BATCH_SIZE)\n if len(x_train_mnist) % BATCH_SIZE != 0:\n nb_batches_train += 1\n ind_shuf = np.arange(len(x_train_mnist))\n np.random.shuffle(ind_shuf)\n for batch in range(nb_batches_train):\n ind_batch = range(BATCH_SIZE * batch, min(BATCH_SIZE * (1 + batch),\n len(x_train_mnist)))\n ind_source = ind_shuf[ind_batch]\n ind_target = np.random.choice(len(x_train_mnistm), size=len(\n ind_source), replace=False)\n x_source_batch = x_train_mnist[ind_source]\n y_source_batch = y_train_mnist[ind_source]\n x_target_batch = x_train_mnistm[ind_target]\n train_step_erm(x_source_batch, y_source_batch)\n train_discrepancy_1(x_source_batch, y_source_batch, x_target_batch)\n train_discrepancy_2(x_target_batch)\n if epoch % 20 == 0:\n print('Full training Poisoning:', USE_POISON, 'MNIST->MNIST_M:',\n epoch, 'METHOD:', METHOD, '\\n')\n print([eval_accuracy_main_cdan(x_target_test,\n y_target_test_incorrect_label, shared[i], main_classifier_1[i]) for\n i in range(NUM_MODELS)])\n print([eval_accuracy_main_cdan(x_target_test, y_target_test, shared\n [i], main_classifier_1[i]) for i in range(NUM_MODELS)])\n print([eval_accuracy_main_cdan(x_test_mnistm, y_test_mnist, shared[\n i], main_classifier_1[i]) for i in range(NUM_MODELS)])\n if USE_POISON:\n print([eval_accuracy_main_cdan(x_poison, y_poison, shared[i],\n main_classifier_1[i]) for i in range(NUM_MODELS)])\n print('\\n')\n", "step-4": "<mask token>\nsys.path.append('../')\n<mask token>\nparser = argparse.ArgumentParser(description='Training', formatter_class=\n argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--USE_POISON', type=int, default=1, help=\n 'POISON used or not')\nargs = parser.parse_args()\nUSE_POISON = bool(args.USE_POISON)\nMETHOD = 'mcd'\nIMG_WIDTH = 28\nIMG_HEIGHT = 28\nNCH = 3\nNUM_CLASSES_MAIN = 2\nNUM_CLASSES_DC = 2\nEPOCHS = 101\nBATCH_SIZE = 64\nPLOT_POINTS = 100\nNUM_MODELS = 5\nce_loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\nshared = [mnist2mnistm_shared_discrepancy([50000, IMG_HEIGHT, IMG_WIDTH,\n NCH]) for i in range(NUM_MODELS)]\nmain_classifier_1 = [mnist2mnistm_predictor_discrepancy(shared[i],\n NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)]\nmain_classifier_2 = [mnist2mnistm_predictor_discrepancy(shared[i],\n NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)]\noptimizer_shared = [tf.keras.optimizers.Adam(0.001, beta_1=0.5) for i in\n range(NUM_MODELS)]\noptimizer_main_classifier_1 = [tf.keras.optimizers.Adam(0.001, beta_1=0.5) for\n i in range(NUM_MODELS)]\noptimizer_main_classifier_2 = [tf.keras.optimizers.Adam(0.001, beta_1=0.5) for\n i in range(NUM_MODELS)]\n\n\n@tf.function\ndef train_discrepancy_1(main_data, main_labels, target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(\n target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for\n i in range(NUM_MODELS)]\n loss = [(main_loss[i] - adv_loss[i]) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_discrepancy_2(target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_target = [shared[i](target_data, training=True) for i in\n range(NUM_MODELS)]\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=\n True) for i in range(NUM_MODELS)]\n adv_loss = [tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) -\n tf.nn.softmax(target_logits_2[i]))) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(adv_loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n return adv_loss\n\n\n@tf.function\ndef train_step_erm(main_data, main_labels):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n NUM_MODELS)]\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True\n ) for i in range(NUM_MODELS)]\n loss = [(ce_loss(main_labels, main_logits_1[i]) + ce_loss(\n main_labels, main_logits_2[i])) for i in range(NUM_MODELS)]\n gradients_shared = [tape.gradient(loss[i], shared[i].\n trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1\n [i].trainable_variables) for i in range(NUM_MODELS)]\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2\n [i].trainable_variables) for i in range(NUM_MODELS)]\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i]\n .trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_1[i].apply_gradients(zip(\n gradients_main_classifier_1[i], main_classifier_1[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n [optimizer_main_classifier_2[i].apply_gradients(zip(\n gradients_main_classifier_2[i], main_classifier_2[i].\n trainable_variables)) for i in range(NUM_MODELS)]\n return loss\n\n\nmnist = tf.keras.datasets.mnist\n(x_train_mnist_all, y_train_mnist_all), (x_test_mnist_all, y_test_mnist_all\n ) = mnist.load_data()\nx_train_mnist_all = np.stack((x_train_mnist_all,) * 3, axis=-1) / 255.0\nx_test_mnist_all = np.stack((x_test_mnist_all,) * 3, axis=-1) / 255.0\nmnistm = pkl.load(open('../../../../MNIST_MNIST-m/mnistm_data.pkl', 'rb'))\nx_train_mnistm_all = mnistm['train'] / 255.0\nx_test_mnistm_all = mnistm['test'] / 255.0\npicked_class = 3\npicked_class_next = 8\ntrain_points_class_0 = np.argwhere(y_train_mnist_all == picked_class).flatten()\ntrain_points_class_1 = np.argwhere(y_train_mnist_all == picked_class_next\n ).flatten()\ntest_points_class_0 = np.argwhere(y_test_mnist_all == picked_class).flatten()\ntest_points_class_1 = np.argwhere(y_test_mnist_all == picked_class_next\n ).flatten()\nx_train_mnist = x_train_mnist_all[np.concatenate([train_points_class_0,\n train_points_class_1])]\ny_train_mnist = y_train_mnist_all[np.concatenate([train_points_class_0,\n train_points_class_1])]\nx_test_mnist = x_test_mnist_all[np.concatenate([test_points_class_0,\n test_points_class_1])]\ny_test_mnist = y_test_mnist_all[np.concatenate([test_points_class_0,\n test_points_class_1])]\nx_train_mnistm = x_train_mnistm_all[np.concatenate([train_points_class_0,\n train_points_class_1])]\nx_test_mnistm = x_test_mnistm_all[np.concatenate([test_points_class_0,\n test_points_class_1])]\nzeros_train = np.argwhere(y_train_mnist == picked_class).flatten()\nones_train = np.argwhere(y_train_mnist == picked_class_next).flatten()\nzeros_test = np.argwhere(y_test_mnist == picked_class).flatten()\nones_test = np.argwhere(y_test_mnist == picked_class_next).flatten()\ny_train_mnist[zeros_train] = 0\ny_train_mnist[ones_train] = 1\ny_test_mnist[zeros_test] = 0\ny_test_mnist[ones_test] = 1\ny_train_mnist = keras.utils.to_categorical(y_train_mnist, NUM_CLASSES_MAIN)\ny_test_mnist = keras.utils.to_categorical(y_test_mnist, NUM_CLASSES_MAIN)\nx_target_test = np.load('data/' + METHOD + '_TARGET_DATA.npy')\ny_target_test = np.load('data/' + METHOD + '_TARGET_LABEL.npy')\ny_target_test_incorrect_label = np.zeros([1, NUM_CLASSES_MAIN])\ntarget_correct_label = np.argmax(y_target_test, 1).flatten()[0]\ny_target_test_incorrect_label[0][(target_correct_label + 1) % NUM_CLASSES_MAIN\n ] = 1\nif USE_POISON:\n x_poison = np.load('data/' + METHOD + '_GENERATED_POISON_DATA.npy')\n y_poison = np.load('data/' + METHOD + '_GENERATED_POISON_LABELS.npy')\n x_train_mnist = np.concatenate([x_train_mnist, x_poison])\n y_train_mnist = np.concatenate([y_train_mnist, y_poison])\nfor epoch in range(EPOCHS):\n nb_batches_train = int(len(x_train_mnist) / BATCH_SIZE)\n if len(x_train_mnist) % BATCH_SIZE != 0:\n nb_batches_train += 1\n ind_shuf = np.arange(len(x_train_mnist))\n np.random.shuffle(ind_shuf)\n for batch in range(nb_batches_train):\n ind_batch = range(BATCH_SIZE * batch, min(BATCH_SIZE * (1 + batch),\n len(x_train_mnist)))\n ind_source = ind_shuf[ind_batch]\n ind_target = np.random.choice(len(x_train_mnistm), size=len(\n ind_source), replace=False)\n x_source_batch = x_train_mnist[ind_source]\n y_source_batch = y_train_mnist[ind_source]\n x_target_batch = x_train_mnistm[ind_target]\n train_step_erm(x_source_batch, y_source_batch)\n train_discrepancy_1(x_source_batch, y_source_batch, x_target_batch)\n train_discrepancy_2(x_target_batch)\n if epoch % 20 == 0:\n print('Full training Poisoning:', USE_POISON, 'MNIST->MNIST_M:',\n epoch, 'METHOD:', METHOD, '\\n')\n print([eval_accuracy_main_cdan(x_target_test,\n y_target_test_incorrect_label, shared[i], main_classifier_1[i]) for\n i in range(NUM_MODELS)])\n print([eval_accuracy_main_cdan(x_target_test, y_target_test, shared\n [i], main_classifier_1[i]) for i in range(NUM_MODELS)])\n print([eval_accuracy_main_cdan(x_test_mnistm, y_test_mnist, shared[\n i], main_classifier_1[i]) for i in range(NUM_MODELS)])\n if USE_POISON:\n print([eval_accuracy_main_cdan(x_poison, y_poison, shared[i],\n main_classifier_1[i]) for i in range(NUM_MODELS)])\n print('\\n')\n", "step-5": "import sys\r\nsys.path.append(\"../\")\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom utils import eval_accuracy_main_cdan\r\nfrom models import mnist2mnistm_shared_discrepancy, mnist2mnistm_predictor_discrepancy\r\nimport keras\r\nimport argparse\r\nimport pickle as pkl \r\n\r\nparser = argparse.ArgumentParser(description='Training', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\nparser.add_argument('--USE_POISON', type=int, default=1, help='POISON used or not')\r\nargs = parser.parse_args()\r\nUSE_POISON = bool(args.USE_POISON)\r\nMETHOD = \"mcd\"\r\n\r\nIMG_WIDTH = 28\r\nIMG_HEIGHT = 28\r\nNCH = 3\r\n\r\nNUM_CLASSES_MAIN = 2\r\nNUM_CLASSES_DC = 2\r\n\r\nEPOCHS = 101\r\nBATCH_SIZE = 64\r\nPLOT_POINTS = 100\r\n\r\nNUM_MODELS = 5\r\n\r\nce_loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\r\n\r\nshared = [mnist2mnistm_shared_discrepancy([50000, IMG_HEIGHT, IMG_WIDTH, NCH]) for i in range(NUM_MODELS)]\r\n\r\nmain_classifier_1 = [mnist2mnistm_predictor_discrepancy(shared[i], NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)]#48*4*4, 500\r\nmain_classifier_2 = [mnist2mnistm_predictor_discrepancy(shared[i], NUM_CLASSES_MAIN, 768) for i in range(NUM_MODELS)]\r\n\r\noptimizer_shared = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)]\r\n\r\noptimizer_main_classifier_1 = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)]\r\noptimizer_main_classifier_2 = [tf.keras.optimizers.Adam(1E-3, beta_1=0.5) for i in range(NUM_MODELS)]\r\n\r\n@tf.function\r\ndef train_discrepancy_1(main_data, main_labels, target_data):\r\n # persistent is set to True because the tape is used more than\r\n # once to calculate the gradients.\r\n \r\n with tf.GradientTape(persistent=True) as tape:\r\n shared_main = [shared[i](main_data, training=True) for i in range(NUM_MODELS)]\r\n \r\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True) for i in range(NUM_MODELS)]\r\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True) for i in range(NUM_MODELS)]\r\n \r\n main_loss = [ce_loss(main_labels, main_logits_1[i]) + ce_loss(main_labels, main_logits_2[i]) for i in range(NUM_MODELS)]\r\n \r\n shared_target = [shared[i](target_data, training=True) for i in range(NUM_MODELS)]\r\n \r\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=True) for i in range(NUM_MODELS)]\r\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=True) for i in range(NUM_MODELS)]\r\n \r\n adv_loss = [tf.reduce_mean(tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) - tf.nn.softmax(target_logits_2[i])), 1)) for i in range(NUM_MODELS)]\r\n \r\n loss = [main_loss[i] - adv_loss[i] for i in range(NUM_MODELS)]\r\n \r\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1[i].trainable_variables) for i in range(NUM_MODELS)]\r\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2[i].trainable_variables) for i in range(NUM_MODELS)]\r\n \r\n [optimizer_main_classifier_1[i].apply_gradients(zip(gradients_main_classifier_1[i], main_classifier_1[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n [optimizer_main_classifier_2[i].apply_gradients(zip(gradients_main_classifier_2[i], main_classifier_2[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n \r\n return adv_loss\r\n\r\n@tf.function\r\ndef train_discrepancy_2(target_data):\r\n # persistent is set to True because the tape is used more than\r\n # once to calculate the gradients.\r\n \r\n with tf.GradientTape(persistent=True) as tape:\r\n shared_target = [shared[i](target_data, training=True) for i in range(NUM_MODELS)]\r\n \r\n target_logits_1 = [main_classifier_1[i](shared_target[i], training=True) for i in range(NUM_MODELS)]\r\n target_logits_2 = [main_classifier_2[i](shared_target[i], training=True) for i in range(NUM_MODELS)]\r\n \r\n adv_loss = [tf.reduce_mean(tf.abs(tf.nn.softmax(target_logits_1[i]) - tf.nn.softmax(target_logits_2[i]))) for i in range(NUM_MODELS)]\r\n \r\n gradients_shared = [tape.gradient(adv_loss[i], shared[i].trainable_variables) for i in range(NUM_MODELS)]\r\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n \r\n return adv_loss\r\n\r\n\r\n@tf.function\r\ndef train_step_erm(main_data, main_labels):\r\n # persistent is set to True because the tape is used more than\r\n # once to calculate the gradients.\r\n \r\n with tf.GradientTape(persistent=True) as tape:\r\n shared_main = [shared[i](main_data, training=True) for i in range(NUM_MODELS)]\r\n \r\n main_logits_1 = [main_classifier_1[i](shared_main[i], training=True) for i in range(NUM_MODELS)]\r\n main_logits_2 = [main_classifier_2[i](shared_main[i], training=True) for i in range(NUM_MODELS)]\r\n \r\n loss = [ce_loss(main_labels, main_logits_1[i]) + ce_loss(main_labels, main_logits_2[i]) for i in range(NUM_MODELS)]\r\n\r\n gradients_shared = [tape.gradient(loss[i], shared[i].trainable_variables) for i in range(NUM_MODELS)]\r\n gradients_main_classifier_1 = [tape.gradient(loss[i], main_classifier_1[i].trainable_variables) for i in range(NUM_MODELS)]\r\n gradients_main_classifier_2 = [tape.gradient(loss[i], main_classifier_2[i].trainable_variables) for i in range(NUM_MODELS)]\r\n \r\n [optimizer_shared[i].apply_gradients(zip(gradients_shared[i], shared[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n [optimizer_main_classifier_1[i].apply_gradients(zip(gradients_main_classifier_1[i], main_classifier_1[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n [optimizer_main_classifier_2[i].apply_gradients(zip(gradients_main_classifier_2[i], main_classifier_2[i].trainable_variables)) for i in range(NUM_MODELS)]\r\n \r\n return loss\r\n\r\nmnist = tf.keras.datasets.mnist\r\n(x_train_mnist_all, y_train_mnist_all), (x_test_mnist_all, y_test_mnist_all) = mnist.load_data()\r\n\r\nx_train_mnist_all = np.stack((x_train_mnist_all,)*3, axis=-1)/255.\r\nx_test_mnist_all = np.stack((x_test_mnist_all,)*3, axis=-1)/255.\r\n\r\nmnistm = pkl.load(open('../../../../MNIST_MNIST-m/mnistm_data.pkl', 'rb'))\r\nx_train_mnistm_all = mnistm['train']/255.\r\nx_test_mnistm_all = mnistm['test']/255.\r\n\r\npicked_class = 3\r\npicked_class_next = 8\r\n\r\ntrain_points_class_0 = np.argwhere(y_train_mnist_all == picked_class).flatten()\r\ntrain_points_class_1 = np.argwhere(y_train_mnist_all == picked_class_next).flatten()\r\n\r\ntest_points_class_0 = np.argwhere(y_test_mnist_all == picked_class).flatten()\r\ntest_points_class_1 = np.argwhere(y_test_mnist_all == picked_class_next).flatten()\r\n\r\nx_train_mnist = x_train_mnist_all[np.concatenate([train_points_class_0, train_points_class_1])]\r\ny_train_mnist = y_train_mnist_all[np.concatenate([train_points_class_0, train_points_class_1])]\r\n\r\nx_test_mnist = x_test_mnist_all[np.concatenate([test_points_class_0, test_points_class_1])]\r\ny_test_mnist = y_test_mnist_all[np.concatenate([test_points_class_0, test_points_class_1])]\r\n\r\nx_train_mnistm = x_train_mnistm_all[np.concatenate([train_points_class_0, train_points_class_1])]\r\nx_test_mnistm = x_test_mnistm_all[np.concatenate([test_points_class_0, test_points_class_1])]\r\n\r\nzeros_train = np.argwhere(y_train_mnist == picked_class).flatten()\r\nones_train = np.argwhere(y_train_mnist == picked_class_next).flatten()\r\nzeros_test = np.argwhere(y_test_mnist == picked_class).flatten()\r\nones_test = np.argwhere(y_test_mnist == picked_class_next).flatten()\r\n\r\ny_train_mnist[zeros_train] = 0\r\ny_train_mnist[ones_train] = 1\r\ny_test_mnist[zeros_test] = 0\r\ny_test_mnist[ones_test] = 1\r\n\r\ny_train_mnist = keras.utils.to_categorical(y_train_mnist, NUM_CLASSES_MAIN)\r\ny_test_mnist = keras.utils.to_categorical(y_test_mnist, NUM_CLASSES_MAIN)\r\n\r\nx_target_test = np.load(\"data/\" + METHOD + \"_TARGET_DATA.npy\")\r\ny_target_test = np.load(\"data/\" + METHOD + \"_TARGET_LABEL.npy\")\r\ny_target_test_incorrect_label = np.zeros([1, NUM_CLASSES_MAIN])\r\ntarget_correct_label = np.argmax(y_target_test,1).flatten()[0]\r\ny_target_test_incorrect_label[0][(target_correct_label+1)%NUM_CLASSES_MAIN]=1\r\n\r\nif USE_POISON:\r\n\r\n x_poison = np.load(\"data/\" + METHOD + \"_GENERATED_POISON_DATA.npy\")\r\n y_poison = np.load(\"data/\" + METHOD + \"_GENERATED_POISON_LABELS.npy\") \r\n\r\n x_train_mnist = np.concatenate([x_train_mnist, x_poison])\r\n y_train_mnist = np.concatenate([y_train_mnist, y_poison])\r\n \r\nfor epoch in range(EPOCHS):\r\n nb_batches_train = int(len(x_train_mnist)/BATCH_SIZE)\r\n if len(x_train_mnist) % BATCH_SIZE != 0:\r\n nb_batches_train += 1\r\n ind_shuf = np.arange(len(x_train_mnist))\r\n np.random.shuffle(ind_shuf)\r\n \r\n for batch in range(nb_batches_train):\r\n ind_batch = range(BATCH_SIZE * batch, min(BATCH_SIZE * (1+batch), len(x_train_mnist)))\r\n ind_source = ind_shuf[ind_batch]\r\n \r\n ind_target = np.random.choice(len(x_train_mnistm), size=len(ind_source), replace=False)\r\n \r\n x_source_batch = x_train_mnist[ind_source]\r\n y_source_batch = y_train_mnist[ind_source]\r\n \r\n x_target_batch = x_train_mnistm[ind_target]\r\n \r\n train_step_erm(x_source_batch, y_source_batch)\r\n train_discrepancy_1(x_source_batch, y_source_batch, x_target_batch)\r\n train_discrepancy_2(x_target_batch)\r\n \r\n if epoch % 20 == 0: \r\n print(\"Full training Poisoning:\", USE_POISON, \"MNIST->MNIST_M:\", epoch, \"METHOD:\", METHOD, \"\\n\")\r\n print([eval_accuracy_main_cdan(x_target_test, y_target_test_incorrect_label, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)])\r\n print([eval_accuracy_main_cdan(x_target_test, y_target_test, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)])\r\n print([eval_accuracy_main_cdan(x_test_mnistm, y_test_mnist, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)])\r\n if USE_POISON:\r\n print([eval_accuracy_main_cdan(x_poison, y_poison, shared[i], main_classifier_1[i]) for i in range(NUM_MODELS)])\r\n print(\"\\n\")\r\n \r\n", "step-ids": [ 1, 3, 4, 5, 7 ] }
[ 1, 3, 4, 5, 7 ]
def check_ip_or_mask(temp_str): IPv4_regex = (r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}') temp_list_ip_mask = re.findall(IPv4_regex, temp_str) binary_temp_list_ip_mask = [] temp_binary_ip_mask = '' for x in range(len(temp_list_ip_mask)): split_ip_address = re.split(r'\.', temp_list_ip_mask[x]) for y in range(len(split_ip_address)): temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8)) binary_temp_list_ip_mask.append(temp_binary_ip_mask) temp_binary_ip_mask = '' ip_index_list = [] mask_index_list = [] for x in range(2): if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]): ip_index_list.append(x) if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]): mask_index_list.append(x) if len(ip_index_list) == 1 and len(mask_index_list) == 1: ipv4 = temp_list_ip_mask[int(ip_index_list[0])] net_mask = temp_list_ip_mask[int(mask_index_list[0])] else: if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')): ipv4 = temp_list_ip_mask[0] net_mask = temp_list_ip_mask[1] else: ipv4 = temp_list_ip_mask[1] net_mask = temp_list_ip_mask[0] return "IPv4: " + ipv4 + "\n" + "Net mask: " + net_mask
normal
{ "blob_id": "fe597ad4462b1af3f3f99346c759c5fa8a7c14f4", "index": 741, "step-1": "<mask token>\n", "step-2": "def check_ip_or_mask(temp_str):\n IPv4_regex = '(?:[0-9]{1,3}\\\\.){3}[0-9]{1,3}'\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split('\\\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].\n zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n elif binary_temp_list_ip_mask[0].count('1') < binary_temp_list_ip_mask[0\n ].count('1'):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n return 'IPv4: ' + ipv4 + '\\n' + 'Net mask: ' + net_mask\n", "step-3": "def check_ip_or_mask(temp_str):\n IPv4_regex = (r'(?:[0-9]{1,3}\\.){3}[0-9]{1,3}')\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split(r'\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n else:\n if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n\n return \"IPv4: \" + ipv4 + \"\\n\" + \"Net mask: \" + net_mask\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#Author: AKHILESH #This program illustrates the advanced concepts of inheritance #Python looks up for method in following order: Instance attributes, class attributes and the #from the base class #mro: Method Resolution order class Data(object): def __init__(self, data): self.data = data def getData(self): print('Data:',self.data) class Time(Data): #Inhertiting from Data class def getTime(self): print('Time:',self.data) if __name__ == '__main__': data = Data(10) time = Time(20) #inherited Class -> Value passed to __init__of Data (Base class) time.getTime() data.getData() time.getData() print(Time.mro())
normal
{ "blob_id": "153a33b85cf8b3ef9c742f05b460e94e0c684682", "index": 1000, "step-1": "class Data(object):\n <mask token>\n <mask token>\n\n\nclass Time(Data):\n\n def getTime(self):\n print('Time:', self.data)\n\n\n<mask token>\n", "step-2": "class Data(object):\n\n def __init__(self, data):\n self.data = data\n <mask token>\n\n\nclass Time(Data):\n\n def getTime(self):\n print('Time:', self.data)\n\n\n<mask token>\n", "step-3": "class Data(object):\n\n def __init__(self, data):\n self.data = data\n\n def getData(self):\n print('Data:', self.data)\n\n\nclass Time(Data):\n\n def getTime(self):\n print('Time:', self.data)\n\n\n<mask token>\n", "step-4": "class Data(object):\n\n def __init__(self, data):\n self.data = data\n\n def getData(self):\n print('Data:', self.data)\n\n\nclass Time(Data):\n\n def getTime(self):\n print('Time:', self.data)\n\n\nif __name__ == '__main__':\n data = Data(10)\n time = Time(20)\n time.getTime()\n data.getData()\n time.getData()\n print(Time.mro())\n", "step-5": "#Author: AKHILESH\n#This program illustrates the advanced concepts of inheritance\n#Python looks up for method in following order: Instance attributes, class attributes and the\n#from the base class\n#mro: Method Resolution order\n\nclass Data(object):\n def __init__(self, data):\n self.data = data\n\n def getData(self):\n print('Data:',self.data)\n\nclass Time(Data): #Inhertiting from Data class\n def getTime(self):\n print('Time:',self.data)\n\nif __name__ == '__main__':\n data = Data(10)\n time = Time(20) #inherited Class -> Value passed to __init__of Data (Base class)\n\n time.getTime()\n data.getData()\n time.getData()\n\n print(Time.mro())\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# 上传文件 import os from selenium import webdriver # 获取当前路径的 “files” 文件夹 file_path = os.path.abspath("./files//") # 浏览器打开文件夹的 upfile.html 文件 driver = webdriver.Firefox() upload_page = "file:///" + file_path + "/upfile.html" driver.get(upload_page) # 定位上传按钮,添加本地文件 driver.find_element_by_id("inputfile").send_keys(file_path + "\\test.txt")
normal
{ "blob_id": "9e28fa1f221df13f9cc8e6b71586da961ebdc0e0", "index": 4580, "step-1": "<mask token>\n", "step-2": "<mask token>\ndriver.get(upload_page)\ndriver.find_element_by_id('inputfile').send_keys(file_path + '\\\\test.txt')\n", "step-3": "<mask token>\nfile_path = os.path.abspath('./files//')\ndriver = webdriver.Firefox()\nupload_page = 'file:///' + file_path + '/upfile.html'\ndriver.get(upload_page)\ndriver.find_element_by_id('inputfile').send_keys(file_path + '\\\\test.txt')\n", "step-4": "import os\nfrom selenium import webdriver\nfile_path = os.path.abspath('./files//')\ndriver = webdriver.Firefox()\nupload_page = 'file:///' + file_path + '/upfile.html'\ndriver.get(upload_page)\ndriver.find_element_by_id('inputfile').send_keys(file_path + '\\\\test.txt')\n", "step-5": "# 上传文件\n\nimport os\nfrom selenium import webdriver\n\n# 获取当前路径的 “files” 文件夹\nfile_path = os.path.abspath(\"./files//\")\n\n# 浏览器打开文件夹的 upfile.html 文件\ndriver = webdriver.Firefox()\nupload_page = \"file:///\" + file_path + \"/upfile.html\"\ndriver.get(upload_page)\n\n# 定位上传按钮,添加本地文件\ndriver.find_element_by_id(\"inputfile\").send_keys(file_path + \"\\\\test.txt\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Rec1(object): def setupUi(self, Rec1): Rec1.setObjectName("Rec1") Rec1.setFixedSize(450, 200) ico = QtGui.QIcon("mylogo.png") Rec1.setWindowIcon(ico) font = QtGui.QFont() font.setFamily("Times New Roman") font.setPointSize(14) self.centralwidget = QtWidgets.QWidget(Rec1) self.centralwidget.setObjectName("centralwidget") self.pushButton_photo = QtWidgets.QPushButton(self.centralwidget) self.pushButton_photo.setGeometry(QtCore.QRect(50, 20, 350, 30)) self.pushButton_photo.setFont(font) self.pushButton_photo.setObjectName("pushButton_photo") self.pushButton_video = QtWidgets.QPushButton(self.centralwidget) self.pushButton_video.setGeometry(QtCore.QRect(50, 60, 350, 30)) self.pushButton_video.setFont(font) self.pushButton_video.setObjectName("pushButton_video") self.pushButton_camera = QtWidgets.QPushButton(self.centralwidget) self.pushButton_camera.setGeometry(QtCore.QRect(50, 100, 350, 30)) self.pushButton_camera.setFont(font) self.pushButton_camera.setObjectName("pushButton_camera") self.pushButton_back = QtWidgets.QPushButton(self.centralwidget) self.pushButton_back.setGeometry(QtCore.QRect(50, 140, 170, 30)) self.pushButton_back.setFont(font) self.pushButton_back.setObjectName("pushButton_back") self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget) self.pushButton_exit.setGeometry(QtCore.QRect(230, 140, 170, 30)) self.pushButton_exit.setFont(font) self.pushButton_exit.setObjectName("pushButton_exit") Rec1.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(Rec1) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") Rec1.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(Rec1) self.statusbar.setObjectName("statusbar") Rec1.setStatusBar(self.statusbar) self.retranslateUi(Rec1) QtCore.QMetaObject.connectSlotsByName(Rec1) def retranslateUi(self, Rec1): _translate = QtCore.QCoreApplication.translate Rec1.setWindowTitle(_translate("Rec1", "Recognition")) self.pushButton_photo.setText(_translate("Rec1", "Распознавание по фото")) self.pushButton_video.setText(_translate("Rec1", "Распознавие по видео")) self.pushButton_camera.setText(_translate("Rec1", "Распознавание с помощью веб-камеры")) self.pushButton_back.setText(_translate("Rec1", "Назад")) self.pushButton_exit.setText(_translate("Rec1", "Выход"))
normal
{ "blob_id": "c500ecaa66672ac960dc548c3f3882e4bc196745", "index": 6870, "step-1": "<mask token>\n\n\nclass Ui_Rec1(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Ui_Rec1(object):\n <mask token>\n\n def retranslateUi(self, Rec1):\n _translate = QtCore.QCoreApplication.translate\n Rec1.setWindowTitle(_translate('Rec1', 'Recognition'))\n self.pushButton_photo.setText(_translate('Rec1',\n 'Распознавание по фото'))\n self.pushButton_video.setText(_translate('Rec1',\n 'Распознавие по видео'))\n self.pushButton_camera.setText(_translate('Rec1',\n 'Распознавание с помощью веб-камеры'))\n self.pushButton_back.setText(_translate('Rec1', 'Назад'))\n self.pushButton_exit.setText(_translate('Rec1', 'Выход'))\n", "step-3": "<mask token>\n\n\nclass Ui_Rec1(object):\n\n def setupUi(self, Rec1):\n Rec1.setObjectName('Rec1')\n Rec1.setFixedSize(450, 200)\n ico = QtGui.QIcon('mylogo.png')\n Rec1.setWindowIcon(ico)\n font = QtGui.QFont()\n font.setFamily('Times New Roman')\n font.setPointSize(14)\n self.centralwidget = QtWidgets.QWidget(Rec1)\n self.centralwidget.setObjectName('centralwidget')\n self.pushButton_photo = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_photo.setGeometry(QtCore.QRect(50, 20, 350, 30))\n self.pushButton_photo.setFont(font)\n self.pushButton_photo.setObjectName('pushButton_photo')\n self.pushButton_video = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_video.setGeometry(QtCore.QRect(50, 60, 350, 30))\n self.pushButton_video.setFont(font)\n self.pushButton_video.setObjectName('pushButton_video')\n self.pushButton_camera = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_camera.setGeometry(QtCore.QRect(50, 100, 350, 30))\n self.pushButton_camera.setFont(font)\n self.pushButton_camera.setObjectName('pushButton_camera')\n self.pushButton_back = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_back.setGeometry(QtCore.QRect(50, 140, 170, 30))\n self.pushButton_back.setFont(font)\n self.pushButton_back.setObjectName('pushButton_back')\n self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_exit.setGeometry(QtCore.QRect(230, 140, 170, 30))\n self.pushButton_exit.setFont(font)\n self.pushButton_exit.setObjectName('pushButton_exit')\n Rec1.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(Rec1)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))\n self.menubar.setObjectName('menubar')\n Rec1.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(Rec1)\n self.statusbar.setObjectName('statusbar')\n Rec1.setStatusBar(self.statusbar)\n self.retranslateUi(Rec1)\n QtCore.QMetaObject.connectSlotsByName(Rec1)\n\n def retranslateUi(self, Rec1):\n _translate = QtCore.QCoreApplication.translate\n Rec1.setWindowTitle(_translate('Rec1', 'Recognition'))\n self.pushButton_photo.setText(_translate('Rec1',\n 'Распознавание по фото'))\n self.pushButton_video.setText(_translate('Rec1',\n 'Распознавие по видео'))\n self.pushButton_camera.setText(_translate('Rec1',\n 'Распознавание с помощью веб-камеры'))\n self.pushButton_back.setText(_translate('Rec1', 'Назад'))\n self.pushButton_exit.setText(_translate('Rec1', 'Выход'))\n", "step-4": "from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Rec1(object):\n\n def setupUi(self, Rec1):\n Rec1.setObjectName('Rec1')\n Rec1.setFixedSize(450, 200)\n ico = QtGui.QIcon('mylogo.png')\n Rec1.setWindowIcon(ico)\n font = QtGui.QFont()\n font.setFamily('Times New Roman')\n font.setPointSize(14)\n self.centralwidget = QtWidgets.QWidget(Rec1)\n self.centralwidget.setObjectName('centralwidget')\n self.pushButton_photo = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_photo.setGeometry(QtCore.QRect(50, 20, 350, 30))\n self.pushButton_photo.setFont(font)\n self.pushButton_photo.setObjectName('pushButton_photo')\n self.pushButton_video = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_video.setGeometry(QtCore.QRect(50, 60, 350, 30))\n self.pushButton_video.setFont(font)\n self.pushButton_video.setObjectName('pushButton_video')\n self.pushButton_camera = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_camera.setGeometry(QtCore.QRect(50, 100, 350, 30))\n self.pushButton_camera.setFont(font)\n self.pushButton_camera.setObjectName('pushButton_camera')\n self.pushButton_back = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_back.setGeometry(QtCore.QRect(50, 140, 170, 30))\n self.pushButton_back.setFont(font)\n self.pushButton_back.setObjectName('pushButton_back')\n self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_exit.setGeometry(QtCore.QRect(230, 140, 170, 30))\n self.pushButton_exit.setFont(font)\n self.pushButton_exit.setObjectName('pushButton_exit')\n Rec1.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(Rec1)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))\n self.menubar.setObjectName('menubar')\n Rec1.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(Rec1)\n self.statusbar.setObjectName('statusbar')\n Rec1.setStatusBar(self.statusbar)\n self.retranslateUi(Rec1)\n QtCore.QMetaObject.connectSlotsByName(Rec1)\n\n def retranslateUi(self, Rec1):\n _translate = QtCore.QCoreApplication.translate\n Rec1.setWindowTitle(_translate('Rec1', 'Recognition'))\n self.pushButton_photo.setText(_translate('Rec1',\n 'Распознавание по фото'))\n self.pushButton_video.setText(_translate('Rec1',\n 'Распознавие по видео'))\n self.pushButton_camera.setText(_translate('Rec1',\n 'Распознавание с помощью веб-камеры'))\n self.pushButton_back.setText(_translate('Rec1', 'Назад'))\n self.pushButton_exit.setText(_translate('Rec1', 'Выход'))\n", "step-5": "from PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Rec1(object):\n def setupUi(self, Rec1):\n Rec1.setObjectName(\"Rec1\")\n Rec1.setFixedSize(450, 200)\n ico = QtGui.QIcon(\"mylogo.png\")\n Rec1.setWindowIcon(ico)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(14)\n \n self.centralwidget = QtWidgets.QWidget(Rec1)\n self.centralwidget.setObjectName(\"centralwidget\")\n \n self.pushButton_photo = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_photo.setGeometry(QtCore.QRect(50, 20, 350, 30))\n self.pushButton_photo.setFont(font)\n self.pushButton_photo.setObjectName(\"pushButton_photo\")\n \n self.pushButton_video = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_video.setGeometry(QtCore.QRect(50, 60, 350, 30))\n self.pushButton_video.setFont(font)\n self.pushButton_video.setObjectName(\"pushButton_video\")\n \n self.pushButton_camera = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_camera.setGeometry(QtCore.QRect(50, 100, 350, 30))\n self.pushButton_camera.setFont(font)\n self.pushButton_camera.setObjectName(\"pushButton_camera\")\n \n self.pushButton_back = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_back.setGeometry(QtCore.QRect(50, 140, 170, 30))\n self.pushButton_back.setFont(font)\n self.pushButton_back.setObjectName(\"pushButton_back\")\n \n self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_exit.setGeometry(QtCore.QRect(230, 140, 170, 30))\n self.pushButton_exit.setFont(font)\n self.pushButton_exit.setObjectName(\"pushButton_exit\")\n\n Rec1.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(Rec1)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))\n self.menubar.setObjectName(\"menubar\")\n Rec1.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(Rec1)\n self.statusbar.setObjectName(\"statusbar\")\n Rec1.setStatusBar(self.statusbar)\n\n self.retranslateUi(Rec1)\n QtCore.QMetaObject.connectSlotsByName(Rec1)\n\n def retranslateUi(self, Rec1):\n _translate = QtCore.QCoreApplication.translate\n Rec1.setWindowTitle(_translate(\"Rec1\", \"Recognition\"))\n self.pushButton_photo.setText(_translate(\"Rec1\", \"Распознавание по фото\"))\n self.pushButton_video.setText(_translate(\"Rec1\", \"Распознавие по видео\"))\n self.pushButton_camera.setText(_translate(\"Rec1\", \"Распознавание с помощью веб-камеры\"))\n self.pushButton_back.setText(_translate(\"Rec1\", \"Назад\"))\n self.pushButton_exit.setText(_translate(\"Rec1\", \"Выход\"))\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python3 #coding=utf-8 import sys import os import tool class BrandRegBasic(object): def __init__(self, base_folder, log_instance): if not os.path.exists(base_folder): raise Exception("%s does not exists!" % base_folder) self._real_brand_p = base_folder + "/real_brand.txt" if not os.path.exists(self._real_brand_p): raise Exception("%s does not exists!" % self._real_brand_p) # 注:word_dict.txt和error.txt是一样的功能 # 都是品牌改写,数据格式也一样 self._error_p = base_folder + '/error.txt' if not os.path.exists(self._error_p): raise Exception("%s does not exists!" % self._error_p) self._word_dict_p = base_folder + '/word_dict.txt' if not os.path.exists(self._word_dict_p): raise Exception("%s does not exists!" % self._word_dict_p) self._del_brand_p = base_folder + '/del_brand.txt' if not os.path.exists(self._del_brand_p): raise Exception("%s does not exists!" % self._del_brand_p) self.logger = log_instance self.logger.info("get_real_brand") self.real_brand_set = self._get_real_brand() self.logger.info("get_exchange_brand_pair") self.exchange_brand_pair = self._get_exchange_brand_pair() self.logger.info("get_del_brand") self.del_brand_dict = self._get_del_brand() #通过真实品牌这个文件获取到真实品牌的元组 def _get_real_brand(self): # 根据real_brand进行品牌确定 if not os.path.exists(self._real_brand_p): raise Exception("%s does not exist!" % self._real_brand_p) real_brand_set = set() with open(self._real_brand_p) as f1: for line in f1: line = line.strip() if line == "": continue real_brand_set.add(line) self.logger.info("len of real_brand: %s" % len(real_brand_set)) return real_brand_set # no-using def _brand_pair_correction(self, exchange_dict, conflict_brand_set): # Tips: {1:2, 2:3, 3:4}这种情况会有错误 tmp_dict = {} for k, v in exchange_dict.items(): if k in conflict_brand_set: right_brand = exchange_dict[k] for k1, v1 in exchange_dict.items(): if v1 == k: tmp_dict[k1] = right_brand exchange_dict_ext = {} for k2, v2 in exchange_dict.items(): if k2 == v2: continue if k2 in conflict_brand_set: continue if k2 in tmp_dict: exchange_dict_ext[k2] = tmp_dict[k2] else: exchange_dict_ext[k2] = v2 return exchange_dict_ext def _brand_pair_checking(self, exchange_dict): s1 = set(list(exchange_dict.keys())) s2 = set(list(exchange_dict.values())) s3 = s1 & s2 if len(s3) > 0: self.logger.error("exchang-brand-pair has error, error brands is: %s" % "\t".join(list(s3))) return False, s3 else: return True, None def _get_exchange_brand_pair(self): exchange_dict = {} def _line_deal(line): line = line.strip() if line == "": return lst1 = line.split("|") if len(lst1) != 2: self.logger.info("wrong brand pair: %s" % line) return lst1 = [z.strip() for z in lst1] if lst1[0] != lst1[1]: exchange_dict[lst1[0]] = lst1[1] # 根据品牌确定的结果+error.txt获得需要修正的sname结果 if not os.path.exists(self._error_p): self.logger.info("%s does not exist!" % self._real_brand_p) else: with open(self._error_p) as f1: for line in f1: _line_deal(line) self.logger.info("len of exchang_brand_pair: %s" % len(exchange_dict)) if not os.path.exists(self._word_dict_p): self.logger.info("%s does not exist!" % self._real_brand_p) else: with open(self._word_dict_p) as f1: for line in f1: _line_deal(line) self.logger.info("len of exchang_brand_pair: %s" % len(exchange_dict)) # 品牌对检测 chk_flag, conflict_brand_set = self._brand_pair_checking(exchange_dict) if not chk_flag: err_s = "exchang-brand-pair error: %s" % "\t".join(list(conflict_brand_set)) self.logger.error(err_s) raise Exception(err_s) return exchange_dict def _get_del_brand(self): if not os.path.exists(self._del_brand_p): raise Exception("%s does not exist!" % self._real_brand_p) del_dict = {} with open(self._del_brand_p) as f1: for line in f1: line = line.strip() if line == "": continue del_dict[line] = 0 self.logger.info("len of del_brand: %s" % len(del_dict)) return del_dict class BrandReg(BrandRegBasic): def __init__(self, base_folder, log_instance, input_lst=None): super(BrandReg, self).__init__(base_folder, log_instance) input_file = base_folder + "/dp_brands_result.txt" if not os.path.exists(input_file): raise Exception("%s does not exist!" % input_file) output_file = base_folder + "/dp_brands_result.txt.brandreg" self._input_p = input_file self._input_lst = input_lst self._output_p = output_file def _brand_exchange(self, ori_brand): if ori_brand in self.exchange_brand_pair: return self.exchange_brand_pair[ori_brand] else: return ori_brand def brand_reg(self): stp1_lst = [] idx = 0 if self._input_lst != None and len(self._input_lst) > 0: self.logger.info("增量数据处理") for line in self._input_lst: idx += 1 if idx % 10000 == 0: self.logger.info(idx) line = line.strip() r = self.brand_rewrite(line) if r is None: continue stp1_lst.append(r) elif os.path.exists(self._input_p): f_input = open(self._input_p) for line in f_input: idx += 1 if idx % 100000 == 0: self.logger.info(idx) line = line.strip() r = self.brand_rewrite(line) if r is None: continue stp1_lst.append(r) f_input.close() else: raise Exception("输入增量数据为空!!!") if len(stp1_lst) < 1: raise Exception("增量数据处理后数据为空!!!") with open(self._output_p, 'w') as f3: f3.write("\n".join(stp1_lst)) f3.flush() def _real_brand_reg(self, s_name): tmp_brand = None """ attention: 这一步可能出现问题, 比如:东方骆驼,骆驼, 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面, 那么将导致【东方骆驼】变为【骆驼】 """ for r_b in self.real_brand_set: lst5 = s_name.split(r_b) if len(lst5) > 1: tmp_brand = r_b break return tmp_brand def brand_rewrite(self, line): line = line.strip() if line == "": self.logger.info("empty string!!") return None lst1 = line.split("\x01") if len(lst1) == 3: s_id, ori_name, s_brand = lst1 #取到相关的数据 s_brand = s_brand.strip() else: self.logger.info("brand_rewrite error data: %s" % line) return None s_name = tool.s_name_dealing(ori_name) if len(self.real_brand_set) > 0: if s_brand not in self.real_brand_set: ex_brand = self._real_brand_reg(s_name) #匹配过程。如果取到的数据当中没有在数据集中找到相同的品牌,则对这种数据处理一下,在一个数据集中去匹配,进行品牌的归并 tmp_brand = ex_brand if ex_brand != None else s_brand #如果对处理过的品牌就赋值给tmp_brand,否则直接赋值 else: tmp_brand = s_brand #如果在数据集中找到了直接赋值 else: tmp_brand = s_brand #如果没有数据集就直接赋值 # brand 修正 r_brand = self._brand_exchange(tmp_brand) # 错误品牌检测 if r_brand in self.del_brand_dict: r_brand = s_name return "\x01".join([s_id, ori_name, r_brand]) #拼接后返回结果
normal
{ "blob_id": "845d1251497df61dd2c23241016a049c695ad940", "index": 9193, "step-1": "<mask token>\n\n\nclass BrandReg(BrandRegBasic):\n\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + '/dp_brands_result.txt'\n if not os.path.exists(input_file):\n raise Exception('%s does not exist!' % input_file)\n output_file = base_folder + '/dp_brands_result.txt.brandreg'\n self._input_p = input_file\n self._input_lst = input_lst\n self._output_p = output_file\n\n def _brand_exchange(self, ori_brand):\n if ori_brand in self.exchange_brand_pair:\n return self.exchange_brand_pair[ori_brand]\n else:\n return ori_brand\n\n def brand_reg(self):\n stp1_lst = []\n idx = 0\n if self._input_lst != None and len(self._input_lst) > 0:\n self.logger.info('增量数据处理')\n for line in self._input_lst:\n idx += 1\n if idx % 10000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n elif os.path.exists(self._input_p):\n f_input = open(self._input_p)\n for line in f_input:\n idx += 1\n if idx % 100000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n f_input.close()\n else:\n raise Exception('输入增量数据为空!!!')\n if len(stp1_lst) < 1:\n raise Exception('增量数据处理后数据为空!!!')\n with open(self._output_p, 'w') as f3:\n f3.write('\\n'.join(stp1_lst))\n f3.flush()\n\n def _real_brand_reg(self, s_name):\n tmp_brand = None\n \"\"\"\n attention: 这一步可能出现问题, \n 比如:东方骆驼,骆驼, \n 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面,\n 那么将导致【东方骆驼】变为【骆驼】\n \"\"\"\n for r_b in self.real_brand_set:\n lst5 = s_name.split(r_b)\n if len(lst5) > 1:\n tmp_brand = r_b\n break\n return tmp_brand\n\n def brand_rewrite(self, line):\n line = line.strip()\n if line == '':\n self.logger.info('empty string!!')\n return None\n lst1 = line.split('\\x01')\n if len(lst1) == 3:\n s_id, ori_name, s_brand = lst1\n s_brand = s_brand.strip()\n else:\n self.logger.info('brand_rewrite error data: %s' % line)\n return None\n s_name = tool.s_name_dealing(ori_name)\n if len(self.real_brand_set) > 0:\n if s_brand not in self.real_brand_set:\n ex_brand = self._real_brand_reg(s_name)\n tmp_brand = ex_brand if ex_brand != None else s_brand\n else:\n tmp_brand = s_brand\n else:\n tmp_brand = s_brand\n r_brand = self._brand_exchange(tmp_brand)\n if r_brand in self.del_brand_dict:\n r_brand = s_name\n return '\\x01'.join([s_id, ori_name, r_brand])\n", "step-2": "<mask token>\n\n\nclass BrandRegBasic(object):\n\n def __init__(self, base_folder, log_instance):\n if not os.path.exists(base_folder):\n raise Exception('%s does not exists!' % base_folder)\n self._real_brand_p = base_folder + '/real_brand.txt'\n if not os.path.exists(self._real_brand_p):\n raise Exception('%s does not exists!' % self._real_brand_p)\n self._error_p = base_folder + '/error.txt'\n if not os.path.exists(self._error_p):\n raise Exception('%s does not exists!' % self._error_p)\n self._word_dict_p = base_folder + '/word_dict.txt'\n if not os.path.exists(self._word_dict_p):\n raise Exception('%s does not exists!' % self._word_dict_p)\n self._del_brand_p = base_folder + '/del_brand.txt'\n if not os.path.exists(self._del_brand_p):\n raise Exception('%s does not exists!' % self._del_brand_p)\n self.logger = log_instance\n self.logger.info('get_real_brand')\n self.real_brand_set = self._get_real_brand()\n self.logger.info('get_exchange_brand_pair')\n self.exchange_brand_pair = self._get_exchange_brand_pair()\n self.logger.info('get_del_brand')\n self.del_brand_dict = self._get_del_brand()\n <mask token>\n <mask token>\n\n def _brand_pair_checking(self, exchange_dict):\n s1 = set(list(exchange_dict.keys()))\n s2 = set(list(exchange_dict.values()))\n s3 = s1 & s2\n if len(s3) > 0:\n self.logger.error(\n 'exchang-brand-pair has error, error brands is: %s' % '\\t'.\n join(list(s3)))\n return False, s3\n else:\n return True, None\n <mask token>\n <mask token>\n\n\nclass BrandReg(BrandRegBasic):\n\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + '/dp_brands_result.txt'\n if not os.path.exists(input_file):\n raise Exception('%s does not exist!' % input_file)\n output_file = base_folder + '/dp_brands_result.txt.brandreg'\n self._input_p = input_file\n self._input_lst = input_lst\n self._output_p = output_file\n\n def _brand_exchange(self, ori_brand):\n if ori_brand in self.exchange_brand_pair:\n return self.exchange_brand_pair[ori_brand]\n else:\n return ori_brand\n\n def brand_reg(self):\n stp1_lst = []\n idx = 0\n if self._input_lst != None and len(self._input_lst) > 0:\n self.logger.info('增量数据处理')\n for line in self._input_lst:\n idx += 1\n if idx % 10000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n elif os.path.exists(self._input_p):\n f_input = open(self._input_p)\n for line in f_input:\n idx += 1\n if idx % 100000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n f_input.close()\n else:\n raise Exception('输入增量数据为空!!!')\n if len(stp1_lst) < 1:\n raise Exception('增量数据处理后数据为空!!!')\n with open(self._output_p, 'w') as f3:\n f3.write('\\n'.join(stp1_lst))\n f3.flush()\n\n def _real_brand_reg(self, s_name):\n tmp_brand = None\n \"\"\"\n attention: 这一步可能出现问题, \n 比如:东方骆驼,骆驼, \n 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面,\n 那么将导致【东方骆驼】变为【骆驼】\n \"\"\"\n for r_b in self.real_brand_set:\n lst5 = s_name.split(r_b)\n if len(lst5) > 1:\n tmp_brand = r_b\n break\n return tmp_brand\n\n def brand_rewrite(self, line):\n line = line.strip()\n if line == '':\n self.logger.info('empty string!!')\n return None\n lst1 = line.split('\\x01')\n if len(lst1) == 3:\n s_id, ori_name, s_brand = lst1\n s_brand = s_brand.strip()\n else:\n self.logger.info('brand_rewrite error data: %s' % line)\n return None\n s_name = tool.s_name_dealing(ori_name)\n if len(self.real_brand_set) > 0:\n if s_brand not in self.real_brand_set:\n ex_brand = self._real_brand_reg(s_name)\n tmp_brand = ex_brand if ex_brand != None else s_brand\n else:\n tmp_brand = s_brand\n else:\n tmp_brand = s_brand\n r_brand = self._brand_exchange(tmp_brand)\n if r_brand in self.del_brand_dict:\n r_brand = s_name\n return '\\x01'.join([s_id, ori_name, r_brand])\n", "step-3": "<mask token>\n\n\nclass BrandRegBasic(object):\n\n def __init__(self, base_folder, log_instance):\n if not os.path.exists(base_folder):\n raise Exception('%s does not exists!' % base_folder)\n self._real_brand_p = base_folder + '/real_brand.txt'\n if not os.path.exists(self._real_brand_p):\n raise Exception('%s does not exists!' % self._real_brand_p)\n self._error_p = base_folder + '/error.txt'\n if not os.path.exists(self._error_p):\n raise Exception('%s does not exists!' % self._error_p)\n self._word_dict_p = base_folder + '/word_dict.txt'\n if not os.path.exists(self._word_dict_p):\n raise Exception('%s does not exists!' % self._word_dict_p)\n self._del_brand_p = base_folder + '/del_brand.txt'\n if not os.path.exists(self._del_brand_p):\n raise Exception('%s does not exists!' % self._del_brand_p)\n self.logger = log_instance\n self.logger.info('get_real_brand')\n self.real_brand_set = self._get_real_brand()\n self.logger.info('get_exchange_brand_pair')\n self.exchange_brand_pair = self._get_exchange_brand_pair()\n self.logger.info('get_del_brand')\n self.del_brand_dict = self._get_del_brand()\n <mask token>\n\n def _brand_pair_correction(self, exchange_dict, conflict_brand_set):\n tmp_dict = {}\n for k, v in exchange_dict.items():\n if k in conflict_brand_set:\n right_brand = exchange_dict[k]\n for k1, v1 in exchange_dict.items():\n if v1 == k:\n tmp_dict[k1] = right_brand\n exchange_dict_ext = {}\n for k2, v2 in exchange_dict.items():\n if k2 == v2:\n continue\n if k2 in conflict_brand_set:\n continue\n if k2 in tmp_dict:\n exchange_dict_ext[k2] = tmp_dict[k2]\n else:\n exchange_dict_ext[k2] = v2\n return exchange_dict_ext\n\n def _brand_pair_checking(self, exchange_dict):\n s1 = set(list(exchange_dict.keys()))\n s2 = set(list(exchange_dict.values()))\n s3 = s1 & s2\n if len(s3) > 0:\n self.logger.error(\n 'exchang-brand-pair has error, error brands is: %s' % '\\t'.\n join(list(s3)))\n return False, s3\n else:\n return True, None\n\n def _get_exchange_brand_pair(self):\n exchange_dict = {}\n\n def _line_deal(line):\n line = line.strip()\n if line == '':\n return\n lst1 = line.split('|')\n if len(lst1) != 2:\n self.logger.info('wrong brand pair: %s' % line)\n return\n lst1 = [z.strip() for z in lst1]\n if lst1[0] != lst1[1]:\n exchange_dict[lst1[0]] = lst1[1]\n if not os.path.exists(self._error_p):\n self.logger.info('%s does not exist!' % self._real_brand_p)\n else:\n with open(self._error_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info('len of exchang_brand_pair: %s' % len(\n exchange_dict))\n if not os.path.exists(self._word_dict_p):\n self.logger.info('%s does not exist!' % self._real_brand_p)\n else:\n with open(self._word_dict_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info('len of exchang_brand_pair: %s' % len(\n exchange_dict))\n chk_flag, conflict_brand_set = self._brand_pair_checking(exchange_dict)\n if not chk_flag:\n err_s = 'exchang-brand-pair error: %s' % '\\t'.join(list(\n conflict_brand_set))\n self.logger.error(err_s)\n raise Exception(err_s)\n return exchange_dict\n\n def _get_del_brand(self):\n if not os.path.exists(self._del_brand_p):\n raise Exception('%s does not exist!' % self._real_brand_p)\n del_dict = {}\n with open(self._del_brand_p) as f1:\n for line in f1:\n line = line.strip()\n if line == '':\n continue\n del_dict[line] = 0\n self.logger.info('len of del_brand: %s' % len(del_dict))\n return del_dict\n\n\nclass BrandReg(BrandRegBasic):\n\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + '/dp_brands_result.txt'\n if not os.path.exists(input_file):\n raise Exception('%s does not exist!' % input_file)\n output_file = base_folder + '/dp_brands_result.txt.brandreg'\n self._input_p = input_file\n self._input_lst = input_lst\n self._output_p = output_file\n\n def _brand_exchange(self, ori_brand):\n if ori_brand in self.exchange_brand_pair:\n return self.exchange_brand_pair[ori_brand]\n else:\n return ori_brand\n\n def brand_reg(self):\n stp1_lst = []\n idx = 0\n if self._input_lst != None and len(self._input_lst) > 0:\n self.logger.info('增量数据处理')\n for line in self._input_lst:\n idx += 1\n if idx % 10000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n elif os.path.exists(self._input_p):\n f_input = open(self._input_p)\n for line in f_input:\n idx += 1\n if idx % 100000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n f_input.close()\n else:\n raise Exception('输入增量数据为空!!!')\n if len(stp1_lst) < 1:\n raise Exception('增量数据处理后数据为空!!!')\n with open(self._output_p, 'w') as f3:\n f3.write('\\n'.join(stp1_lst))\n f3.flush()\n\n def _real_brand_reg(self, s_name):\n tmp_brand = None\n \"\"\"\n attention: 这一步可能出现问题, \n 比如:东方骆驼,骆驼, \n 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面,\n 那么将导致【东方骆驼】变为【骆驼】\n \"\"\"\n for r_b in self.real_brand_set:\n lst5 = s_name.split(r_b)\n if len(lst5) > 1:\n tmp_brand = r_b\n break\n return tmp_brand\n\n def brand_rewrite(self, line):\n line = line.strip()\n if line == '':\n self.logger.info('empty string!!')\n return None\n lst1 = line.split('\\x01')\n if len(lst1) == 3:\n s_id, ori_name, s_brand = lst1\n s_brand = s_brand.strip()\n else:\n self.logger.info('brand_rewrite error data: %s' % line)\n return None\n s_name = tool.s_name_dealing(ori_name)\n if len(self.real_brand_set) > 0:\n if s_brand not in self.real_brand_set:\n ex_brand = self._real_brand_reg(s_name)\n tmp_brand = ex_brand if ex_brand != None else s_brand\n else:\n tmp_brand = s_brand\n else:\n tmp_brand = s_brand\n r_brand = self._brand_exchange(tmp_brand)\n if r_brand in self.del_brand_dict:\n r_brand = s_name\n return '\\x01'.join([s_id, ori_name, r_brand])\n", "step-4": "<mask token>\n\n\nclass BrandRegBasic(object):\n\n def __init__(self, base_folder, log_instance):\n if not os.path.exists(base_folder):\n raise Exception('%s does not exists!' % base_folder)\n self._real_brand_p = base_folder + '/real_brand.txt'\n if not os.path.exists(self._real_brand_p):\n raise Exception('%s does not exists!' % self._real_brand_p)\n self._error_p = base_folder + '/error.txt'\n if not os.path.exists(self._error_p):\n raise Exception('%s does not exists!' % self._error_p)\n self._word_dict_p = base_folder + '/word_dict.txt'\n if not os.path.exists(self._word_dict_p):\n raise Exception('%s does not exists!' % self._word_dict_p)\n self._del_brand_p = base_folder + '/del_brand.txt'\n if not os.path.exists(self._del_brand_p):\n raise Exception('%s does not exists!' % self._del_brand_p)\n self.logger = log_instance\n self.logger.info('get_real_brand')\n self.real_brand_set = self._get_real_brand()\n self.logger.info('get_exchange_brand_pair')\n self.exchange_brand_pair = self._get_exchange_brand_pair()\n self.logger.info('get_del_brand')\n self.del_brand_dict = self._get_del_brand()\n\n def _get_real_brand(self):\n if not os.path.exists(self._real_brand_p):\n raise Exception('%s does not exist!' % self._real_brand_p)\n real_brand_set = set()\n with open(self._real_brand_p) as f1:\n for line in f1:\n line = line.strip()\n if line == '':\n continue\n real_brand_set.add(line)\n self.logger.info('len of real_brand: %s' % len(real_brand_set))\n return real_brand_set\n\n def _brand_pair_correction(self, exchange_dict, conflict_brand_set):\n tmp_dict = {}\n for k, v in exchange_dict.items():\n if k in conflict_brand_set:\n right_brand = exchange_dict[k]\n for k1, v1 in exchange_dict.items():\n if v1 == k:\n tmp_dict[k1] = right_brand\n exchange_dict_ext = {}\n for k2, v2 in exchange_dict.items():\n if k2 == v2:\n continue\n if k2 in conflict_brand_set:\n continue\n if k2 in tmp_dict:\n exchange_dict_ext[k2] = tmp_dict[k2]\n else:\n exchange_dict_ext[k2] = v2\n return exchange_dict_ext\n\n def _brand_pair_checking(self, exchange_dict):\n s1 = set(list(exchange_dict.keys()))\n s2 = set(list(exchange_dict.values()))\n s3 = s1 & s2\n if len(s3) > 0:\n self.logger.error(\n 'exchang-brand-pair has error, error brands is: %s' % '\\t'.\n join(list(s3)))\n return False, s3\n else:\n return True, None\n\n def _get_exchange_brand_pair(self):\n exchange_dict = {}\n\n def _line_deal(line):\n line = line.strip()\n if line == '':\n return\n lst1 = line.split('|')\n if len(lst1) != 2:\n self.logger.info('wrong brand pair: %s' % line)\n return\n lst1 = [z.strip() for z in lst1]\n if lst1[0] != lst1[1]:\n exchange_dict[lst1[0]] = lst1[1]\n if not os.path.exists(self._error_p):\n self.logger.info('%s does not exist!' % self._real_brand_p)\n else:\n with open(self._error_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info('len of exchang_brand_pair: %s' % len(\n exchange_dict))\n if not os.path.exists(self._word_dict_p):\n self.logger.info('%s does not exist!' % self._real_brand_p)\n else:\n with open(self._word_dict_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info('len of exchang_brand_pair: %s' % len(\n exchange_dict))\n chk_flag, conflict_brand_set = self._brand_pair_checking(exchange_dict)\n if not chk_flag:\n err_s = 'exchang-brand-pair error: %s' % '\\t'.join(list(\n conflict_brand_set))\n self.logger.error(err_s)\n raise Exception(err_s)\n return exchange_dict\n\n def _get_del_brand(self):\n if not os.path.exists(self._del_brand_p):\n raise Exception('%s does not exist!' % self._real_brand_p)\n del_dict = {}\n with open(self._del_brand_p) as f1:\n for line in f1:\n line = line.strip()\n if line == '':\n continue\n del_dict[line] = 0\n self.logger.info('len of del_brand: %s' % len(del_dict))\n return del_dict\n\n\nclass BrandReg(BrandRegBasic):\n\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + '/dp_brands_result.txt'\n if not os.path.exists(input_file):\n raise Exception('%s does not exist!' % input_file)\n output_file = base_folder + '/dp_brands_result.txt.brandreg'\n self._input_p = input_file\n self._input_lst = input_lst\n self._output_p = output_file\n\n def _brand_exchange(self, ori_brand):\n if ori_brand in self.exchange_brand_pair:\n return self.exchange_brand_pair[ori_brand]\n else:\n return ori_brand\n\n def brand_reg(self):\n stp1_lst = []\n idx = 0\n if self._input_lst != None and len(self._input_lst) > 0:\n self.logger.info('增量数据处理')\n for line in self._input_lst:\n idx += 1\n if idx % 10000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n elif os.path.exists(self._input_p):\n f_input = open(self._input_p)\n for line in f_input:\n idx += 1\n if idx % 100000 == 0:\n self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None:\n continue\n stp1_lst.append(r)\n f_input.close()\n else:\n raise Exception('输入增量数据为空!!!')\n if len(stp1_lst) < 1:\n raise Exception('增量数据处理后数据为空!!!')\n with open(self._output_p, 'w') as f3:\n f3.write('\\n'.join(stp1_lst))\n f3.flush()\n\n def _real_brand_reg(self, s_name):\n tmp_brand = None\n \"\"\"\n attention: 这一步可能出现问题, \n 比如:东方骆驼,骆驼, \n 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面,\n 那么将导致【东方骆驼】变为【骆驼】\n \"\"\"\n for r_b in self.real_brand_set:\n lst5 = s_name.split(r_b)\n if len(lst5) > 1:\n tmp_brand = r_b\n break\n return tmp_brand\n\n def brand_rewrite(self, line):\n line = line.strip()\n if line == '':\n self.logger.info('empty string!!')\n return None\n lst1 = line.split('\\x01')\n if len(lst1) == 3:\n s_id, ori_name, s_brand = lst1\n s_brand = s_brand.strip()\n else:\n self.logger.info('brand_rewrite error data: %s' % line)\n return None\n s_name = tool.s_name_dealing(ori_name)\n if len(self.real_brand_set) > 0:\n if s_brand not in self.real_brand_set:\n ex_brand = self._real_brand_reg(s_name)\n tmp_brand = ex_brand if ex_brand != None else s_brand\n else:\n tmp_brand = s_brand\n else:\n tmp_brand = s_brand\n r_brand = self._brand_exchange(tmp_brand)\n if r_brand in self.del_brand_dict:\n r_brand = s_name\n return '\\x01'.join([s_id, ori_name, r_brand])\n", "step-5": "#!/usr/bin/env python3\n#coding=utf-8\n\nimport sys\nimport os\nimport tool\n\nclass BrandRegBasic(object):\n def __init__(self, base_folder, log_instance):\n if not os.path.exists(base_folder):\n raise Exception(\"%s does not exists!\" % base_folder)\n self._real_brand_p = base_folder + \"/real_brand.txt\"\n if not os.path.exists(self._real_brand_p):\n raise Exception(\"%s does not exists!\" % self._real_brand_p)\n # 注:word_dict.txt和error.txt是一样的功能\n # 都是品牌改写,数据格式也一样\n self._error_p = base_folder + '/error.txt'\n if not os.path.exists(self._error_p):\n raise Exception(\"%s does not exists!\" % self._error_p)\n self._word_dict_p = base_folder + '/word_dict.txt'\n if not os.path.exists(self._word_dict_p):\n raise Exception(\"%s does not exists!\" % self._word_dict_p)\n self._del_brand_p = base_folder + '/del_brand.txt'\n if not os.path.exists(self._del_brand_p):\n raise Exception(\"%s does not exists!\" % self._del_brand_p)\n self.logger = log_instance\n self.logger.info(\"get_real_brand\")\n self.real_brand_set = self._get_real_brand()\n self.logger.info(\"get_exchange_brand_pair\")\n self.exchange_brand_pair = self._get_exchange_brand_pair()\n self.logger.info(\"get_del_brand\")\n self.del_brand_dict = self._get_del_brand()\n\n #通过真实品牌这个文件获取到真实品牌的元组\n def _get_real_brand(self):\n # 根据real_brand进行品牌确定\n if not os.path.exists(self._real_brand_p):\n raise Exception(\"%s does not exist!\" % self._real_brand_p)\n\n real_brand_set = set()\n with open(self._real_brand_p) as f1:\n for line in f1:\n line = line.strip()\n if line == \"\": continue\n real_brand_set.add(line)\n\n self.logger.info(\"len of real_brand: %s\" % len(real_brand_set))\n return real_brand_set\n\n # no-using\n def _brand_pair_correction(self, exchange_dict, conflict_brand_set):\n # Tips: {1:2, 2:3, 3:4}这种情况会有错误\n\n tmp_dict = {}\n for k, v in exchange_dict.items():\n if k in conflict_brand_set:\n right_brand = exchange_dict[k]\n for k1, v1 in exchange_dict.items():\n if v1 == k:\n tmp_dict[k1] = right_brand\n\n exchange_dict_ext = {}\n for k2, v2 in exchange_dict.items():\n if k2 == v2: continue\n if k2 in conflict_brand_set: continue\n if k2 in tmp_dict:\n exchange_dict_ext[k2] = tmp_dict[k2]\n else:\n exchange_dict_ext[k2] = v2\n\n return exchange_dict_ext\n\n def _brand_pair_checking(self, exchange_dict):\n s1 = set(list(exchange_dict.keys()))\n s2 = set(list(exchange_dict.values()))\n s3 = s1 & s2\n if len(s3) > 0:\n self.logger.error(\"exchang-brand-pair has error, error brands is: %s\" % \"\\t\".join(list(s3)))\n return False, s3\n else:\n return True, None\n\n def _get_exchange_brand_pair(self):\n exchange_dict = {}\n def _line_deal(line):\n line = line.strip()\n if line == \"\": return\n lst1 = line.split(\"|\")\n if len(lst1) != 2:\n self.logger.info(\"wrong brand pair: %s\" % line)\n return\n lst1 = [z.strip() for z in lst1]\n if lst1[0] != lst1[1]:\n exchange_dict[lst1[0]] = lst1[1]\n\n # 根据品牌确定的结果+error.txt获得需要修正的sname结果\n if not os.path.exists(self._error_p):\n self.logger.info(\"%s does not exist!\" % self._real_brand_p)\n else:\n with open(self._error_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info(\"len of exchang_brand_pair: %s\" % len(exchange_dict))\n\n if not os.path.exists(self._word_dict_p):\n self.logger.info(\"%s does not exist!\" % self._real_brand_p)\n else:\n with open(self._word_dict_p) as f1:\n for line in f1:\n _line_deal(line)\n self.logger.info(\"len of exchang_brand_pair: %s\" % len(exchange_dict))\n\n # 品牌对检测\n chk_flag, conflict_brand_set = self._brand_pair_checking(exchange_dict)\n if not chk_flag:\n err_s = \"exchang-brand-pair error: %s\" % \"\\t\".join(list(conflict_brand_set))\n self.logger.error(err_s)\n raise Exception(err_s)\n \n return exchange_dict\n\n def _get_del_brand(self):\n if not os.path.exists(self._del_brand_p):\n raise Exception(\"%s does not exist!\" % self._real_brand_p)\n\n del_dict = {}\n with open(self._del_brand_p) as f1:\n for line in f1:\n line = line.strip()\n if line == \"\": continue\n del_dict[line] = 0\n self.logger.info(\"len of del_brand: %s\" % len(del_dict))\n return del_dict\n\nclass BrandReg(BrandRegBasic):\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + \"/dp_brands_result.txt\"\n if not os.path.exists(input_file):\n raise Exception(\"%s does not exist!\" % input_file)\n\n output_file = base_folder + \"/dp_brands_result.txt.brandreg\"\n self._input_p = input_file\n self._input_lst = input_lst\n self._output_p = output_file\n\n def _brand_exchange(self, ori_brand):\n if ori_brand in self.exchange_brand_pair:\n return self.exchange_brand_pair[ori_brand]\n else:\n return ori_brand\n\n def brand_reg(self):\n stp1_lst = []\n idx = 0\n if self._input_lst != None and len(self._input_lst) > 0:\n self.logger.info(\"增量数据处理\")\n for line in self._input_lst:\n idx += 1\n if idx % 10000 == 0: self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None: continue\n stp1_lst.append(r)\n elif os.path.exists(self._input_p):\n f_input = open(self._input_p)\n for line in f_input:\n idx += 1\n if idx % 100000 == 0: self.logger.info(idx)\n line = line.strip()\n r = self.brand_rewrite(line)\n if r is None: continue\n stp1_lst.append(r)\n\n f_input.close()\n else:\n raise Exception(\"输入增量数据为空!!!\")\n\n if len(stp1_lst) < 1:\n raise Exception(\"增量数据处理后数据为空!!!\")\n\n with open(self._output_p, 'w') as f3:\n f3.write(\"\\n\".join(stp1_lst))\n f3.flush()\n\n def _real_brand_reg(self, s_name):\n tmp_brand = None\n \"\"\"\n attention: 这一步可能出现问题, \n 比如:东方骆驼,骆驼, \n 在real_brand.txt文件中,如果【骆驼】出现在【东方骆驼】前面,\n 那么将导致【东方骆驼】变为【骆驼】\n \"\"\"\n for r_b in self.real_brand_set:\n lst5 = s_name.split(r_b)\n if len(lst5) > 1:\n tmp_brand = r_b\n break\n\n return tmp_brand\n\n def brand_rewrite(self, line):\n line = line.strip()\n if line == \"\":\n self.logger.info(\"empty string!!\")\n return None\n lst1 = line.split(\"\\x01\")\n if len(lst1) == 3:\n s_id, ori_name, s_brand = lst1 #取到相关的数据\n s_brand = s_brand.strip()\n else:\n self.logger.info(\"brand_rewrite error data: %s\" % line)\n return None\n\n s_name = tool.s_name_dealing(ori_name)\n if len(self.real_brand_set) > 0:\n if s_brand not in self.real_brand_set:\n ex_brand = self._real_brand_reg(s_name) #匹配过程。如果取到的数据当中没有在数据集中找到相同的品牌,则对这种数据处理一下,在一个数据集中去匹配,进行品牌的归并\n tmp_brand = ex_brand if ex_brand != None else s_brand #如果对处理过的品牌就赋值给tmp_brand,否则直接赋值\n else:\n tmp_brand = s_brand #如果在数据集中找到了直接赋值\n else:\n tmp_brand = s_brand #如果没有数据集就直接赋值\n # brand 修正\n r_brand = self._brand_exchange(tmp_brand)\n # 错误品牌检测\n if r_brand in self.del_brand_dict:\n r_brand = s_name\n\n return \"\\x01\".join([s_id, ori_name, r_brand]) #拼接后返回结果\n\n\n\n\n\n\n", "step-ids": [ 6, 9, 12, 13, 15 ] }
[ 6, 9, 12, 13, 15 ]
def somaSerie(valor): soma = 0 for i in range(valor): soma += ((i**2)+1)/(i+3) return soma a = int(input("Digite o 1º Numero :-> ")) result = somaSerie(a) print(result)
normal
{ "blob_id": "8114d8162bab625854804d1df2b4a9c11818d35e", "index": 3747, "step-1": "<mask token>\n", "step-2": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\n<mask token>\n", "step-3": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\n<mask token>\nprint(result)\n", "step-4": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\na = int(input('Digite o 1º Numero :-> '))\nresult = somaSerie(a)\nprint(result)\n", "step-5": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += ((i**2)+1)/(i+3)\n return soma\n\na = int(input(\"Digite o 1º Numero :-> \"))\nresult = somaSerie(a)\nprint(result)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import re def detectPeriod(data): numWord = "[0-9,一二三四五六七八九十兩半]" hourWord = "小時鐘頭" minWord = "分鐘" secWord = "秒鐘" timePat = "["+numWord+"]+點?\.?["+numWord+"]*個?半?["+hourWord+"]*半?又?["+numWord+"]*["+minWord+"]*又?["+numWord+"]*["+secWord+"]*" def main(): detectPeriod("我要去游泳一個小時") if __name__ == "__main__": main()
normal
{ "blob_id": "397686964acbf640a5463a3a7095d85832545d9e", "index": 6462, "step-1": "<mask token>\n\n\ndef main():\n detectPeriod('我要去游泳一個小時')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef detectPeriod(data):\n numWord = '[0-9,一二三四五六七八九十兩半]'\n hourWord = '小時鐘頭'\n minWord = '分鐘'\n secWord = '秒鐘'\n timePat = ('[' + numWord + ']+點?\\\\.?[' + numWord + ']*個?半?[' + hourWord +\n ']*半?又?[' + numWord + ']*[' + minWord + ']*又?[' + numWord + ']*[' +\n secWord + ']*')\n\n\ndef main():\n detectPeriod('我要去游泳一個小時')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef detectPeriod(data):\n numWord = '[0-9,一二三四五六七八九十兩半]'\n hourWord = '小時鐘頭'\n minWord = '分鐘'\n secWord = '秒鐘'\n timePat = ('[' + numWord + ']+點?\\\\.?[' + numWord + ']*個?半?[' + hourWord +\n ']*半?又?[' + numWord + ']*[' + minWord + ']*又?[' + numWord + ']*[' +\n secWord + ']*')\n\n\ndef main():\n detectPeriod('我要去游泳一個小時')\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import re\n\n\ndef detectPeriod(data):\n numWord = '[0-9,一二三四五六七八九十兩半]'\n hourWord = '小時鐘頭'\n minWord = '分鐘'\n secWord = '秒鐘'\n timePat = ('[' + numWord + ']+點?\\\\.?[' + numWord + ']*個?半?[' + hourWord +\n ']*半?又?[' + numWord + ']*[' + minWord + ']*又?[' + numWord + ']*[' +\n secWord + ']*')\n\n\ndef main():\n detectPeriod('我要去游泳一個小時')\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import re\n\n\ndef detectPeriod(data):\n \n numWord = \"[0-9,一二三四五六七八九十兩半]\"\n hourWord = \"小時鐘頭\"\n minWord = \"分鐘\"\n secWord = \"秒鐘\"\n\n\n timePat = \"[\"+numWord+\"]+點?\\.?[\"+numWord+\"]*個?半?[\"+hourWord+\"]*半?又?[\"+numWord+\"]*[\"+minWord+\"]*又?[\"+numWord+\"]*[\"+secWord+\"]*\"\n\n\n\n\ndef main():\n detectPeriod(\"我要去游泳一個小時\")\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
""" # listbinmin.py # Sam Connolly 04/03/2013 #=============================================================================== # bin data according a given column in an ascii file of column data, such that # each bin has a minimum number of points, giving the bin of each data point as # a LIST. UNEVEN BINS. #=============================================================================== """ # Import packages import numpy as np #================ PARAMETERS =================================================== # read variables header = 0 # number of header lines to ignore outdata = [1, 3] # column numbers to output bincolumn = 3 # column to bin along errorcolumn = 4 binmin = 18 # File routes route = "/disks/raid/raid1/xray/raid/sdc1g08/NetData/ngc1365/"\ + "lightcurve/refinedCounts/" # file name infilename = "NGC1365_lcurve_4_0.5-10keV.qdp" # Save output? # histogram of binning? hist = True # Save output? save = True savefile = "binsout.dat" outroute = "/disks/raid/raid1/xray/raid/sdc1g08/NetData/ngc1365/"\ #+ "spectra/" # Highlighted lightcurve? lc = True timecolumn = 2 labels = False #==================== Load data ================================================ # create file routes location = route+infilename savelocation = outroute+savefile # read data intoarray start = 0 infile= open(location, 'r') for line in infile: linedata = line.split() if start == header: columns = len(linedata) data = [[] for x in range(columns)] if start >= header: for column in range(columns): if len(linedata) == columns: data[column].append(float(linedata[column])) start += 1 infile.close() outdata = np.array(outdata) outdata -= 1 bincolumn -= 1 errorcolumn -= 1 #========================= Sort ================================================ start = True for index in range(len(data[0])): if start == True: sortindex = [index] start = False else: i = 0 if data[bincolumn][index] < data[bincolumn][sortindex[-1]]: while data[bincolumn][index] > data[bincolumn][sortindex[i]]: i += 1 sortindex.insert(i,index) else: sortindex.append(index) #======================== Bin ================================================== bins = [] for index in np.arange(0,int(len(sortindex)),binmin): this = [[],0,0,0,0,0] err = [] total = 0 for i in range(binmin): if index+i <= len(sortindex) - 1: this[0].append(sortindex[index+i]) err.append(data[errorcolumn][sortindex[index+i]]) total += data[countscolumn][sortindex[index+i] this[1] = data[bincolumn][sortindex[index]] # bin min if index+binmin-1 <= len(sortindex) - 1: # bin max this[2] = data[bincolumn][sortindex[index+binmin-1]] else: this[2] = max(data[bincolumn]) this[3] = (this[2]+this[1])/2.0 err = np.array(err) this[4] = sum(err**2) this[5] = total bins.append(this) print bins #======================== print output ========================================= if save == True: out = open(savelocation,'w') for b in range(len(bins)): low = bins[b][1] high = bins[b][2] mid = bins[b][3] errs = bins[b][4] print low, " >= x > ", high, " ==> ",mid, ' +/- ', errs , " :\n" if save == True: out.write(str(low) + " >=x> " + str(high) + " :\n") output = '' for index in bins[b][0]: for dat in outdata: if dat != bincolumn: output = output + str(data[dat][index]) + '\t' print output, "\n" if save == True: out.write(output+"\n") print "number of bins: ", len(bins) if save == True: out.write("number of bins: " + str(len(bins))) out.close() # plots nplots = 0 if hist: nplots += 1 if lc: nplots += 1 if nplots == 1: fig = plt.figure() ax = fig.add_subplot(1,1,1) if nplots == 2: fig = plt.figure() # histogram if hist: if nplots == 2: ax = fig.add_subplot(1,2,1) edges = [] counts = [] widths = [] for b in range(len(bins)): edges.append(bins[b][1]) counts.append(bins[b][2]) try: widths.append(data[bincolumn][bins[b+1][0][0]]-\ data[bincolumn][bins[b][0][0]]) except IndexError: widths.append(data[bincolumn][bins[b][0][-1]]-\ data[bincolumn][bins[b][0][0]]) plt.bar(edges,counts,widths) # highlighted lightcurve if lc: if nplots == 2: ax = fig.add_subplot(1,2,2) plt.scatter(data[timecolumn],data[bincolumn]) for b in range(len(bins)): try: plt.axhspan(data[bincolumn][bins[b][0][0]], \ data[bincolumn][bins[b+1][0][0]],alpha = 0.3) except IndexError: plt.axhspan(data[bincolumn][bins[b][0][0]], \ data[bincolumn][bins[b][0][-1]],alpha = 0.3) if labels: for index in range(len(data[0])): plt.annotate(data[-1][index], xy = (data[timecolumn][index],data[bincolumn][index]), xytext = (-20,20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'blue', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) if nplots > 0: plt.show()
normal
{ "blob_id": "496c58e68d3ac78a3eb1272d61ca3603c5d843b6", "index": 4787, "step-1": "\"\"\"\n# listbinmin.py\n# Sam Connolly 04/03/2013\n\n#===============================================================================\n# bin data according a given column in an ascii file of column data, such that\n# each bin has a minimum number of points, giving the bin of each data point as \n# a LIST. UNEVEN BINS.\n#===============================================================================\n\"\"\"\n\n# Import packages\n\nimport numpy as np\n\n#================ PARAMETERS ===================================================\n\n# read variables\nheader = 0 # number of header lines to ignore\n\noutdata = [1, 3] # column numbers to output\n\nbincolumn = 3 # column to bin along\nerrorcolumn = 4\nbinmin = 18\n\n# File routes\nroute = \"/disks/raid/raid1/xray/raid/sdc1g08/NetData/ngc1365/\"\\\n\t\t\t\t\t\t+ \"lightcurve/refinedCounts/\"\n\n# file name\ninfilename \t= \"NGC1365_lcurve_4_0.5-10keV.qdp\"\n\n\n# Save output?\n\n# histogram of binning?\n\nhist = True\n\n# Save output?\n\nsave = True\nsavefile = \"binsout.dat\"\n\noutroute = \"/disks/raid/raid1/xray/raid/sdc1g08/NetData/ngc1365/\"\\\n\t\t\t\t\t\t#+ \"spectra/\"\n\n# Highlighted lightcurve?\n\nlc = True\ntimecolumn = 2\nlabels = False\n\n#==================== Load data ================================================\n\n# create file routes\nlocation = route+infilename\nsavelocation = outroute+savefile\n\n# read data intoarray\n\nstart = 0\n\ninfile= open(location, 'r')\n\nfor line in infile:\n\t\n\tlinedata = line.split()\n\n\tif start == header:\n\t\tcolumns = len(linedata)\n\t\tdata = [[] for x in range(columns)]\n\n\tif start >= header:\n\t\tfor column in range(columns):\n\t\t\tif len(linedata) == columns:\n\t\t\t\tdata[column].append(float(linedata[column]))\n\t\t\n\tstart += 1\n\ninfile.close()\n\noutdata = np.array(outdata)\t\noutdata -= 1 \nbincolumn -= 1\nerrorcolumn -= 1\n\n#========================= Sort ================================================\n\nstart = True\n\nfor index in range(len(data[0])):\n\n\tif start == True:\n\n\t\tsortindex = [index]\n\n\t\tstart = False\n\t\n\telse:\n\n\t\ti = 0\n\n\t\tif data[bincolumn][index] < data[bincolumn][sortindex[-1]]:\n\t\t\twhile data[bincolumn][index] > data[bincolumn][sortindex[i]]:\n\n\t\t\t\ti += 1\n\n\t\t\tsortindex.insert(i,index)\n\n\t\telse:\n\t\t\t\n\t\t\tsortindex.append(index)\n\n#======================== Bin ==================================================\n\nbins = []\n\nfor index in np.arange(0,int(len(sortindex)),binmin):\n\n\tthis = [[],0,0,0,0,0]\n\terr = []\n\ttotal = 0\n\n\tfor i in range(binmin):\n\n\t\tif index+i <= len(sortindex) - 1:\n\t\t\tthis[0].append(sortindex[index+i]) \n\t\t\terr.append(data[errorcolumn][sortindex[index+i]])\n\n\t\t\ttotal += data[countscolumn][sortindex[index+i]\n\n\tthis[1] = data[bincolumn][sortindex[index]] # bin min\n\n\tif index+binmin-1 <= len(sortindex) - 1:\t# bin max\n\n\t\tthis[2] = data[bincolumn][sortindex[index+binmin-1]]\n\t\t\n\telse:\n\t\tthis[2] = max(data[bincolumn])\n\n\tthis[3] = (this[2]+this[1])/2.0\n\n\terr = np.array(err)\n\n\tthis[4] = sum(err**2)\n\n\tthis[5] = total\n\n\tbins.append(this)\n\nprint bins\n\n#======================== print output =========================================\nif save == True:\n\n\tout = open(savelocation,'w')\n\nfor b in range(len(bins)):\n\n\tlow = bins[b][1]\n\thigh = bins[b][2]\n\tmid\t = bins[b][3]\n\terrs = bins[b][4]\n\n\tprint low, \" >= x > \", high, \" ==> \",mid, ' +/- ', errs , \" :\\n\"\n\n\tif save == True:\n\n\t\tout.write(str(low) + \" >=x> \" + str(high) + \" :\\n\")\n\n\toutput = ''\n\n\tfor index in bins[b][0]:\n\t\tfor dat in outdata:\n\t\t\tif dat != bincolumn:\n\n\t\t\t\toutput = output + str(data[dat][index]) + '\\t'\n\n\tprint output, \"\\n\"\n\n\tif save == True:\n\n\t\tout.write(output+\"\\n\")\n\n\nprint \"number of bins: \", len(bins)\n\nif save == True:\n\n\tout.write(\"number of bins: \" + str(len(bins)))\n\n\tout.close()\n\n# plots\n\nnplots = 0\n\nif hist:\n\n\tnplots += 1\n\nif lc:\n\n\tnplots += 1\n\nif nplots == 1:\n\n\tfig = plt.figure()\n\tax = fig.add_subplot(1,1,1)\n\nif nplots == 2:\n\n\tfig = plt.figure()\n\n# histogram\n\nif hist:\n\n\tif nplots == 2:\n\t\tax = fig.add_subplot(1,2,1)\n\n\tedges = []\n\tcounts = []\n\twidths = []\n\n\tfor b in range(len(bins)):\n\n\t\tedges.append(bins[b][1])\n\t\tcounts.append(bins[b][2])\n\t\ttry:\n\t\t\twidths.append(data[bincolumn][bins[b+1][0][0]]-\\\n\t\t\t\tdata[bincolumn][bins[b][0][0]])\n\t\texcept IndexError:\n\t\t\twidths.append(data[bincolumn][bins[b][0][-1]]-\\\n\t\t\t\tdata[bincolumn][bins[b][0][0]])\n\n\tplt.bar(edges,counts,widths)\n\n\n\n\n# highlighted lightcurve\n\nif lc:\n\n\tif nplots == 2:\n\t\tax = fig.add_subplot(1,2,2)\n\n\tplt.scatter(data[timecolumn],data[bincolumn])\n\n\tfor b in range(len(bins)):\n\n\t\ttry:\n\t\t\tplt.axhspan(data[bincolumn][bins[b][0][0]], \\\n\t\t\t\t\t\t\tdata[bincolumn][bins[b+1][0][0]],alpha = 0.3)\n\t\texcept IndexError:\n\t\t\tplt.axhspan(data[bincolumn][bins[b][0][0]], \\\n\t\t\t\t\t\t\tdata[bincolumn][bins[b][0][-1]],alpha = 0.3)\n\n\tif labels:\n\t\tfor index in range(len(data[0])):\n\t\t\tplt.annotate(data[-1][index], \n\t\t\t\t\txy = (data[timecolumn][index],data[bincolumn][index]), \n\t\t\t\t\txytext = (-20,20),\n\t\t\t\t\ttextcoords = 'offset points', ha = 'right', va = 'bottom',\n\t\t\t\t\tbbox = dict(boxstyle = 'round,pad=0.5', fc = 'blue', \n\t\t\t\t\talpha = 0.5), arrowprops = dict(arrowstyle = '->', \n\t\t\t\t\tconnectionstyle = 'arc3,rad=0'))\t\n\n\nif nplots > 0:\n\n\tplt.show()\n\n\n\n\n\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# Interprets the AST class Program: def __init__(self, code): self.code = code def eval(self, binding): return self.code.eval(binding) class Code: def __init__(self, statements): self.statements = statements def eval(self, binding): val = 0 for statement in self.statements: val = statement.eval(binding) return val class Statement: def __init__(self, statement): self.statement = statement def eval(self, binding): return self.statement.eval(binding) class Expr: def __init__(self, expression): self.expression = expression def eval(self, binding): return self.expression.eval(binding) class Integer: def __init__(self, value): self.value = value def eval(self, binding): return int(self.value) class BinaryOp: def __init__(self, left, right): self.left = left self.right = right class Sum(BinaryOp): def eval(self, binding): return self.left.eval(binding) + self.right.eval(binding) class Sub(BinaryOp): def eval(self, binding): return self.left.eval(binding) - self.right.eval(binding) class Mult(BinaryOp): def eval(self, binding): return self.left.eval(binding) * self.right.eval(binding) class Div(BinaryOp): def eval(self, binding): return int(self.left.eval(binding) / self.right.eval(binding)) class BuiltInFunction: # built-in functions are print, and () def __init__(self, func_name, call_args): self.func_name = func_name self.call_args = call_args def eval(self, binding): args = self.call_args.eval(binding) if self.func_name == "print": if type(args) == int: print(args) else: print("Print: ") count = 0 for arg in args: out = str(arg) if count != len(args) - 1: print(out, end="|") else: print(out) count += 1 return else: return args[0] # binding class used to store variables and functions class Binding: def __init__(self, parent, binding): self.parent = parent self.binding = binding def get(self, name): if name in self.binding: return self.binding[name] return self.parent.get(name) def add(self, var_name, value): self.binding[var_name] = value def contains(self, name): for i in self.binding: if i == name: return True if self.parent: return self.parent.contains(name) return False class FunctionCall: def __init__(self, func_name, call_args): self.func_name = func_name self.call_args = call_args def eval(self, binding): # if function has no parameters if type(self.call_args) == VarReference: args = self.call_args.eval(binding) return args[1].eval(binding) # else # creates a new function binding that is a child of the binding when the function was created func_binding = Binding(binding.get(self.func_name.value)[2], {}) # sets parameters and arguments and adds them to the function binding parameters = self.call_args[0].eval(func_binding)[0] # checks to see if the arg values for param_list are in the function binding. This is for recursion. if func_binding.contains(parameters[0]): args = self.call_args[1].eval(func_binding) # if not, checks if the arg values are in the global binding else: args = self.call_args[1].eval(binding) # assigns the arg values to the parameters and adds it to the function binding for i in range(len(parameters)): func_binding.add(parameters[i], args[i]) # returns the evaluated code using the function binding code = func_binding.get(self.func_name.value)[1] return code.eval(func_binding) class FunctionDefinition: def __init__(self, param_list, code_block): self.param_list = param_list self.code_block = code_block def eval(self, binding): # creates a new binding func_binding = Binding(binding, {}) # used to store a function's parameters, code, and function binding in global binding return self.param_list, self.code_block, func_binding class CallArguments: def __init__(self, arguments): self.arguments = arguments def eval(self, binding): arg_list = [] for arg in self.arguments: arg_list.append(arg.eval(binding)) return arg_list class VariableDecl: def __init__(self, declarations): self.declarations = declarations def eval(self, binding): for decl in self.declarations: temp = decl.eval(binding) return temp class Decl: def __init__(self, var_name, val): self.var_name = var_name self.val = val def eval(self, binding): var_val = self.val.eval(binding) binding.add(self.var_name, var_val) return var_val class Assignment: def __init__(self, var_name, val): self.var_name = var_name self.val = val def eval(self, binding): var_val = self.val.eval(binding) binding.add(self.var_name, var_val) return var_val class VarReference: def __init__(self, var_name): self.var_name = var_name def eval(self, binding): return binding.get(self.var_name) class EqualTo(BinaryOp): def eval(self, binding): if self.left.eval(binding) == self.right.eval(binding): return 1 else: return 0 class NotEqualTo(BinaryOp): def eval(self, binding): if self.left.eval(binding) != self.right.eval(binding): return 1 else: return 0 class LessThan(BinaryOp): def eval(self, binding): if self.left.eval(binding) < self.right.eval(binding): return 1 else: return 0 class LessThanOrEqualTo(BinaryOp): def eval(self, binding): if self.left.eval(binding) <= self.right.eval(binding): return 1 else: return 0 class GreaterThan(BinaryOp): def eval(self, binding): if self.left.eval(binding) > self.right.eval(binding): return 1 else: return 0 class GreaterThanOrEqualTo(BinaryOp): def eval(self, binding): if self.left.eval(binding) >= self.right.eval(binding): return 1 else: return 0 class IfExpression: def __init__(self, bool_expr, if_block): self.bool_expr = bool_expr self.if_block = if_block def eval(self, binding): bool_result = self.bool_expr.eval(binding) if type(bool_result) is not int: bool_result = bool_result[0] if bool_result == 1: return self.if_block.eval(binding) else: return 0 class IfElseExpression: def __init__(self, bool_expr, if_block, else_block): self.bool_expr = bool_expr self.if_block = if_block self.else_block = else_block def eval(self, binding): bool_result = self.bool_expr.eval(binding) if type(bool_result) is not int: bool_result = bool_result[0] if bool_result == 1: return self.if_block.eval(binding) else: return self.else_block.eval(binding)
normal
{ "blob_id": "5fa91a5061a5e87a4a2b8fece0378299e87e5a48", "index": 6694, "step-1": "<mask token>\n\n\nclass Binding:\n\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n <mask token>\n\n def add(self, var_name, value):\n self.binding[var_name] = value\n <mask token>\n\n\nclass FunctionCall:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n if type(self.call_args) == VarReference:\n args = self.call_args.eval(binding)\n return args[1].eval(binding)\n func_binding = Binding(binding.get(self.func_name.value)[2], {})\n parameters = self.call_args[0].eval(func_binding)[0]\n if func_binding.contains(parameters[0]):\n args = self.call_args[1].eval(func_binding)\n else:\n args = self.call_args[1].eval(binding)\n for i in range(len(parameters)):\n func_binding.add(parameters[i], args[i])\n code = func_binding.get(self.func_name.value)[1]\n return code.eval(func_binding)\n\n\nclass FunctionDefinition:\n\n def __init__(self, param_list, code_block):\n self.param_list = param_list\n self.code_block = code_block\n\n def eval(self, binding):\n func_binding = Binding(binding, {})\n return self.param_list, self.code_block, func_binding\n\n\nclass CallArguments:\n\n def __init__(self, arguments):\n self.arguments = arguments\n\n def eval(self, binding):\n arg_list = []\n for arg in self.arguments:\n arg_list.append(arg.eval(binding))\n return arg_list\n\n\nclass VariableDecl:\n\n def __init__(self, declarations):\n self.declarations = declarations\n\n def eval(self, binding):\n for decl in self.declarations:\n temp = decl.eval(binding)\n return temp\n\n\nclass Decl:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass Assignment:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass VarReference:\n\n def __init__(self, var_name):\n self.var_name = var_name\n\n def eval(self, binding):\n return binding.get(self.var_name)\n\n\nclass EqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) == self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass NotEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) != self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) < self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) <= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) > self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) >= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass IfExpression:\n\n def __init__(self, bool_expr, if_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return 0\n\n\nclass IfElseExpression:\n\n def __init__(self, bool_expr, if_block, else_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n self.else_block = else_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return self.else_block.eval(binding)\n", "step-2": "<mask token>\n\n\nclass Mult(BinaryOp):\n <mask token>\n\n\nclass Div(BinaryOp):\n\n def eval(self, binding):\n return int(self.left.eval(binding) / self.right.eval(binding))\n\n\nclass BuiltInFunction:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n args = self.call_args.eval(binding)\n if self.func_name == 'print':\n if type(args) == int:\n print(args)\n else:\n print('Print: ')\n count = 0\n for arg in args:\n out = str(arg)\n if count != len(args) - 1:\n print(out, end='|')\n else:\n print(out)\n count += 1\n return\n else:\n return args[0]\n\n\nclass Binding:\n\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n\n def get(self, name):\n if name in self.binding:\n return self.binding[name]\n return self.parent.get(name)\n\n def add(self, var_name, value):\n self.binding[var_name] = value\n\n def contains(self, name):\n for i in self.binding:\n if i == name:\n return True\n if self.parent:\n return self.parent.contains(name)\n return False\n\n\nclass FunctionCall:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n if type(self.call_args) == VarReference:\n args = self.call_args.eval(binding)\n return args[1].eval(binding)\n func_binding = Binding(binding.get(self.func_name.value)[2], {})\n parameters = self.call_args[0].eval(func_binding)[0]\n if func_binding.contains(parameters[0]):\n args = self.call_args[1].eval(func_binding)\n else:\n args = self.call_args[1].eval(binding)\n for i in range(len(parameters)):\n func_binding.add(parameters[i], args[i])\n code = func_binding.get(self.func_name.value)[1]\n return code.eval(func_binding)\n\n\nclass FunctionDefinition:\n\n def __init__(self, param_list, code_block):\n self.param_list = param_list\n self.code_block = code_block\n\n def eval(self, binding):\n func_binding = Binding(binding, {})\n return self.param_list, self.code_block, func_binding\n\n\nclass CallArguments:\n\n def __init__(self, arguments):\n self.arguments = arguments\n\n def eval(self, binding):\n arg_list = []\n for arg in self.arguments:\n arg_list.append(arg.eval(binding))\n return arg_list\n\n\nclass VariableDecl:\n\n def __init__(self, declarations):\n self.declarations = declarations\n\n def eval(self, binding):\n for decl in self.declarations:\n temp = decl.eval(binding)\n return temp\n\n\nclass Decl:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass Assignment:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass VarReference:\n\n def __init__(self, var_name):\n self.var_name = var_name\n\n def eval(self, binding):\n return binding.get(self.var_name)\n\n\nclass EqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) == self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass NotEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) != self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) < self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) <= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) > self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) >= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass IfExpression:\n\n def __init__(self, bool_expr, if_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return 0\n\n\nclass IfElseExpression:\n\n def __init__(self, bool_expr, if_block, else_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n self.else_block = else_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return self.else_block.eval(binding)\n", "step-3": "<mask token>\n\n\nclass BinaryOp:\n <mask token>\n\n\nclass Sum(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) + self.right.eval(binding)\n\n\nclass Sub(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) - self.right.eval(binding)\n\n\nclass Mult(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) * self.right.eval(binding)\n\n\nclass Div(BinaryOp):\n\n def eval(self, binding):\n return int(self.left.eval(binding) / self.right.eval(binding))\n\n\nclass BuiltInFunction:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n args = self.call_args.eval(binding)\n if self.func_name == 'print':\n if type(args) == int:\n print(args)\n else:\n print('Print: ')\n count = 0\n for arg in args:\n out = str(arg)\n if count != len(args) - 1:\n print(out, end='|')\n else:\n print(out)\n count += 1\n return\n else:\n return args[0]\n\n\nclass Binding:\n\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n\n def get(self, name):\n if name in self.binding:\n return self.binding[name]\n return self.parent.get(name)\n\n def add(self, var_name, value):\n self.binding[var_name] = value\n\n def contains(self, name):\n for i in self.binding:\n if i == name:\n return True\n if self.parent:\n return self.parent.contains(name)\n return False\n\n\nclass FunctionCall:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n if type(self.call_args) == VarReference:\n args = self.call_args.eval(binding)\n return args[1].eval(binding)\n func_binding = Binding(binding.get(self.func_name.value)[2], {})\n parameters = self.call_args[0].eval(func_binding)[0]\n if func_binding.contains(parameters[0]):\n args = self.call_args[1].eval(func_binding)\n else:\n args = self.call_args[1].eval(binding)\n for i in range(len(parameters)):\n func_binding.add(parameters[i], args[i])\n code = func_binding.get(self.func_name.value)[1]\n return code.eval(func_binding)\n\n\nclass FunctionDefinition:\n\n def __init__(self, param_list, code_block):\n self.param_list = param_list\n self.code_block = code_block\n\n def eval(self, binding):\n func_binding = Binding(binding, {})\n return self.param_list, self.code_block, func_binding\n\n\nclass CallArguments:\n\n def __init__(self, arguments):\n self.arguments = arguments\n\n def eval(self, binding):\n arg_list = []\n for arg in self.arguments:\n arg_list.append(arg.eval(binding))\n return arg_list\n\n\nclass VariableDecl:\n\n def __init__(self, declarations):\n self.declarations = declarations\n\n def eval(self, binding):\n for decl in self.declarations:\n temp = decl.eval(binding)\n return temp\n\n\nclass Decl:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass Assignment:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass VarReference:\n\n def __init__(self, var_name):\n self.var_name = var_name\n\n def eval(self, binding):\n return binding.get(self.var_name)\n\n\nclass EqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) == self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass NotEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) != self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) < self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) <= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) > self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) >= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass IfExpression:\n\n def __init__(self, bool_expr, if_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return 0\n\n\nclass IfElseExpression:\n\n def __init__(self, bool_expr, if_block, else_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n self.else_block = else_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return self.else_block.eval(binding)\n", "step-4": "<mask token>\n\n\nclass Code:\n\n def __init__(self, statements):\n self.statements = statements\n <mask token>\n\n\nclass Statement:\n\n def __init__(self, statement):\n self.statement = statement\n\n def eval(self, binding):\n return self.statement.eval(binding)\n\n\nclass Expr:\n\n def __init__(self, expression):\n self.expression = expression\n\n def eval(self, binding):\n return self.expression.eval(binding)\n\n\nclass Integer:\n\n def __init__(self, value):\n self.value = value\n\n def eval(self, binding):\n return int(self.value)\n\n\nclass BinaryOp:\n\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\n\nclass Sum(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) + self.right.eval(binding)\n\n\nclass Sub(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) - self.right.eval(binding)\n\n\nclass Mult(BinaryOp):\n\n def eval(self, binding):\n return self.left.eval(binding) * self.right.eval(binding)\n\n\nclass Div(BinaryOp):\n\n def eval(self, binding):\n return int(self.left.eval(binding) / self.right.eval(binding))\n\n\nclass BuiltInFunction:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n args = self.call_args.eval(binding)\n if self.func_name == 'print':\n if type(args) == int:\n print(args)\n else:\n print('Print: ')\n count = 0\n for arg in args:\n out = str(arg)\n if count != len(args) - 1:\n print(out, end='|')\n else:\n print(out)\n count += 1\n return\n else:\n return args[0]\n\n\nclass Binding:\n\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n\n def get(self, name):\n if name in self.binding:\n return self.binding[name]\n return self.parent.get(name)\n\n def add(self, var_name, value):\n self.binding[var_name] = value\n\n def contains(self, name):\n for i in self.binding:\n if i == name:\n return True\n if self.parent:\n return self.parent.contains(name)\n return False\n\n\nclass FunctionCall:\n\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n if type(self.call_args) == VarReference:\n args = self.call_args.eval(binding)\n return args[1].eval(binding)\n func_binding = Binding(binding.get(self.func_name.value)[2], {})\n parameters = self.call_args[0].eval(func_binding)[0]\n if func_binding.contains(parameters[0]):\n args = self.call_args[1].eval(func_binding)\n else:\n args = self.call_args[1].eval(binding)\n for i in range(len(parameters)):\n func_binding.add(parameters[i], args[i])\n code = func_binding.get(self.func_name.value)[1]\n return code.eval(func_binding)\n\n\nclass FunctionDefinition:\n\n def __init__(self, param_list, code_block):\n self.param_list = param_list\n self.code_block = code_block\n\n def eval(self, binding):\n func_binding = Binding(binding, {})\n return self.param_list, self.code_block, func_binding\n\n\nclass CallArguments:\n\n def __init__(self, arguments):\n self.arguments = arguments\n\n def eval(self, binding):\n arg_list = []\n for arg in self.arguments:\n arg_list.append(arg.eval(binding))\n return arg_list\n\n\nclass VariableDecl:\n\n def __init__(self, declarations):\n self.declarations = declarations\n\n def eval(self, binding):\n for decl in self.declarations:\n temp = decl.eval(binding)\n return temp\n\n\nclass Decl:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass Assignment:\n\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass VarReference:\n\n def __init__(self, var_name):\n self.var_name = var_name\n\n def eval(self, binding):\n return binding.get(self.var_name)\n\n\nclass EqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) == self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass NotEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) != self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) < self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) <= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThan(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) > self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThanOrEqualTo(BinaryOp):\n\n def eval(self, binding):\n if self.left.eval(binding) >= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass IfExpression:\n\n def __init__(self, bool_expr, if_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return 0\n\n\nclass IfElseExpression:\n\n def __init__(self, bool_expr, if_block, else_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n self.else_block = else_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return self.else_block.eval(binding)\n", "step-5": "# Interprets the AST\n\n\nclass Program:\n def __init__(self, code):\n self.code = code\n\n def eval(self, binding):\n return self.code.eval(binding)\n\n\nclass Code:\n def __init__(self, statements):\n self.statements = statements\n\n def eval(self, binding):\n val = 0\n for statement in self.statements:\n val = statement.eval(binding)\n return val\n\n\nclass Statement:\n def __init__(self, statement):\n self.statement = statement\n\n def eval(self, binding):\n return self.statement.eval(binding)\n\n\nclass Expr:\n def __init__(self, expression):\n self.expression = expression\n\n def eval(self, binding):\n return self.expression.eval(binding)\n\n\nclass Integer:\n def __init__(self, value):\n self.value = value\n\n def eval(self, binding):\n return int(self.value)\n\n\nclass BinaryOp:\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\n\nclass Sum(BinaryOp):\n def eval(self, binding):\n return self.left.eval(binding) + self.right.eval(binding)\n\n\nclass Sub(BinaryOp):\n def eval(self, binding):\n return self.left.eval(binding) - self.right.eval(binding)\n\n\nclass Mult(BinaryOp):\n def eval(self, binding):\n return self.left.eval(binding) * self.right.eval(binding)\n\n\nclass Div(BinaryOp):\n def eval(self, binding):\n return int(self.left.eval(binding) / self.right.eval(binding))\n\n\nclass BuiltInFunction:\n # built-in functions are print, and ()\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n args = self.call_args.eval(binding)\n if self.func_name == \"print\":\n if type(args) == int:\n print(args)\n else:\n print(\"Print: \")\n count = 0\n for arg in args:\n out = str(arg)\n if count != len(args) - 1:\n print(out, end=\"|\")\n else:\n print(out)\n count += 1\n return\n else:\n return args[0]\n\n\n# binding class used to store variables and functions\nclass Binding:\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n\n def get(self, name):\n if name in self.binding:\n return self.binding[name]\n return self.parent.get(name)\n\n def add(self, var_name, value):\n self.binding[var_name] = value\n\n def contains(self, name):\n for i in self.binding:\n if i == name:\n return True\n if self.parent:\n return self.parent.contains(name)\n return False\n\n\nclass FunctionCall:\n def __init__(self, func_name, call_args):\n self.func_name = func_name\n self.call_args = call_args\n\n def eval(self, binding):\n # if function has no parameters\n if type(self.call_args) == VarReference:\n args = self.call_args.eval(binding)\n return args[1].eval(binding)\n\n # else\n # creates a new function binding that is a child of the binding when the function was created\n func_binding = Binding(binding.get(self.func_name.value)[2], {})\n # sets parameters and arguments and adds them to the function binding\n parameters = self.call_args[0].eval(func_binding)[0]\n # checks to see if the arg values for param_list are in the function binding. This is for recursion.\n if func_binding.contains(parameters[0]):\n args = self.call_args[1].eval(func_binding)\n # if not, checks if the arg values are in the global binding\n else:\n args = self.call_args[1].eval(binding)\n\n # assigns the arg values to the parameters and adds it to the function binding\n for i in range(len(parameters)):\n func_binding.add(parameters[i], args[i])\n\n # returns the evaluated code using the function binding\n code = func_binding.get(self.func_name.value)[1]\n return code.eval(func_binding)\n\n\nclass FunctionDefinition:\n def __init__(self, param_list, code_block):\n self.param_list = param_list\n self.code_block = code_block\n\n def eval(self, binding):\n # creates a new binding\n func_binding = Binding(binding, {})\n # used to store a function's parameters, code, and function binding in global binding\n return self.param_list, self.code_block, func_binding\n\n\nclass CallArguments:\n def __init__(self, arguments):\n self.arguments = arguments\n\n def eval(self, binding):\n arg_list = []\n for arg in self.arguments:\n arg_list.append(arg.eval(binding))\n return arg_list\n\n\nclass VariableDecl:\n def __init__(self, declarations):\n self.declarations = declarations\n\n def eval(self, binding):\n for decl in self.declarations:\n temp = decl.eval(binding)\n return temp\n\n\nclass Decl:\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass Assignment:\n def __init__(self, var_name, val):\n self.var_name = var_name\n self.val = val\n\n def eval(self, binding):\n var_val = self.val.eval(binding)\n binding.add(self.var_name, var_val)\n return var_val\n\n\nclass VarReference:\n def __init__(self, var_name):\n self.var_name = var_name\n\n def eval(self, binding):\n return binding.get(self.var_name)\n\n\nclass EqualTo(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) == self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass NotEqualTo(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) != self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThan(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) < self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass LessThanOrEqualTo(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) <= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThan(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) > self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass GreaterThanOrEqualTo(BinaryOp):\n def eval(self, binding):\n if self.left.eval(binding) >= self.right.eval(binding):\n return 1\n else:\n return 0\n\n\nclass IfExpression:\n def __init__(self, bool_expr, if_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return 0\n\n\nclass IfElseExpression:\n def __init__(self, bool_expr, if_block, else_block):\n self.bool_expr = bool_expr\n self.if_block = if_block\n self.else_block = else_block\n\n def eval(self, binding):\n bool_result = self.bool_expr.eval(binding)\n if type(bool_result) is not int:\n bool_result = bool_result[0]\n if bool_result == 1:\n return self.if_block.eval(binding)\n else:\n return self.else_block.eval(binding)\n\n", "step-ids": [ 42, 50, 56, 68, 73 ] }
[ 42, 50, 56, 68, 73 ]
from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment from paypalcheckoutsdk.orders import OrdersCaptureRequest, OrdersCreateRequest from django.conf import settings import sys class PayPalClient: def __init__(self): self.client_id = settings.PAYPAL_CLIENT_ID self.client_secret = settings.PAYPAL_SECRET """Set up and return PayPal Python SDK environment with PayPal access credentials. This sample uses SandboxEnvironment. In production, use LiveEnvironment.""" self.environment = SandboxEnvironment(client_id=self.client_id, client_secret=self.client_secret) """ Returns PayPal HTTP client instance with environment that has access credentials context. Use this instance to invoke PayPal APIs, provided the credentials have access. """ self.client = PayPalHttpClient(self.environment) def object_to_json(self, json_data): """ Function to print all json data in an organized readable manner """ result = {} if sys.version_info[0] < 3: itr = json_data.__dict__.iteritems() else: itr = json_data.__dict__.items() for key,value in itr: # Skip internal attributes. if key.startswith("__"): continue result[key] = self.array_to_json_array(value) if isinstance(value, list) else\ self.object_to_json(value) if not self.is_primittive(value) else\ value return result; def array_to_json_array(self, json_array): result =[] if isinstance(json_array, list): for item in json_array: result.append(self.object_to_json(item) if not self.is_primittive(item) \ else self.array_to_json_array(item) if isinstance(item, list) else item) return result def is_primittive(self, data): return isinstance(data, str) or isinstance(data, int) class OrderClient(PayPalClient): #2. Set up your server to receive a call from the client """ This is the sample function to create an order. It uses the JSON body returned by buildRequestBody() to create an order.""" def create_order(self, order_body, debug=False): request = OrdersCreateRequest() request.prefer('return=representation') #3. Call PayPal to set up a transaction request.request_body(order_body) response = self.client.execute(request) if debug: print('Status Code: ', response.status_code) print( 'Status: ', response.result.status) print( 'Order ID: ', response.result.id) print( 'Intent: ', response.result.intent) print ('Links:') for link in response.result.links: print('\t{}: {}\tCall Type: {}'.format(link.rel, link.href, link.method)) print ('Total Amount: {} {}'.format(response.result.purchase_units[0].amount.currency_code, response.result.purchase_units[0].amount.value)) return response def capture_order(self, token, debug=False): request = OrdersCaptureRequest(token) try : response = self.client.execute(request) order_id = response.result.id return order_id except IOError as ioe: return 0
normal
{ "blob_id": "542bd52e3d5bc79077277034234419983005f78e", "index": 2128, "step-1": "<mask token>\n\n\nclass OrderClient(PayPalClient):\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_body, debug=False):\n request = OrdersCreateRequest()\n request.prefer('return=representation')\n request.request_body(order_body)\n response = self.client.execute(request)\n if debug:\n print('Status Code: ', response.status_code)\n print('Status: ', response.result.status)\n print('Order ID: ', response.result.id)\n print('Intent: ', response.result.intent)\n print('Links:')\n for link in response.result.links:\n print('\\t{}: {}\\tCall Type: {}'.format(link.rel, link.href,\n link.method))\n print('Total Amount: {} {}'.format(response.result.\n purchase_units[0].amount.currency_code, response.result.\n purchase_units[0].amount.value))\n return response\n\n def capture_order(self, token, debug=False):\n request = OrdersCaptureRequest(token)\n try:\n response = self.client.execute(request)\n order_id = response.result.id\n return order_id\n except IOError as ioe:\n return 0\n", "step-2": "<mask token>\n\n\nclass PayPalClient:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass OrderClient(PayPalClient):\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_body, debug=False):\n request = OrdersCreateRequest()\n request.prefer('return=representation')\n request.request_body(order_body)\n response = self.client.execute(request)\n if debug:\n print('Status Code: ', response.status_code)\n print('Status: ', response.result.status)\n print('Order ID: ', response.result.id)\n print('Intent: ', response.result.intent)\n print('Links:')\n for link in response.result.links:\n print('\\t{}: {}\\tCall Type: {}'.format(link.rel, link.href,\n link.method))\n print('Total Amount: {} {}'.format(response.result.\n purchase_units[0].amount.currency_code, response.result.\n purchase_units[0].amount.value))\n return response\n\n def capture_order(self, token, debug=False):\n request = OrdersCaptureRequest(token)\n try:\n response = self.client.execute(request)\n order_id = response.result.id\n return order_id\n except IOError as ioe:\n return 0\n", "step-3": "<mask token>\n\n\nclass PayPalClient:\n <mask token>\n <mask token>\n\n def array_to_json_array(self, json_array):\n result = []\n if isinstance(json_array, list):\n for item in json_array:\n result.append(self.object_to_json(item) if not self.\n is_primittive(item) else self.array_to_json_array(item) if\n isinstance(item, list) else item)\n return result\n <mask token>\n\n\nclass OrderClient(PayPalClient):\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_body, debug=False):\n request = OrdersCreateRequest()\n request.prefer('return=representation')\n request.request_body(order_body)\n response = self.client.execute(request)\n if debug:\n print('Status Code: ', response.status_code)\n print('Status: ', response.result.status)\n print('Order ID: ', response.result.id)\n print('Intent: ', response.result.intent)\n print('Links:')\n for link in response.result.links:\n print('\\t{}: {}\\tCall Type: {}'.format(link.rel, link.href,\n link.method))\n print('Total Amount: {} {}'.format(response.result.\n purchase_units[0].amount.currency_code, response.result.\n purchase_units[0].amount.value))\n return response\n\n def capture_order(self, token, debug=False):\n request = OrdersCaptureRequest(token)\n try:\n response = self.client.execute(request)\n order_id = response.result.id\n return order_id\n except IOError as ioe:\n return 0\n", "step-4": "<mask token>\n\n\nclass PayPalClient:\n\n def __init__(self):\n self.client_id = settings.PAYPAL_CLIENT_ID\n self.client_secret = settings.PAYPAL_SECRET\n \"\"\"Set up and return PayPal Python SDK environment with PayPal access credentials.\n This sample uses SandboxEnvironment. In production, use LiveEnvironment.\"\"\"\n self.environment = SandboxEnvironment(client_id=self.client_id,\n client_secret=self.client_secret)\n \"\"\" Returns PayPal HTTP client instance with environment that has access\n credentials context. Use this instance to invoke PayPal APIs, provided the\n credentials have access. \"\"\"\n self.client = PayPalHttpClient(self.environment)\n\n def object_to_json(self, json_data):\n \"\"\"\n Function to print all json data in an organized readable manner\n \"\"\"\n result = {}\n if sys.version_info[0] < 3:\n itr = json_data.__dict__.iteritems()\n else:\n itr = json_data.__dict__.items()\n for key, value in itr:\n if key.startswith('__'):\n continue\n result[key] = self.array_to_json_array(value) if isinstance(value,\n list) else self.object_to_json(value\n ) if not self.is_primittive(value) else value\n return result\n\n def array_to_json_array(self, json_array):\n result = []\n if isinstance(json_array, list):\n for item in json_array:\n result.append(self.object_to_json(item) if not self.\n is_primittive(item) else self.array_to_json_array(item) if\n isinstance(item, list) else item)\n return result\n <mask token>\n\n\nclass OrderClient(PayPalClient):\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_body, debug=False):\n request = OrdersCreateRequest()\n request.prefer('return=representation')\n request.request_body(order_body)\n response = self.client.execute(request)\n if debug:\n print('Status Code: ', response.status_code)\n print('Status: ', response.result.status)\n print('Order ID: ', response.result.id)\n print('Intent: ', response.result.intent)\n print('Links:')\n for link in response.result.links:\n print('\\t{}: {}\\tCall Type: {}'.format(link.rel, link.href,\n link.method))\n print('Total Amount: {} {}'.format(response.result.\n purchase_units[0].amount.currency_code, response.result.\n purchase_units[0].amount.value))\n return response\n\n def capture_order(self, token, debug=False):\n request = OrdersCaptureRequest(token)\n try:\n response = self.client.execute(request)\n order_id = response.result.id\n return order_id\n except IOError as ioe:\n return 0\n", "step-5": "from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment\nfrom paypalcheckoutsdk.orders import OrdersCaptureRequest, OrdersCreateRequest\n\nfrom django.conf import settings\n\nimport sys\n\nclass PayPalClient:\n def __init__(self):\n self.client_id = settings.PAYPAL_CLIENT_ID\n self.client_secret = settings.PAYPAL_SECRET\n\n \"\"\"Set up and return PayPal Python SDK environment with PayPal access credentials.\n This sample uses SandboxEnvironment. In production, use LiveEnvironment.\"\"\"\n\n self.environment = SandboxEnvironment(client_id=self.client_id, client_secret=self.client_secret)\n\n \"\"\" Returns PayPal HTTP client instance with environment that has access\n credentials context. Use this instance to invoke PayPal APIs, provided the\n credentials have access. \"\"\"\n self.client = PayPalHttpClient(self.environment)\n\n def object_to_json(self, json_data):\n \"\"\"\n Function to print all json data in an organized readable manner\n \"\"\"\n result = {}\n if sys.version_info[0] < 3:\n itr = json_data.__dict__.iteritems()\n else:\n itr = json_data.__dict__.items()\n for key,value in itr:\n # Skip internal attributes.\n if key.startswith(\"__\"):\n continue\n result[key] = self.array_to_json_array(value) if isinstance(value, list) else\\\n self.object_to_json(value) if not self.is_primittive(value) else\\\n value\n return result;\n def array_to_json_array(self, json_array):\n result =[]\n if isinstance(json_array, list):\n for item in json_array:\n result.append(self.object_to_json(item) if not self.is_primittive(item) \\\n else self.array_to_json_array(item) if isinstance(item, list) else item)\n return result\n\n def is_primittive(self, data):\n return isinstance(data, str) or isinstance(data, int)\n\nclass OrderClient(PayPalClient):\n\n #2. Set up your server to receive a call from the client\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_body, debug=False):\n request = OrdersCreateRequest()\n request.prefer('return=representation')\n #3. Call PayPal to set up a transaction\n request.request_body(order_body)\n response = self.client.execute(request)\n if debug:\n print('Status Code: ', response.status_code)\n print( 'Status: ', response.result.status)\n print( 'Order ID: ', response.result.id)\n print( 'Intent: ', response.result.intent)\n print ('Links:')\n for link in response.result.links:\n print('\\t{}: {}\\tCall Type: {}'.format(link.rel, link.href, link.method))\n print ('Total Amount: {} {}'.format(response.result.purchase_units[0].amount.currency_code,\n response.result.purchase_units[0].amount.value))\n\n return response\n\n\n def capture_order(self, token, debug=False):\n request = OrdersCaptureRequest(token)\n\n try :\n response = self.client.execute(request)\n order_id = response.result.id\n\n return order_id\n\n except IOError as ioe:\n return 0\n\n\n", "step-ids": [ 4, 5, 6, 8, 11 ] }
[ 4, 5, 6, 8, 11 ]
import numpy as np import pandas as pd import datetime import time from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import cross_val_score from sklearn import preprocessing from sklearn.model_selection import KFold def make_submission(y_predict, user_id_test, movie_id_test, name=None, date=True): n_elements = len(y_predict) if name is None: name = 'submission' if date: name = name + '_{}'.format(time.strftime('%d-%m-%Y_%Hh%M')) with open(name + ".csv", 'w') as f: f.write('"USER_ID_MOVIE_ID","PREDICTED_RATING"\n') for i in range(n_elements): if np.isnan(y_predict[i]): raise ValueError('NaN detected!') line = '{:0.0f},{:0.0f},{}\n'.format(user_id_test[i],movie_id_test[i],y_predict[i]) f.write(line) print("Submission file successfully written!") class ModelSelection: def __init__(self, user_data, movie_data, aggregated_data, train_data, output_train): self.train = train_data self.users = user_data self.aggregated = aggregated_data self.movies = movie_data self.output_train = output_train def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range): kf = KFold(n_splits=nb_fold) depth_n_errors = np.zeros((max_depth_range.__len__(), 2)) i = 0 for depth in max_depth_range: depth_n_errors[i][0] = depth i += 1 #First round of cv for train_index, test_index in kf.split(self.aggregated): #Second round of cv i = 0 for depth in max_depth_range: dt = DecisionTreeClassifier(max_depth=depth) scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error') depth_n_errors[i][1] += -scores.mean() i += 1 i = 0 for depth in max_depth_range: depth_n_errors[i][1] /= nb_fold i += 1 best_depth = 0 best_error = 5 #Take the best model and cross validate it on the whole data for depth, error in depth_n_errors: if(error < best_error): best_error = error best_depth = depth #Recompute the error for this model on the whole data set dt = DecisionTreeClassifier(max_depth=best_depth) final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error') return[best_depth, final_error.mean()] def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range): kf = KFold(n_splits=nb_fold) k_n_errors = np.zeros((k_range.__len__(), 2)) i = 0 for k in k_range: k_n_errors[i][0] = k i += 1 #First round of cv for train_index, test_index in kf.split(self.aggregated): #Second round of cv i = 0 for k in k_range: dt = KNeighborsClassifier(n_neighbors=k) scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error') k_n_errors[i][1] += -scores.mean() i += 1 for i in range(k_range.__len__()): k_n_errors[i][1] /= nb_fold best_k = 0 best_error = 5 #Take the best model and cross validate it on the whole data for k, error in k_n_errors: if(error < best_error): best_error = error best_k = k #Recompute the error for this model on the whole data set dt = KNeighborsClassifier(n_neighbors=best_k) final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error') return[best_k, final_error.mean()] def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range): kf = KFold(n_splits=nb_fold) k_n_errors = np.zeros((k_range.__len__(), 2)) i = 0 for k in k_range: k_n_errors[i][0] = k i += 1 #First round of cv for train_index, test_index in kf.split(self.aggregated): #Second round of cv i = 0 for k in k_range: dt = KNeighborsRegressor(n_neighbors=k) scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error') k_n_errors[i][1] += -scores.mean() i += 1 for i in range(k_range.__len__()): k_n_errors[i][1] /= nb_fold best_k = 0 best_error = 5 #Take the best model and cross validate it on the whole data for k, error in k_n_errors: if(error < best_error): best_error = error best_k = k #Recompute the error for this model on the whole data set dt = KNeighborsRegressor(n_neighbors=best_k) final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error') return[best_k, final_error.mean()] users = pd.read_csv("data/user_data_normalized_28-11-2016_01h32.csv", delimiter=",") movies = pd.read_csv("data/movie_data_normalized.csv", delimiter=",") train = pd.read_csv("data/data_train.csv", delimiter=",") output = pd.read_csv("data/output_train.csv", delimiter=",")["rating"] aggregated = pd.read_csv("data/agregated_data_28-11-2016_01h50.csv", delimiter=",") ms = ModelSelection(users.values, movies.values, aggregated.values, train.values, output) #print(ms.optimizeParametersDecisionTreeClassifier(5, range(2,3,1))) print(ms.optimizeParametersKNeighborsClassifier(5, range(1,5,1))) #print(ms.optimizeParametersKNeighborsClassifier(5, range(5,10,1)))
normal
{ "blob_id": "5172819da135600d0764033a85a4175098274806", "index": 7388, "step-1": "<mask token>\n\n\nclass ModelSelection:\n\n def __init__(self, user_data, movie_data, aggregated_data, train_data,\n output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated = aggregated_data\n self.movies = movie_data\n self.output_train = output_train\n\n def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range\n ):\n kf = KFold(n_splits=nb_fold)\n depth_n_errors = np.zeros((max_depth_range.__len__(), 2))\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][0] = depth\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for depth in max_depth_range:\n dt = DecisionTreeClassifier(max_depth=depth)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n depth_n_errors[i][1] += -scores.mean()\n i += 1\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][1] /= nb_fold\n i += 1\n best_depth = 0\n best_error = 5\n for depth, error in depth_n_errors:\n if error < best_error:\n best_error = error\n best_depth = depth\n dt = DecisionTreeClassifier(max_depth=best_depth)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_depth, final_error.mean()]\n\n def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsClassifier(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsRegressor(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsRegressor(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef make_submission(y_predict, user_id_test, movie_id_test, name=None, date\n =True):\n n_elements = len(y_predict)\n if name is None:\n name = 'submission'\n if date:\n name = name + '_{}'.format(time.strftime('%d-%m-%Y_%Hh%M'))\n with open(name + '.csv', 'w') as f:\n f.write('\"USER_ID_MOVIE_ID\",\"PREDICTED_RATING\"\\n')\n for i in range(n_elements):\n if np.isnan(y_predict[i]):\n raise ValueError('NaN detected!')\n line = '{:0.0f},{:0.0f},{}\\n'.format(user_id_test[i],\n movie_id_test[i], y_predict[i])\n f.write(line)\n print('Submission file successfully written!')\n\n\nclass ModelSelection:\n\n def __init__(self, user_data, movie_data, aggregated_data, train_data,\n output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated = aggregated_data\n self.movies = movie_data\n self.output_train = output_train\n\n def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range\n ):\n kf = KFold(n_splits=nb_fold)\n depth_n_errors = np.zeros((max_depth_range.__len__(), 2))\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][0] = depth\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for depth in max_depth_range:\n dt = DecisionTreeClassifier(max_depth=depth)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n depth_n_errors[i][1] += -scores.mean()\n i += 1\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][1] /= nb_fold\n i += 1\n best_depth = 0\n best_error = 5\n for depth, error in depth_n_errors:\n if error < best_error:\n best_error = error\n best_depth = depth\n dt = DecisionTreeClassifier(max_depth=best_depth)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_depth, final_error.mean()]\n\n def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsClassifier(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsRegressor(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsRegressor(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n\n<mask token>\nprint(ms.optimizeParametersKNeighborsClassifier(5, range(1, 5, 1)))\n", "step-3": "<mask token>\n\n\ndef make_submission(y_predict, user_id_test, movie_id_test, name=None, date\n =True):\n n_elements = len(y_predict)\n if name is None:\n name = 'submission'\n if date:\n name = name + '_{}'.format(time.strftime('%d-%m-%Y_%Hh%M'))\n with open(name + '.csv', 'w') as f:\n f.write('\"USER_ID_MOVIE_ID\",\"PREDICTED_RATING\"\\n')\n for i in range(n_elements):\n if np.isnan(y_predict[i]):\n raise ValueError('NaN detected!')\n line = '{:0.0f},{:0.0f},{}\\n'.format(user_id_test[i],\n movie_id_test[i], y_predict[i])\n f.write(line)\n print('Submission file successfully written!')\n\n\nclass ModelSelection:\n\n def __init__(self, user_data, movie_data, aggregated_data, train_data,\n output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated = aggregated_data\n self.movies = movie_data\n self.output_train = output_train\n\n def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range\n ):\n kf = KFold(n_splits=nb_fold)\n depth_n_errors = np.zeros((max_depth_range.__len__(), 2))\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][0] = depth\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for depth in max_depth_range:\n dt = DecisionTreeClassifier(max_depth=depth)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n depth_n_errors[i][1] += -scores.mean()\n i += 1\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][1] /= nb_fold\n i += 1\n best_depth = 0\n best_error = 5\n for depth, error in depth_n_errors:\n if error < best_error:\n best_error = error\n best_depth = depth\n dt = DecisionTreeClassifier(max_depth=best_depth)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_depth, final_error.mean()]\n\n def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsClassifier(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsRegressor(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsRegressor(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n\nusers = pd.read_csv('data/user_data_normalized_28-11-2016_01h32.csv',\n delimiter=',')\nmovies = pd.read_csv('data/movie_data_normalized.csv', delimiter=',')\ntrain = pd.read_csv('data/data_train.csv', delimiter=',')\noutput = pd.read_csv('data/output_train.csv', delimiter=',')['rating']\naggregated = pd.read_csv('data/agregated_data_28-11-2016_01h50.csv',\n delimiter=',')\nms = ModelSelection(users.values, movies.values, aggregated.values, train.\n values, output)\nprint(ms.optimizeParametersKNeighborsClassifier(5, range(1, 5, 1)))\n", "step-4": "import numpy as np\nimport pandas as pd\nimport datetime\nimport time\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\n\n\ndef make_submission(y_predict, user_id_test, movie_id_test, name=None, date\n =True):\n n_elements = len(y_predict)\n if name is None:\n name = 'submission'\n if date:\n name = name + '_{}'.format(time.strftime('%d-%m-%Y_%Hh%M'))\n with open(name + '.csv', 'w') as f:\n f.write('\"USER_ID_MOVIE_ID\",\"PREDICTED_RATING\"\\n')\n for i in range(n_elements):\n if np.isnan(y_predict[i]):\n raise ValueError('NaN detected!')\n line = '{:0.0f},{:0.0f},{}\\n'.format(user_id_test[i],\n movie_id_test[i], y_predict[i])\n f.write(line)\n print('Submission file successfully written!')\n\n\nclass ModelSelection:\n\n def __init__(self, user_data, movie_data, aggregated_data, train_data,\n output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated = aggregated_data\n self.movies = movie_data\n self.output_train = output_train\n\n def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range\n ):\n kf = KFold(n_splits=nb_fold)\n depth_n_errors = np.zeros((max_depth_range.__len__(), 2))\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][0] = depth\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for depth in max_depth_range:\n dt = DecisionTreeClassifier(max_depth=depth)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n depth_n_errors[i][1] += -scores.mean()\n i += 1\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][1] /= nb_fold\n i += 1\n best_depth = 0\n best_error = 5\n for depth, error in depth_n_errors:\n if error < best_error:\n best_error = error\n best_depth = depth\n dt = DecisionTreeClassifier(max_depth=best_depth)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_depth, final_error.mean()]\n\n def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsClassifier(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range):\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n for train_index, test_index in kf.split(self.aggregated):\n i = 0\n for k in k_range:\n dt = KNeighborsRegressor(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index],\n self.output_train[train_index], cv=nb_fold, scoring=\n 'neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n best_k = 0\n best_error = 5\n for k, error in k_n_errors:\n if error < best_error:\n best_error = error\n best_k = k\n dt = KNeighborsRegressor(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.\n output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n return [best_k, final_error.mean()]\n\n\nusers = pd.read_csv('data/user_data_normalized_28-11-2016_01h32.csv',\n delimiter=',')\nmovies = pd.read_csv('data/movie_data_normalized.csv', delimiter=',')\ntrain = pd.read_csv('data/data_train.csv', delimiter=',')\noutput = pd.read_csv('data/output_train.csv', delimiter=',')['rating']\naggregated = pd.read_csv('data/agregated_data_28-11-2016_01h50.csv',\n delimiter=',')\nms = ModelSelection(users.values, movies.values, aggregated.values, train.\n values, output)\nprint(ms.optimizeParametersKNeighborsClassifier(5, range(1, 5, 1)))\n", "step-5": "import numpy as np\nimport pandas as pd\nimport datetime\nimport time\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\n\ndef make_submission(y_predict, user_id_test, movie_id_test, name=None, date=True):\n n_elements = len(y_predict)\n\n if name is None:\n name = 'submission'\n if date:\n name = name + '_{}'.format(time.strftime('%d-%m-%Y_%Hh%M'))\n\n with open(name + \".csv\", 'w') as f:\n f.write('\"USER_ID_MOVIE_ID\",\"PREDICTED_RATING\"\\n')\n for i in range(n_elements):\n if np.isnan(y_predict[i]):\n raise ValueError('NaN detected!')\n line = '{:0.0f},{:0.0f},{}\\n'.format(user_id_test[i],movie_id_test[i],y_predict[i])\n f.write(line)\n print(\"Submission file successfully written!\")\n\nclass ModelSelection:\n def __init__(self, user_data, movie_data, aggregated_data, train_data, output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated = aggregated_data\n self.movies = movie_data\n self.output_train = output_train\n\n def optimizeParametersDecisionTreeClassifier(self, nb_fold, max_depth_range):\n\n kf = KFold(n_splits=nb_fold)\n depth_n_errors = np.zeros((max_depth_range.__len__(), 2))\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][0] = depth\n i += 1\n #First round of cv\n for train_index, test_index in kf.split(self.aggregated):\n #Second round of cv\n i = 0\n for depth in max_depth_range:\n dt = DecisionTreeClassifier(max_depth=depth)\n scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error')\n depth_n_errors[i][1] += -scores.mean()\n i += 1\n\n i = 0\n for depth in max_depth_range:\n depth_n_errors[i][1] /= nb_fold\n i += 1\n\n best_depth = 0\n best_error = 5\n #Take the best model and cross validate it on the whole data\n for depth, error in depth_n_errors:\n if(error < best_error):\n best_error = error\n best_depth = depth\n\n #Recompute the error for this model on the whole data set\n dt = DecisionTreeClassifier(max_depth=best_depth)\n final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n\n return[best_depth, final_error.mean()]\n\n\n def optimizeParametersKNeighborsClassifier(self, nb_fold, k_range):\n\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n #First round of cv\n for train_index, test_index in kf.split(self.aggregated):\n #Second round of cv\n i = 0\n for k in k_range:\n dt = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n\n best_k = 0\n best_error = 5\n #Take the best model and cross validate it on the whole data\n for k, error in k_n_errors:\n if(error < best_error):\n best_error = error\n best_k = k\n\n #Recompute the error for this model on the whole data set\n dt = KNeighborsClassifier(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n\n return[best_k, final_error.mean()]\n\n def optimizeParametersKNeighborsRegressor(self, nb_fold, k_range):\n\n kf = KFold(n_splits=nb_fold)\n k_n_errors = np.zeros((k_range.__len__(), 2))\n i = 0\n for k in k_range:\n k_n_errors[i][0] = k\n i += 1\n #First round of cv\n for train_index, test_index in kf.split(self.aggregated):\n #Second round of cv\n i = 0\n for k in k_range:\n dt = KNeighborsRegressor(n_neighbors=k)\n scores = cross_val_score(dt, self.aggregated[train_index], self.output_train[train_index], cv=nb_fold, scoring='neg_mean_squared_error')\n k_n_errors[i][1] += -scores.mean()\n i += 1\n\n for i in range(k_range.__len__()):\n k_n_errors[i][1] /= nb_fold\n\n best_k = 0\n best_error = 5\n #Take the best model and cross validate it on the whole data\n for k, error in k_n_errors:\n if(error < best_error):\n best_error = error\n best_k = k\n\n #Recompute the error for this model on the whole data set\n dt = KNeighborsRegressor(n_neighbors=best_k)\n final_error = -cross_val_score(dt, self.aggregated, self.output_train, cv=nb_fold, scoring='neg_mean_squared_error')\n\n return[best_k, final_error.mean()]\n\n\n\n\nusers = pd.read_csv(\"data/user_data_normalized_28-11-2016_01h32.csv\", delimiter=\",\")\nmovies = pd.read_csv(\"data/movie_data_normalized.csv\", delimiter=\",\")\ntrain = pd.read_csv(\"data/data_train.csv\", delimiter=\",\")\noutput = pd.read_csv(\"data/output_train.csv\", delimiter=\",\")[\"rating\"]\naggregated = pd.read_csv(\"data/agregated_data_28-11-2016_01h50.csv\", delimiter=\",\")\nms = ModelSelection(users.values, movies.values, aggregated.values, train.values, output)\n#print(ms.optimizeParametersDecisionTreeClassifier(5, range(2,3,1)))\nprint(ms.optimizeParametersKNeighborsClassifier(5, range(1,5,1)))\n#print(ms.optimizeParametersKNeighborsClassifier(5, range(5,10,1)))", "step-ids": [ 5, 7, 8, 9, 10 ] }
[ 5, 7, 8, 9, 10 ]
# !/usr/bin/python # coding:utf-8 import requests from bs4 import BeautifulSoup import re from datetime import datetime #紀錄檔PATH(建議絕對位置) log_path='./log.txt' #登入聯絡簿的個資 sid=''#學號(Ex. 10731187) cid=''#生份證號(Ex. A123456789) bir=''#生日(Ex. 2000/1/1) #line or telegram module #platform='telegram' platform='line' if platform=='line': from linebot import LineBotApi from linebot.models import TextSendMessage #line api token bottoken='' #line chat id chatid='' line_bot_api = LineBotApi(bottoken) if platform=='telegram': #telegram bot token bottoken='' #telegram group chat id chatid='' #課表 cls=[['學校活動','英文','化學','國文','地理','生物','公民','歷史','數學'], ['彈性課程','地科','數學','數學','資訊','西洋影視','國文','國文','英文'], ['數學','物理','生活科技','體育','國文','化學','音樂','英文','英文'], ['數學','論孟選讀','生物','多元選修','歷史','化學','英文','國防','物理'], ['彈性課程','英文','數學','地理','公民','國文','體育','物理','社團'],[],[]] def open_log(): global log global fw try: fr = open(log_path, "r") log=fr.read().split('\n') fr.close() except: fw = open(log_path, "w+") log='' return fw = open(log_path, "a") return def login_homework(): res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx') soup = BeautifulSoup(res.text, "lxml") VIEWSTATE=soup.find(id="__VIEWSTATE") VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR") EVENTVALIDATION=soup.find(id="__EVENTVALIDATION") res=requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx', allow_redirects=False, data = {'__VIEWSTATE':VIEWSTATE.get('value'),'__VIEWSTATEGENERATOR':VIEWSTATEGENERATOR.get('value'),'__EVENTVALIDATION':EVENTVALIDATION.get('value'),'chk_id':'學生/家長','tbx_sno':sid,'tbx_sid':cid,'tbx_sbir':bir,'but_login_stud':'登  入'}) global cook cook=res.cookies['ASP.NET_SessionId'] return def crawl_and_fetch_today_homework(tomorrow_calendar,tomorrow_class_table): send = requests.get('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',cookies={'ASP.NET_SessionId':cook}) soup = BeautifulSoup(send.text, "lxml") VIEWSTATE=soup.find(id="__VIEWSTATE") VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR") EVENTVALIDATION=soup.find(id="__EVENTVALIDATION") for x in range(15,1,-1):#第一頁1~15則 try:#用try怕有頁面沒15則post #數字轉文字 num=str('') if(x<10): num='0'+str(x) else: num=str(x) #爬內文 send = requests.post('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',cookies={'ASP.NET_SessionId':cook}, data = {'__VIEWSTATE':VIEWSTATE.get('value'),'__VIEWSTATEGENERATOR':VIEWSTATEGENERATOR.get('value'),'__EVENTVALIDATION':EVENTVALIDATION.get('value'),('GridViewS$ctl'+num+'$but_vf1'):'詳細內容'}) soup = BeautifulSoup(send.text, "lxml") #檢查市否已發過 ok=bool(True) for y in range(0,len(log),1): if soup.find(id='Lab_purport').text==log[y]: ok=bool(False) if ok==True:#沒發過 fw.write(soup.find(id='Lab_purport').text+'\n') post_title=str('[主旨:'+str(soup.find(id='Lab_purport').text)+']') post_content=str(soup.find(id='Lab_content').text) post_attachment=str(' ') if(soup.find(target='_blank')): post_attachment=soup.find(target='_blank').get('href') send_word=post_title+'\n'+post_content+'\n'+post_attachment if(str(soup.find(id='Lab_purport').text).find('聯絡簿')>=0 and datetime.today().weekday()<4): send_word=send_word+'\n***系統訊息***\n'+tomorrow_calendar+'\n'+tomorrow_class_table if(str(soup.find(id='Lab_purport').text).find('聯絡簿')>=0 and datetime.today().weekday() == 4 ): send_word=send_word post(send_word) except: pass return def crawl_tomorrow_calendar(): res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx') soup = BeautifulSoup(res.text, "lxml") calendar='明日行事曆:\n 全校:'+soup.find_all(color="#404040")[16].text if(soup.find_all(color="#404040")[16].text==' '): calendar+='N/A' calendar=calendar+'\n 高一:'+soup.find_all(color="#404040")[21].text if(soup.find_all(color="#404040")[21].text==' '): calendar+='N/A' return calendar def fetch_tomorrow_class_table(): count=int(0) tomorrow_class='\n明日課表:\n 早上:\n ' for i in cls[(datetime.today().weekday()+1)%7]: if(count==4): tomorrow_class+='\n 下午:\n ' tomorrow_class+='['+i+']' if(count<8 and count!=3): tomorrow_class+='->' count+=1 return tomorrow_class def post(send_word): if platform=='line': line_bot_api.push_message(chatid,TextSendMessage(text=send_word,wrap=True)) if platform=='telegram': requests.get("https://api.telegram.org/bot"+bottoken+"/sendMessage?chat_id="+chatid+"&text="+send_word) ''' !!!contact ab0897867564534231@gmail.com for this function!!! def crawl_message_board(): res = requests.get('http://59.120.227.144:11300/line/api.php') soup = BeautifulSoup(res.text, "lxml") message_board = soup.find_all('td') message='\n\n留言板( http://59.120.227.144:11300/line/ ) : \n' for i in range(0,len(message_board),3): message=message+'第'+str(int((i/3)+1))+'則:\n-'+message_board[i+1].text+"\n--來自:"+message_board[i+2].text+'\n' return message ''' def close_log(): fw.close() def main(): open_log() login_homework() crawl_and_fetch_today_homework(crawl_tomorrow_calendar(),fetch_tomorrow_class_table()) close_log() #星期天提醒明天要上課 if(datetime.today().weekday()==6 and datetime.today().hour == 21 and datetime.today().minute<10): send_word='[主旨:機器人訊息]\n***系統訊息***\n'+crawl_tomorrow_calendar()+'\n'+fetch_tomorrow_class_table() post(send_word) main()
normal
{ "blob_id": "77f37a80d160e42bb74017a55aa9d06b4c8d4fee", "index": 4320, "step-1": "<mask token>\n\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n res = requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx',\n allow_redirects=False, data={'__VIEWSTATE': VIEWSTATE.get('value'),\n '__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR.get('value'),\n '__EVENTVALIDATION': EVENTVALIDATION.get('value'), 'chk_id':\n '學生/家長', 'tbx_sno': sid, 'tbx_sid': cid, 'tbx_sbir': bir,\n 'but_login_stud': '登\\u3000\\u3000入'})\n global cook\n cook = res.cookies['ASP.NET_SessionId']\n return\n\n\n<mask token>\n\n\ndef crawl_tomorrow_calendar():\n res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n calendar = '明日行事曆:\\n 全校:' + soup.find_all(color='#404040')[16].text\n if soup.find_all(color='#404040')[16].text == '\\xa0':\n calendar += 'N/A'\n calendar = calendar + '\\n 高一:' + soup.find_all(color='#404040')[21].text\n if soup.find_all(color='#404040')[21].text == '\\xa0':\n calendar += 'N/A'\n return calendar\n\n\ndef fetch_tomorrow_class_table():\n count = int(0)\n tomorrow_class = '\\n明日課表:\\n 早上:\\n '\n for i in cls[(datetime.today().weekday() + 1) % 7]:\n if count == 4:\n tomorrow_class += '\\n 下午:\\n '\n tomorrow_class += '[' + i + ']'\n if count < 8 and count != 3:\n tomorrow_class += '->'\n count += 1\n return tomorrow_class\n\n\ndef post(send_word):\n if platform == 'line':\n line_bot_api.push_message(chatid, TextSendMessage(text=send_word,\n wrap=True))\n if platform == 'telegram':\n requests.get('https://api.telegram.org/bot' + bottoken +\n '/sendMessage?chat_id=' + chatid + '&text=' + send_word)\n\n\n<mask token>\n\n\ndef close_log():\n fw.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef open_log():\n global log\n global fw\n try:\n fr = open(log_path, 'r')\n log = fr.read().split('\\n')\n fr.close()\n except:\n fw = open(log_path, 'w+')\n log = ''\n return\n fw = open(log_path, 'a')\n return\n\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n res = requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx',\n allow_redirects=False, data={'__VIEWSTATE': VIEWSTATE.get('value'),\n '__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR.get('value'),\n '__EVENTVALIDATION': EVENTVALIDATION.get('value'), 'chk_id':\n '學生/家長', 'tbx_sno': sid, 'tbx_sid': cid, 'tbx_sbir': bir,\n 'but_login_stud': '登\\u3000\\u3000入'})\n global cook\n cook = res.cookies['ASP.NET_SessionId']\n return\n\n\ndef crawl_and_fetch_today_homework(tomorrow_calendar, tomorrow_class_table):\n send = requests.get('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx', cookies\n ={'ASP.NET_SessionId': cook})\n soup = BeautifulSoup(send.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n for x in range(15, 1, -1):\n try:\n num = str('')\n if x < 10:\n num = '0' + str(x)\n else:\n num = str(x)\n send = requests.post('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',\n cookies={'ASP.NET_SessionId': cook}, data={'__VIEWSTATE':\n VIEWSTATE.get('value'), '__VIEWSTATEGENERATOR':\n VIEWSTATEGENERATOR.get('value'), '__EVENTVALIDATION':\n EVENTVALIDATION.get('value'), ('GridViewS$ctl' + num +\n '$but_vf1'): '詳細內容'})\n soup = BeautifulSoup(send.text, 'lxml')\n ok = bool(True)\n for y in range(0, len(log), 1):\n if soup.find(id='Lab_purport').text == log[y]:\n ok = bool(False)\n if ok == True:\n fw.write(soup.find(id='Lab_purport').text + '\\n')\n post_title = str('[主旨:' + str(soup.find(id='Lab_purport').\n text) + ']')\n post_content = str(soup.find(id='Lab_content').text)\n post_attachment = str(' ')\n if soup.find(target='_blank'):\n post_attachment = soup.find(target='_blank').get('href')\n send_word = (post_title + '\\n' + post_content + '\\n' +\n post_attachment)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() < 4:\n send_word = (send_word + '\\n***系統訊息***\\n' +\n tomorrow_calendar + '\\n' + tomorrow_class_table)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() == 4:\n send_word = send_word\n post(send_word)\n except:\n pass\n return\n\n\ndef crawl_tomorrow_calendar():\n res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n calendar = '明日行事曆:\\n 全校:' + soup.find_all(color='#404040')[16].text\n if soup.find_all(color='#404040')[16].text == '\\xa0':\n calendar += 'N/A'\n calendar = calendar + '\\n 高一:' + soup.find_all(color='#404040')[21].text\n if soup.find_all(color='#404040')[21].text == '\\xa0':\n calendar += 'N/A'\n return calendar\n\n\ndef fetch_tomorrow_class_table():\n count = int(0)\n tomorrow_class = '\\n明日課表:\\n 早上:\\n '\n for i in cls[(datetime.today().weekday() + 1) % 7]:\n if count == 4:\n tomorrow_class += '\\n 下午:\\n '\n tomorrow_class += '[' + i + ']'\n if count < 8 and count != 3:\n tomorrow_class += '->'\n count += 1\n return tomorrow_class\n\n\ndef post(send_word):\n if platform == 'line':\n line_bot_api.push_message(chatid, TextSendMessage(text=send_word,\n wrap=True))\n if platform == 'telegram':\n requests.get('https://api.telegram.org/bot' + bottoken +\n '/sendMessage?chat_id=' + chatid + '&text=' + send_word)\n\n\n<mask token>\n\n\ndef close_log():\n fw.close()\n\n\ndef main():\n open_log()\n login_homework()\n crawl_and_fetch_today_homework(crawl_tomorrow_calendar(),\n fetch_tomorrow_class_table())\n close_log()\n if datetime.today().weekday() == 6 and datetime.today(\n ).hour == 21 and datetime.today().minute < 10:\n send_word = '[主旨:機器人訊息]\\n***系統訊息***\\n' + crawl_tomorrow_calendar(\n ) + '\\n' + fetch_tomorrow_class_table()\n post(send_word)\n\n\n<mask token>\n", "step-3": "<mask token>\nlog_path = './log.txt'\nsid = ''\ncid = ''\nbir = ''\nplatform = 'line'\nif platform == 'line':\n from linebot import LineBotApi\n from linebot.models import TextSendMessage\n bottoken = ''\n chatid = ''\n line_bot_api = LineBotApi(bottoken)\nif platform == 'telegram':\n bottoken = ''\n chatid = ''\ncls = [['學校活動', '英文', '化學', '國文', '地理', '生物', '公民', '歷史', '數學'], ['彈性課程',\n '地科', '數學', '數學', '資訊', '西洋影視', '國文', '國文', '英文'], ['數學', '物理', '生活科技',\n '體育', '國文', '化學', '音樂', '英文', '英文'], ['數學', '論孟選讀', '生物', '多元選修', '歷史',\n '化學', '英文', '國防', '物理'], ['彈性課程', '英文', '數學', '地理', '公民', '國文', '體育',\n '物理', '社團'], [], []]\n\n\ndef open_log():\n global log\n global fw\n try:\n fr = open(log_path, 'r')\n log = fr.read().split('\\n')\n fr.close()\n except:\n fw = open(log_path, 'w+')\n log = ''\n return\n fw = open(log_path, 'a')\n return\n\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n res = requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx',\n allow_redirects=False, data={'__VIEWSTATE': VIEWSTATE.get('value'),\n '__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR.get('value'),\n '__EVENTVALIDATION': EVENTVALIDATION.get('value'), 'chk_id':\n '學生/家長', 'tbx_sno': sid, 'tbx_sid': cid, 'tbx_sbir': bir,\n 'but_login_stud': '登\\u3000\\u3000入'})\n global cook\n cook = res.cookies['ASP.NET_SessionId']\n return\n\n\ndef crawl_and_fetch_today_homework(tomorrow_calendar, tomorrow_class_table):\n send = requests.get('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx', cookies\n ={'ASP.NET_SessionId': cook})\n soup = BeautifulSoup(send.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n for x in range(15, 1, -1):\n try:\n num = str('')\n if x < 10:\n num = '0' + str(x)\n else:\n num = str(x)\n send = requests.post('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',\n cookies={'ASP.NET_SessionId': cook}, data={'__VIEWSTATE':\n VIEWSTATE.get('value'), '__VIEWSTATEGENERATOR':\n VIEWSTATEGENERATOR.get('value'), '__EVENTVALIDATION':\n EVENTVALIDATION.get('value'), ('GridViewS$ctl' + num +\n '$but_vf1'): '詳細內容'})\n soup = BeautifulSoup(send.text, 'lxml')\n ok = bool(True)\n for y in range(0, len(log), 1):\n if soup.find(id='Lab_purport').text == log[y]:\n ok = bool(False)\n if ok == True:\n fw.write(soup.find(id='Lab_purport').text + '\\n')\n post_title = str('[主旨:' + str(soup.find(id='Lab_purport').\n text) + ']')\n post_content = str(soup.find(id='Lab_content').text)\n post_attachment = str(' ')\n if soup.find(target='_blank'):\n post_attachment = soup.find(target='_blank').get('href')\n send_word = (post_title + '\\n' + post_content + '\\n' +\n post_attachment)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() < 4:\n send_word = (send_word + '\\n***系統訊息***\\n' +\n tomorrow_calendar + '\\n' + tomorrow_class_table)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() == 4:\n send_word = send_word\n post(send_word)\n except:\n pass\n return\n\n\ndef crawl_tomorrow_calendar():\n res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n calendar = '明日行事曆:\\n 全校:' + soup.find_all(color='#404040')[16].text\n if soup.find_all(color='#404040')[16].text == '\\xa0':\n calendar += 'N/A'\n calendar = calendar + '\\n 高一:' + soup.find_all(color='#404040')[21].text\n if soup.find_all(color='#404040')[21].text == '\\xa0':\n calendar += 'N/A'\n return calendar\n\n\ndef fetch_tomorrow_class_table():\n count = int(0)\n tomorrow_class = '\\n明日課表:\\n 早上:\\n '\n for i in cls[(datetime.today().weekday() + 1) % 7]:\n if count == 4:\n tomorrow_class += '\\n 下午:\\n '\n tomorrow_class += '[' + i + ']'\n if count < 8 and count != 3:\n tomorrow_class += '->'\n count += 1\n return tomorrow_class\n\n\ndef post(send_word):\n if platform == 'line':\n line_bot_api.push_message(chatid, TextSendMessage(text=send_word,\n wrap=True))\n if platform == 'telegram':\n requests.get('https://api.telegram.org/bot' + bottoken +\n '/sendMessage?chat_id=' + chatid + '&text=' + send_word)\n\n\n<mask token>\n\n\ndef close_log():\n fw.close()\n\n\ndef main():\n open_log()\n login_homework()\n crawl_and_fetch_today_homework(crawl_tomorrow_calendar(),\n fetch_tomorrow_class_table())\n close_log()\n if datetime.today().weekday() == 6 and datetime.today(\n ).hour == 21 and datetime.today().minute < 10:\n send_word = '[主旨:機器人訊息]\\n***系統訊息***\\n' + crawl_tomorrow_calendar(\n ) + '\\n' + fetch_tomorrow_class_table()\n post(send_word)\n\n\nmain()\n", "step-4": "import requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nlog_path = './log.txt'\nsid = ''\ncid = ''\nbir = ''\nplatform = 'line'\nif platform == 'line':\n from linebot import LineBotApi\n from linebot.models import TextSendMessage\n bottoken = ''\n chatid = ''\n line_bot_api = LineBotApi(bottoken)\nif platform == 'telegram':\n bottoken = ''\n chatid = ''\ncls = [['學校活動', '英文', '化學', '國文', '地理', '生物', '公民', '歷史', '數學'], ['彈性課程',\n '地科', '數學', '數學', '資訊', '西洋影視', '國文', '國文', '英文'], ['數學', '物理', '生活科技',\n '體育', '國文', '化學', '音樂', '英文', '英文'], ['數學', '論孟選讀', '生物', '多元選修', '歷史',\n '化學', '英文', '國防', '物理'], ['彈性課程', '英文', '數學', '地理', '公民', '國文', '體育',\n '物理', '社團'], [], []]\n\n\ndef open_log():\n global log\n global fw\n try:\n fr = open(log_path, 'r')\n log = fr.read().split('\\n')\n fr.close()\n except:\n fw = open(log_path, 'w+')\n log = ''\n return\n fw = open(log_path, 'a')\n return\n\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n res = requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx',\n allow_redirects=False, data={'__VIEWSTATE': VIEWSTATE.get('value'),\n '__VIEWSTATEGENERATOR': VIEWSTATEGENERATOR.get('value'),\n '__EVENTVALIDATION': EVENTVALIDATION.get('value'), 'chk_id':\n '學生/家長', 'tbx_sno': sid, 'tbx_sid': cid, 'tbx_sbir': bir,\n 'but_login_stud': '登\\u3000\\u3000入'})\n global cook\n cook = res.cookies['ASP.NET_SessionId']\n return\n\n\ndef crawl_and_fetch_today_homework(tomorrow_calendar, tomorrow_class_table):\n send = requests.get('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx', cookies\n ={'ASP.NET_SessionId': cook})\n soup = BeautifulSoup(send.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(id='__VIEWSTATEGENERATOR')\n EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')\n for x in range(15, 1, -1):\n try:\n num = str('')\n if x < 10:\n num = '0' + str(x)\n else:\n num = str(x)\n send = requests.post('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',\n cookies={'ASP.NET_SessionId': cook}, data={'__VIEWSTATE':\n VIEWSTATE.get('value'), '__VIEWSTATEGENERATOR':\n VIEWSTATEGENERATOR.get('value'), '__EVENTVALIDATION':\n EVENTVALIDATION.get('value'), ('GridViewS$ctl' + num +\n '$but_vf1'): '詳細內容'})\n soup = BeautifulSoup(send.text, 'lxml')\n ok = bool(True)\n for y in range(0, len(log), 1):\n if soup.find(id='Lab_purport').text == log[y]:\n ok = bool(False)\n if ok == True:\n fw.write(soup.find(id='Lab_purport').text + '\\n')\n post_title = str('[主旨:' + str(soup.find(id='Lab_purport').\n text) + ']')\n post_content = str(soup.find(id='Lab_content').text)\n post_attachment = str(' ')\n if soup.find(target='_blank'):\n post_attachment = soup.find(target='_blank').get('href')\n send_word = (post_title + '\\n' + post_content + '\\n' +\n post_attachment)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() < 4:\n send_word = (send_word + '\\n***系統訊息***\\n' +\n tomorrow_calendar + '\\n' + tomorrow_class_table)\n if str(soup.find(id='Lab_purport').text).find('聯絡簿'\n ) >= 0 and datetime.today().weekday() == 4:\n send_word = send_word\n post(send_word)\n except:\n pass\n return\n\n\ndef crawl_tomorrow_calendar():\n res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n calendar = '明日行事曆:\\n 全校:' + soup.find_all(color='#404040')[16].text\n if soup.find_all(color='#404040')[16].text == '\\xa0':\n calendar += 'N/A'\n calendar = calendar + '\\n 高一:' + soup.find_all(color='#404040')[21].text\n if soup.find_all(color='#404040')[21].text == '\\xa0':\n calendar += 'N/A'\n return calendar\n\n\ndef fetch_tomorrow_class_table():\n count = int(0)\n tomorrow_class = '\\n明日課表:\\n 早上:\\n '\n for i in cls[(datetime.today().weekday() + 1) % 7]:\n if count == 4:\n tomorrow_class += '\\n 下午:\\n '\n tomorrow_class += '[' + i + ']'\n if count < 8 and count != 3:\n tomorrow_class += '->'\n count += 1\n return tomorrow_class\n\n\ndef post(send_word):\n if platform == 'line':\n line_bot_api.push_message(chatid, TextSendMessage(text=send_word,\n wrap=True))\n if platform == 'telegram':\n requests.get('https://api.telegram.org/bot' + bottoken +\n '/sendMessage?chat_id=' + chatid + '&text=' + send_word)\n\n\n<mask token>\n\n\ndef close_log():\n fw.close()\n\n\ndef main():\n open_log()\n login_homework()\n crawl_and_fetch_today_homework(crawl_tomorrow_calendar(),\n fetch_tomorrow_class_table())\n close_log()\n if datetime.today().weekday() == 6 and datetime.today(\n ).hour == 21 and datetime.today().minute < 10:\n send_word = '[主旨:機器人訊息]\\n***系統訊息***\\n' + crawl_tomorrow_calendar(\n ) + '\\n' + fetch_tomorrow_class_table()\n post(send_word)\n\n\nmain()\n", "step-5": "# !/usr/bin/python \n# coding:utf-8 \nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\n\n#紀錄檔PATH(建議絕對位置)\nlog_path='./log.txt'\n\n#登入聯絡簿的個資\nsid=''#學號(Ex. 10731187)\ncid=''#生份證號(Ex. A123456789)\nbir=''#生日(Ex. 2000/1/1)\n\n#line or telegram module\n\n#platform='telegram'\nplatform='line'\n\nif platform=='line':\n from linebot import LineBotApi\n from linebot.models import TextSendMessage\n #line api token\n bottoken=''\n #line chat id\n chatid=''\n\n line_bot_api = LineBotApi(bottoken)\n\nif platform=='telegram':\n #telegram bot token\n bottoken=''\n #telegram group chat id\n chatid=''\n\n#課表\ncls=[['學校活動','英文','化學','國文','地理','生物','公民','歷史','數學'],\n ['彈性課程','地科','數學','數學','資訊','西洋影視','國文','國文','英文'],\n ['數學','物理','生活科技','體育','國文','化學','音樂','英文','英文'],\n ['數學','論孟選讀','生物','多元選修','歷史','化學','英文','國防','物理'],\n ['彈性課程','英文','數學','地理','公民','國文','體育','物理','社團'],[],[]]\n\ndef open_log():\n global log\n global fw\n try:\n fr = open(log_path, \"r\")\n log=fr.read().split('\\n')\n fr.close()\n except:\n fw = open(log_path, \"w+\")\n log=''\n return\n fw = open(log_path, \"a\")\n return\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, \"lxml\")\n VIEWSTATE=soup.find(id=\"__VIEWSTATE\")\n VIEWSTATEGENERATOR=soup.find(id=\"__VIEWSTATEGENERATOR\")\n EVENTVALIDATION=soup.find(id=\"__EVENTVALIDATION\")\n res=requests.post('http://www.yphs.tp.edu.tw/tea/tu2.aspx', allow_redirects=False, data = {'__VIEWSTATE':VIEWSTATE.get('value'),'__VIEWSTATEGENERATOR':VIEWSTATEGENERATOR.get('value'),'__EVENTVALIDATION':EVENTVALIDATION.get('value'),'chk_id':'學生/家長','tbx_sno':sid,'tbx_sid':cid,'tbx_sbir':bir,'but_login_stud':'登  入'})\n global cook\n cook=res.cookies['ASP.NET_SessionId']\n return\n\ndef crawl_and_fetch_today_homework(tomorrow_calendar,tomorrow_class_table):\n send = requests.get('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',cookies={'ASP.NET_SessionId':cook})\n soup = BeautifulSoup(send.text, \"lxml\")\n VIEWSTATE=soup.find(id=\"__VIEWSTATE\")\n VIEWSTATEGENERATOR=soup.find(id=\"__VIEWSTATEGENERATOR\")\n EVENTVALIDATION=soup.find(id=\"__EVENTVALIDATION\")\n for x in range(15,1,-1):#第一頁1~15則\n try:#用try怕有頁面沒15則post\n #數字轉文字\n num=str('')\n if(x<10):\n num='0'+str(x)\n else:\n num=str(x)\n #爬內文\n send = requests.post('http://www.yphs.tp.edu.tw/tea/tu2-1.aspx',cookies={'ASP.NET_SessionId':cook}, data = {'__VIEWSTATE':VIEWSTATE.get('value'),'__VIEWSTATEGENERATOR':VIEWSTATEGENERATOR.get('value'),'__EVENTVALIDATION':EVENTVALIDATION.get('value'),('GridViewS$ctl'+num+'$but_vf1'):'詳細內容'})\n soup = BeautifulSoup(send.text, \"lxml\")\n #檢查市否已發過\n ok=bool(True)\n for y in range(0,len(log),1):\n if soup.find(id='Lab_purport').text==log[y]:\n ok=bool(False)\n if ok==True:#沒發過\n fw.write(soup.find(id='Lab_purport').text+'\\n')\n post_title=str('[主旨:'+str(soup.find(id='Lab_purport').text)+']')\n post_content=str(soup.find(id='Lab_content').text)\n post_attachment=str(' ')\n if(soup.find(target='_blank')):\n post_attachment=soup.find(target='_blank').get('href')\n send_word=post_title+'\\n'+post_content+'\\n'+post_attachment\n if(str(soup.find(id='Lab_purport').text).find('聯絡簿')>=0 and datetime.today().weekday()<4):\n send_word=send_word+'\\n***系統訊息***\\n'+tomorrow_calendar+'\\n'+tomorrow_class_table\n if(str(soup.find(id='Lab_purport').text).find('聯絡簿')>=0 and datetime.today().weekday() == 4 ):\n send_word=send_word\n post(send_word)\n except:\n pass\n return\n\ndef crawl_tomorrow_calendar():\n res = requests.get('http://www.yphs.tp.edu.tw/yphs/gr2.aspx')\n soup = BeautifulSoup(res.text, \"lxml\")\n calendar='明日行事曆:\\n 全校:'+soup.find_all(color=\"#404040\")[16].text\n if(soup.find_all(color=\"#404040\")[16].text==' '):\n calendar+='N/A'\n calendar=calendar+'\\n 高一:'+soup.find_all(color=\"#404040\")[21].text\n if(soup.find_all(color=\"#404040\")[21].text==' '):\n calendar+='N/A'\n return calendar\n\ndef fetch_tomorrow_class_table():\n count=int(0)\n tomorrow_class='\\n明日課表:\\n 早上:\\n '\n for i in cls[(datetime.today().weekday()+1)%7]:\n if(count==4):\n tomorrow_class+='\\n 下午:\\n '\n tomorrow_class+='['+i+']'\n if(count<8 and count!=3):\n tomorrow_class+='->'\n count+=1\n return tomorrow_class\n\ndef post(send_word):\n if platform=='line':\n line_bot_api.push_message(chatid,TextSendMessage(text=send_word,wrap=True))\n if platform=='telegram':\n requests.get(\"https://api.telegram.org/bot\"+bottoken+\"/sendMessage?chat_id=\"+chatid+\"&text=\"+send_word)\n'''\n\n!!!contact ab0897867564534231@gmail.com for this function!!!\n\ndef crawl_message_board():\n res = requests.get('http://59.120.227.144:11300/line/api.php')\n soup = BeautifulSoup(res.text, \"lxml\")\n message_board = soup.find_all('td')\n message='\\n\\n留言板( http://59.120.227.144:11300/line/ ) : \\n'\n for i in range(0,len(message_board),3):\n message=message+'第'+str(int((i/3)+1))+'則:\\n-'+message_board[i+1].text+\"\\n--來自:\"+message_board[i+2].text+'\\n'\n return message\n'''\n\ndef close_log():\n fw.close()\n\ndef main():\n open_log()\n login_homework()\n crawl_and_fetch_today_homework(crawl_tomorrow_calendar(),fetch_tomorrow_class_table())\n close_log()\n\n #星期天提醒明天要上課\n if(datetime.today().weekday()==6 and datetime.today().hour == 21 and datetime.today().minute<10):\n send_word='[主旨:機器人訊息]\\n***系統訊息***\\n'+crawl_tomorrow_calendar()+'\\n'+fetch_tomorrow_class_table()\n post(send_word)\nmain()", "step-ids": [ 5, 8, 10, 11, 12 ] }
[ 5, 8, 10, 11, 12 ]
from selenium import webdriver import time import datetime import os import openpyxl as vb from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.action_chains import ActionChains def deconnexion(Chrome): """登陆""" """初始化""" global web, actions web = webdriver.Chrome(Chrome) #公司电脑 # web = webdriver.Chrome(r'D:\python\webdrivers\chromedriver.exe') #自己的电脑 web.maximize_window() web.implicitly_wait(10) # 最大运行时间不超过10秒 web.get('http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain') actions = ActionChains(web) """登录网页""" username = web.find_element_by_xpath('/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input') # 获得账号和密码 password = web.find_element_by_xpath('/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input') username.send_keys('15375429564') password.send_keys("cdc1234cdc") enter = web.find_element_by_xpath("/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button") enter.click() return 0 def menu_lien(): """跳转页面""" enter_into = web.find_element_by_xpath( "/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article") enter_into.click() return 0 def confirm_area(city, area): """确定区域""" """点击区域""" enter_area = web.find_element_by_xpath("/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input").click() """点击安徽省""" enter_on_on = web.find_element_by_class_name("el-cascader__dropdown") enter_on = enter_on_on.find_element_by_class_name("el-cascader-panel") try: enter_AnHui_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_AnHui_on =enter_AnHui_on_on[0].find_element_by_class_name("el-scrollbar__view") except: time.sleep(1) enter_AnHui_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name("el-scrollbar__view") enter_AnHui = enter_AnHui_on.find_element_by_tag_name("li") enter_AnHui_down =enter_AnHui.find_element_by_class_name("el-radio__input") web.execute_script("arguments[0].click();", enter_AnHui_down) """选择城市""" enter_on_on = web.find_element_by_class_name("el-cascader__dropdown") enter_on = enter_on_on.find_element_by_class_name("el-cascader-panel") try: enter_city_on_on =enter_on.find_elements_by_class_name("el-scrollbar") enter_city_on = enter_city_on_on[1].find_element_by_class_name("el-cascader-menu__wrap") except: time.sleep(1) enter_city_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_city_on = enter_city_on_on[1].find_element_by_class_name("el-cascader-menu__wrap") enter_city = enter_city_on.find_elements_by_tag_name("li") for i in range(len(enter_city)): enter_on_on = web.find_element_by_class_name("el-cascader__dropdown") enter_on = enter_on_on.find_element_by_class_name("el-cascader-panel") enter_city_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_city_on = enter_city_on_on[1].find_element_by_class_name("el-cascader-menu__wrap") enter_city = enter_city_on.find_elements_by_tag_name("li") if enter_city[i].text ==city: enter_city_down = enter_city[i].find_element_by_class_name("el-radio__input") web.execute_script("arguments[0].click();", enter_city_down) break """选则区县""" enter_on_on = web.find_element_by_class_name("el-cascader__dropdown") enter_on = enter_on_on.find_element_by_class_name("el-cascader-panel") try: enter_area_on_on =enter_on.find_elements_by_class_name("el-scrollbar") enter_area_on = enter_area_on_on[2].find_element_by_class_name("el-cascader-menu__wrap") except: time.sleep(1) enter_area_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_area_on = enter_area_on_on[2].find_element_by_class_name("el-cascader-menu__wrap") enter_area = enter_area_on.find_elements_by_tag_name("li") for i in range(len(enter_area)): enter_on_on = web.find_element_by_class_name("el-cascader__dropdown") enter_on = enter_on_on.find_element_by_class_name("el-cascader-panel") enter_area_on_on = enter_on.find_elements_by_class_name("el-scrollbar") enter_area_on = enter_area_on_on[2].find_element_by_class_name("el-cascader-menu__wrap") enter_area = enter_area_on.find_elements_by_tag_name("li") if enter_area[i].text ==area: enter_area_down = enter_area[i].find_element_by_class_name("el-radio__input") web.execute_script("arguments[0].click();", enter_area_down) break return 0 def confirm_time_on(excel_time): if type(excel_time) == str: return str(excel_time) elif type(excel_time) == datetime.datetime: excel_time_2 = excel_time.strftime('%Y-%m-%d') return str(excel_time_2) def confirm_tiem(time): """确定时间""" time =confirm_time_on(time) enter_time = web.find_elements_by_class_name("el-range-input") for i in enter_time: i.send_keys(time) return 0 def confirm_cause(cause): """选则症状""" enter_symptom = web.find_element_by_xpath("/html/body/div[1]/section/main/div/div[3]/div[3]/span/div/div[2]/input").click() enter_on = web.find_element_by_class_name("is-multiple") enter_on_1 =enter_on.find_element_by_class_name("el-scrollbar") enter_on_symptom = enter_on_1.find_elements_by_tag_name("li") for i in range(len(enter_on_symptom)): enter_on = web.find_element_by_class_name("is-multiple") enter_on_symptom = enter_on.find_elements_by_tag_name("li") if enter_on_symptom[i].text == cause: enter_on_symptom[i].click() break return 0 def search(): """点击搜索""" enter_search = web.find_element_by_xpath("/html/body/div[1]/section/main/div/div[3]/button[1]").click() return 0 def reset(): """点击重置""" enter_reset = web.find_element_by_xpath("/html/body/div/section/main/div/div[3]/button[2]").click() return 0 def pending(): """待处理""" enter_pending = web.find_element_by_xpath( "/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[1]").click() return 0 def accomplish(): """已完成""" enter__accomplish = web.find_element_by_xpath( "/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[3]").click() return 0 def download_cas(): """下载病例""" enter_download_cas = web.find_element_by_xpath( "/html/body/div[1]/section/main/section/main/div[2]/ul/li[2]").click() enter_download_cas_1 = web.find_element_by_xpath( "/html/body/div[1]/section/main/section/main/div[2]/div/div[2]/div/div[1]/div/button[3]").click() return 0 def resetting_excel(cause, clinique, path="D:\林钟\下载"): """重命名病例""" try: files = os.listdir(path) src = path + "\\" + "外呼结果导出表格.xlsx" if cause =="发热伴畏寒|寒战": cause ="发热伴畏寒寒战'" if cause == "畏寒|寒战": cause = "畏寒寒战'" dst = path + "\\" + clinique + "--" + cause + ".xlsx" os.rename(src, dst) except (FileExistsError): files = os.listdir(path) src = path + "\\" + "外呼结果导出表格.xlsx" if cause =="发热伴畏寒|寒战": cause ="发热伴畏寒寒战'" if cause == "畏寒|寒战": cause = "畏寒寒战'" dst = path + "\\" + clinique + "--" + cause + ".xlsx" os.remove(dst) os.rename(src, dst) return 0 def pagination(): #获取当前界面一共有多少条数据 pagination__total = web.find_element_by_xpath("/html/body/div[1]/section/main/div/div[5]/span[1]") a = int(pagination__total.text[2:-2]) return a def search_data(cause, city, area, clinique, excel_time): """查找数据""" ls_2 =[] #存储最终点击的元素,如果为空则说明没找到。 trlist_table_on = web.find_element_by_class_name("is-scrolling-none") trlist_table = trlist_table_on.find_element_by_class_name("el-table__body") trlist_tr = trlist_table.find_elements_by_tag_name("tr") for row in range(len(trlist_tr)): trlist_table = web.find_element_by_class_name("el-table__body") trlist_tr = trlist_table.find_elements_by_tag_name("tr") trlist_td = trlist_tr[row].find_elements_by_tag_name("td") i = 0 j = 0 ls = [] for col in range(len(trlist_td)): i += 1 if i == 2: ls.append(trlist_td[col].text) elif i == 3: ls.append(trlist_td[col].text) elif i == 7: ls.append(trlist_td[col]) elif i == 9: j = 1 ls.append((trlist_td[col])) trlist_td = trlist_tr[row].find_elements_by_tag_name("td") if ls[0] == cause: if ls[1] == ("安徽省/" + city + "/" + area + "/" + clinique): if j == 0: # ls[2].click() ls_2.append(ls[2]) elif j == 1: # ls[3].click() ls_2.append(ls[3]) return ls_2 def search_data_down(cause,clinique,path): """找到病例后的对病例进行一系列的处理""" """下载病例""" download_cas() """返回上一界面""" web.back() """点击重置""" reset() """点击待完成""" pending() """给病例重命名""" time.sleep(2) try: resetting_excel(cause, clinique,path) except FileNotFoundError: time.sleep(2) resetting_excel(cause, clinique,path) print(clinique + "--" + cause + "已下载完成!") def tourne_page(): enter_tourne_page =web.find_element_by_xpath("/html/body/div[1]/section/main/div/div[5]/button[2]/i").click() return "" def search_data_on(cause, city, area, clinique, excel_time,path): """核心处理流程""" time.sleep(2) number = pagination() """判断待处理下标是否为0""" if number == 0 : """点击已完成""" accomplish() time.sleep(2) number_accmplish_1 = pagination() """判断已完成的下标是否为0""" if number_accmplish_1 == 0: """如果为0下载失败""" download_revers.append(clinique + "--" + cause + " 下载失败!") else: """不为0判断当前界面是否只有20条数据""" if 0 < number_accmplish_1 <= 20: """只有20条数据查找数据""" accomplish_search_data = search_data(cause, city, area, clinique, excel_time) if len(accomplish_search_data) == 0: """如果没找到结束""" download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """如果找到则点击""" accomplish_search_data[0].click() search_data_down(cause,clinique,path) elif 20 < number_accmplish_1 <= 40: """多于20条数据""" accomplish_search_data = search_data(cause, city, area, clinique, excel_time) """判断第一页有没有查到""" if len(accomplish_search_data) == 0: """如果没找到翻页""" tourne_page() accomplish_search_data = search_data(cause, city, area, clinique, excel_time) """判断翻页后有没有找到""" if len(accomplish_search_data) == 0: """如果没找到存入列表""" download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """找到后点击""" accomplish_search_data[0].click() search_data_down(cause,clinique,path) else: download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """判断待处理里是否小于20条数据""" if 0 < number <= 20: """如果小于进行查找""" pending__search_data = search_data(cause, city, area, clinique, excel_time) """判断有没有找到""" if len(pending__search_data) == 0: """没找到""" """点击已完成""" accomplish() time.sleep(2) number_accmplish_1 = pagination() """判断已完成的下标是否为0""" if number_accmplish_1 == 0: """如果为0下载失败""" download_revers.append(clinique + "--" + cause + " 下载失败!") else: """不为0判断当前界面是否只有20条数据""" if 0 < number_accmplish_1 <= 20: """只有20条数据查找数据""" accomplish_search_data = search_data(cause, city, area, clinique, excel_time) if len(accomplish_search_data) == 0: """如果没找到结束""" download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """如果找到则点击""" accomplish_search_data[0].click() search_data_down(cause, clinique, path) elif 20 < number_accmplish_1 <= 40: """多于20条数据""" accomplish_search_data = search_data(cause, city, area, clinique, excel_time) """判断第一页有没有查到""" if len(accomplish_search_data) == 0: """如果没找到翻页""" tourne_page() accomplish_search_data = search_data(cause, city, area, clinique, excel_time) """判断翻页后有没有找到""" if len(accomplish_search_data) == 0: """如果没找到存入列表""" download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """找到后点击""" accomplish_search_data[0].click() search_data_down(cause, clinique, path) else: download_revers.append(clinique + "--" + cause + " 下载失败!") reset() else: """找到了""" pending__search_data[0].click() search_data_down(cause,clinique,path) # elif 20< number <= 40: # pending__search_data = search_data(cause, city, area, clinique, excel_time) # """判断有没有找到""" # if len(pending__search_data) == 0: if __name__ == "__main__": download_revers = [] """初始化""" url = input("请输入文件的绝对路径:") #文件路径 path = "D:\林钟\下载" # 下载路径 Chrome = r'D:\PYthon\webdrivers\chromedriver.exe' #驱动路径 time1 = time.time() """登录页面""" deconnexion(Chrome) print("已登陆") menu_lien() print("已跳转") """读取表格""" excel = vb.load_workbook(url) sheet = excel["1-每日监控告警明细"] subscript = 1 for i in sheet.iter_rows(min_row=2, max_row=101, max_col=1): for cell in i: if cell.value in ["3", 3, "高"]: """初始化数值""" cause = sheet["I" + str(cell.row)].value city = sheet["E" + str(cell.row)].value area = sheet["F" + str(cell.row)].value clinique = sheet["G" + str(cell.row)].value excel_time = sheet["D" + str(cell.row)].value """搜索""" try: confirm_area(city, area) confirm_tiem(excel_time) confirm_cause(cause) search() except: try: web.refresh() # 刷新方法 refresh print('刷新成功') confirm_area(city, area) confirm_tiem(excel_time) confirm_cause(cause) search() except Exception as e: print("刷新失败!", format(e)) """查找数据""" search_data_on(cause, city, area, clinique, excel_time, path) """打印最终结果""" print("") print("<-----------下面是下载失败的----------->") for i in download_revers: print(i) print("已全部下载完毕") time2 = time.time() print("用时:{:.2f} 秒".format(time2-time1))
normal
{ "blob_id": "d2c31d9c3cc66b43966cfd852582539d4e4bea17", "index": 321, "step-1": "<mask token>\n\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome)\n web.maximize_window()\n web.implicitly_wait(10)\n web.get(\n 'http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain'\n )\n actions = ActionChains(web)\n \"\"\"登录网页\"\"\"\n username = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input')\n password = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input')\n username.send_keys('15375429564')\n password.send_keys('cdc1234cdc')\n enter = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button')\n enter.click()\n return 0\n\n\ndef menu_lien():\n \"\"\"跳转页面\"\"\"\n enter_into = web.find_element_by_xpath(\n '/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article'\n )\n enter_into.click()\n return 0\n\n\ndef confirm_area(city, area):\n \"\"\"确定区域\"\"\"\n \"\"\"点击区域\"\"\"\n enter_area = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input'\n ).click()\n \"\"\"点击安徽省\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n except:\n time.sleep(1)\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n enter_AnHui = enter_AnHui_on.find_element_by_tag_name('li')\n enter_AnHui_down = enter_AnHui.find_element_by_class_name('el-radio__input'\n )\n web.execute_script('arguments[0].click();', enter_AnHui_down)\n \"\"\"选择城市\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n for i in range(len(enter_city)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n if enter_city[i].text == city:\n enter_city_down = enter_city[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_city_down)\n break\n \"\"\"选则区县\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n for i in range(len(enter_area)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n if enter_area[i].text == area:\n enter_area_down = enter_area[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_area_down)\n break\n return 0\n\n\ndef confirm_time_on(excel_time):\n if type(excel_time) == str:\n return str(excel_time)\n elif type(excel_time) == datetime.datetime:\n excel_time_2 = excel_time.strftime('%Y-%m-%d')\n return str(excel_time_2)\n\n\ndef confirm_tiem(time):\n \"\"\"确定时间\"\"\"\n time = confirm_time_on(time)\n enter_time = web.find_elements_by_class_name('el-range-input')\n for i in enter_time:\n i.send_keys(time)\n return 0\n\n\n<mask token>\n\n\ndef search():\n \"\"\"点击搜索\"\"\"\n enter_search = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/button[1]').click()\n return 0\n\n\ndef reset():\n \"\"\"点击重置\"\"\"\n enter_reset = web.find_element_by_xpath(\n '/html/body/div/section/main/div/div[3]/button[2]').click()\n return 0\n\n\n<mask token>\n\n\ndef resetting_excel(cause, clinique, path='D:\\\\林钟\\\\下载'):\n \"\"\"重命名病例\"\"\"\n try:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.rename(src, dst)\n except FileExistsError:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.remove(dst)\n os.rename(src, dst)\n return 0\n\n\ndef pagination():\n pagination__total = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/span[1]')\n a = int(pagination__total.text[2:-2])\n return a\n\n\n<mask token>\n\n\ndef tourne_page():\n enter_tourne_page = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/button[2]/i').click()\n return ''\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome)\n web.maximize_window()\n web.implicitly_wait(10)\n web.get(\n 'http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain'\n )\n actions = ActionChains(web)\n \"\"\"登录网页\"\"\"\n username = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input')\n password = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input')\n username.send_keys('15375429564')\n password.send_keys('cdc1234cdc')\n enter = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button')\n enter.click()\n return 0\n\n\ndef menu_lien():\n \"\"\"跳转页面\"\"\"\n enter_into = web.find_element_by_xpath(\n '/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article'\n )\n enter_into.click()\n return 0\n\n\ndef confirm_area(city, area):\n \"\"\"确定区域\"\"\"\n \"\"\"点击区域\"\"\"\n enter_area = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input'\n ).click()\n \"\"\"点击安徽省\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n except:\n time.sleep(1)\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n enter_AnHui = enter_AnHui_on.find_element_by_tag_name('li')\n enter_AnHui_down = enter_AnHui.find_element_by_class_name('el-radio__input'\n )\n web.execute_script('arguments[0].click();', enter_AnHui_down)\n \"\"\"选择城市\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n for i in range(len(enter_city)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n if enter_city[i].text == city:\n enter_city_down = enter_city[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_city_down)\n break\n \"\"\"选则区县\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n for i in range(len(enter_area)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n if enter_area[i].text == area:\n enter_area_down = enter_area[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_area_down)\n break\n return 0\n\n\ndef confirm_time_on(excel_time):\n if type(excel_time) == str:\n return str(excel_time)\n elif type(excel_time) == datetime.datetime:\n excel_time_2 = excel_time.strftime('%Y-%m-%d')\n return str(excel_time_2)\n\n\ndef confirm_tiem(time):\n \"\"\"确定时间\"\"\"\n time = confirm_time_on(time)\n enter_time = web.find_elements_by_class_name('el-range-input')\n for i in enter_time:\n i.send_keys(time)\n return 0\n\n\n<mask token>\n\n\ndef search():\n \"\"\"点击搜索\"\"\"\n enter_search = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/button[1]').click()\n return 0\n\n\ndef reset():\n \"\"\"点击重置\"\"\"\n enter_reset = web.find_element_by_xpath(\n '/html/body/div/section/main/div/div[3]/button[2]').click()\n return 0\n\n\n<mask token>\n\n\ndef download_cas():\n \"\"\"下载病例\"\"\"\n enter_download_cas = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/ul/li[2]').click()\n enter_download_cas_1 = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/div/div[2]/div/div[1]/div/button[3]'\n ).click()\n return 0\n\n\ndef resetting_excel(cause, clinique, path='D:\\\\林钟\\\\下载'):\n \"\"\"重命名病例\"\"\"\n try:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.rename(src, dst)\n except FileExistsError:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.remove(dst)\n os.rename(src, dst)\n return 0\n\n\ndef pagination():\n pagination__total = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/span[1]')\n a = int(pagination__total.text[2:-2])\n return a\n\n\ndef search_data(cause, city, area, clinique, excel_time):\n \"\"\"查找数据\"\"\"\n ls_2 = []\n trlist_table_on = web.find_element_by_class_name('is-scrolling-none')\n trlist_table = trlist_table_on.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n for row in range(len(trlist_tr)):\n trlist_table = web.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n i = 0\n j = 0\n ls = []\n for col in range(len(trlist_td)):\n i += 1\n if i == 2:\n ls.append(trlist_td[col].text)\n elif i == 3:\n ls.append(trlist_td[col].text)\n elif i == 7:\n ls.append(trlist_td[col])\n elif i == 9:\n j = 1\n ls.append(trlist_td[col])\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n if ls[0] == cause:\n if ls[1] == '安徽省/' + city + '/' + area + '/' + clinique:\n if j == 0:\n ls_2.append(ls[2])\n elif j == 1:\n ls_2.append(ls[3])\n return ls_2\n\n\ndef search_data_down(cause, clinique, path):\n \"\"\"找到病例后的对病例进行一系列的处理\"\"\"\n \"\"\"下载病例\"\"\"\n download_cas()\n \"\"\"返回上一界面\"\"\"\n web.back()\n \"\"\"点击重置\"\"\"\n reset()\n \"\"\"点击待完成\"\"\"\n pending()\n \"\"\"给病例重命名\"\"\"\n time.sleep(2)\n try:\n resetting_excel(cause, clinique, path)\n except FileNotFoundError:\n time.sleep(2)\n resetting_excel(cause, clinique, path)\n print(clinique + '--' + cause + '已下载完成!')\n\n\ndef tourne_page():\n enter_tourne_page = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/button[2]/i').click()\n return ''\n\n\ndef search_data_on(cause, city, area, clinique, excel_time, path):\n \"\"\"核心处理流程\"\"\"\n time.sleep(2)\n number = pagination()\n \"\"\"判断待处理下标是否为0\"\"\"\n if number == 0:\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"判断待处理里是否小于20条数据\"\"\"\n if 0 < number <= 20:\n \"\"\"如果小于进行查找\"\"\"\n pending__search_data = search_data(cause, city, area, clinique,\n excel_time)\n \"\"\"判断有没有找到\"\"\"\n if len(pending__search_data) == 0:\n \"\"\"没找到\"\"\"\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause,\n city, area, clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' +\n cause + ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到了\"\"\"\n pending__search_data[0].click()\n search_data_down(cause, clinique, path)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome)\n web.maximize_window()\n web.implicitly_wait(10)\n web.get(\n 'http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain'\n )\n actions = ActionChains(web)\n \"\"\"登录网页\"\"\"\n username = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input')\n password = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input')\n username.send_keys('15375429564')\n password.send_keys('cdc1234cdc')\n enter = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button')\n enter.click()\n return 0\n\n\ndef menu_lien():\n \"\"\"跳转页面\"\"\"\n enter_into = web.find_element_by_xpath(\n '/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article'\n )\n enter_into.click()\n return 0\n\n\ndef confirm_area(city, area):\n \"\"\"确定区域\"\"\"\n \"\"\"点击区域\"\"\"\n enter_area = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input'\n ).click()\n \"\"\"点击安徽省\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n except:\n time.sleep(1)\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n enter_AnHui = enter_AnHui_on.find_element_by_tag_name('li')\n enter_AnHui_down = enter_AnHui.find_element_by_class_name('el-radio__input'\n )\n web.execute_script('arguments[0].click();', enter_AnHui_down)\n \"\"\"选择城市\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n for i in range(len(enter_city)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n if enter_city[i].text == city:\n enter_city_down = enter_city[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_city_down)\n break\n \"\"\"选则区县\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n for i in range(len(enter_area)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n if enter_area[i].text == area:\n enter_area_down = enter_area[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_area_down)\n break\n return 0\n\n\ndef confirm_time_on(excel_time):\n if type(excel_time) == str:\n return str(excel_time)\n elif type(excel_time) == datetime.datetime:\n excel_time_2 = excel_time.strftime('%Y-%m-%d')\n return str(excel_time_2)\n\n\ndef confirm_tiem(time):\n \"\"\"确定时间\"\"\"\n time = confirm_time_on(time)\n enter_time = web.find_elements_by_class_name('el-range-input')\n for i in enter_time:\n i.send_keys(time)\n return 0\n\n\ndef confirm_cause(cause):\n \"\"\"选则症状\"\"\"\n enter_symptom = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[3]/span/div/div[2]/input'\n ).click()\n enter_on = web.find_element_by_class_name('is-multiple')\n enter_on_1 = enter_on.find_element_by_class_name('el-scrollbar')\n enter_on_symptom = enter_on_1.find_elements_by_tag_name('li')\n for i in range(len(enter_on_symptom)):\n enter_on = web.find_element_by_class_name('is-multiple')\n enter_on_symptom = enter_on.find_elements_by_tag_name('li')\n if enter_on_symptom[i].text == cause:\n enter_on_symptom[i].click()\n break\n return 0\n\n\ndef search():\n \"\"\"点击搜索\"\"\"\n enter_search = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/button[1]').click()\n return 0\n\n\ndef reset():\n \"\"\"点击重置\"\"\"\n enter_reset = web.find_element_by_xpath(\n '/html/body/div/section/main/div/div[3]/button[2]').click()\n return 0\n\n\ndef pending():\n \"\"\"待处理\"\"\"\n enter_pending = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[1]'\n ).click()\n return 0\n\n\n<mask token>\n\n\ndef download_cas():\n \"\"\"下载病例\"\"\"\n enter_download_cas = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/ul/li[2]').click()\n enter_download_cas_1 = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/div/div[2]/div/div[1]/div/button[3]'\n ).click()\n return 0\n\n\ndef resetting_excel(cause, clinique, path='D:\\\\林钟\\\\下载'):\n \"\"\"重命名病例\"\"\"\n try:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.rename(src, dst)\n except FileExistsError:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.remove(dst)\n os.rename(src, dst)\n return 0\n\n\ndef pagination():\n pagination__total = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/span[1]')\n a = int(pagination__total.text[2:-2])\n return a\n\n\ndef search_data(cause, city, area, clinique, excel_time):\n \"\"\"查找数据\"\"\"\n ls_2 = []\n trlist_table_on = web.find_element_by_class_name('is-scrolling-none')\n trlist_table = trlist_table_on.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n for row in range(len(trlist_tr)):\n trlist_table = web.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n i = 0\n j = 0\n ls = []\n for col in range(len(trlist_td)):\n i += 1\n if i == 2:\n ls.append(trlist_td[col].text)\n elif i == 3:\n ls.append(trlist_td[col].text)\n elif i == 7:\n ls.append(trlist_td[col])\n elif i == 9:\n j = 1\n ls.append(trlist_td[col])\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n if ls[0] == cause:\n if ls[1] == '安徽省/' + city + '/' + area + '/' + clinique:\n if j == 0:\n ls_2.append(ls[2])\n elif j == 1:\n ls_2.append(ls[3])\n return ls_2\n\n\ndef search_data_down(cause, clinique, path):\n \"\"\"找到病例后的对病例进行一系列的处理\"\"\"\n \"\"\"下载病例\"\"\"\n download_cas()\n \"\"\"返回上一界面\"\"\"\n web.back()\n \"\"\"点击重置\"\"\"\n reset()\n \"\"\"点击待完成\"\"\"\n pending()\n \"\"\"给病例重命名\"\"\"\n time.sleep(2)\n try:\n resetting_excel(cause, clinique, path)\n except FileNotFoundError:\n time.sleep(2)\n resetting_excel(cause, clinique, path)\n print(clinique + '--' + cause + '已下载完成!')\n\n\ndef tourne_page():\n enter_tourne_page = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/button[2]/i').click()\n return ''\n\n\ndef search_data_on(cause, city, area, clinique, excel_time, path):\n \"\"\"核心处理流程\"\"\"\n time.sleep(2)\n number = pagination()\n \"\"\"判断待处理下标是否为0\"\"\"\n if number == 0:\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"判断待处理里是否小于20条数据\"\"\"\n if 0 < number <= 20:\n \"\"\"如果小于进行查找\"\"\"\n pending__search_data = search_data(cause, city, area, clinique,\n excel_time)\n \"\"\"判断有没有找到\"\"\"\n if len(pending__search_data) == 0:\n \"\"\"没找到\"\"\"\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause,\n city, area, clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' +\n cause + ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到了\"\"\"\n pending__search_data[0].click()\n search_data_down(cause, clinique, path)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome)\n web.maximize_window()\n web.implicitly_wait(10)\n web.get(\n 'http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain'\n )\n actions = ActionChains(web)\n \"\"\"登录网页\"\"\"\n username = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input')\n password = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input')\n username.send_keys('15375429564')\n password.send_keys('cdc1234cdc')\n enter = web.find_element_by_xpath(\n '/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button')\n enter.click()\n return 0\n\n\ndef menu_lien():\n \"\"\"跳转页面\"\"\"\n enter_into = web.find_element_by_xpath(\n '/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article'\n )\n enter_into.click()\n return 0\n\n\ndef confirm_area(city, area):\n \"\"\"确定区域\"\"\"\n \"\"\"点击区域\"\"\"\n enter_area = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input'\n ).click()\n \"\"\"点击安徽省\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n except:\n time.sleep(1)\n enter_AnHui_on_on = enter_on.find_elements_by_class_name('el-scrollbar'\n )\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\n 'el-scrollbar__view')\n enter_AnHui = enter_AnHui_on.find_element_by_tag_name('li')\n enter_AnHui_down = enter_AnHui.find_element_by_class_name('el-radio__input'\n )\n web.execute_script('arguments[0].click();', enter_AnHui_down)\n \"\"\"选择城市\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n for i in range(len(enter_city)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_city_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_city = enter_city_on.find_elements_by_tag_name('li')\n if enter_city[i].text == city:\n enter_city_down = enter_city[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_city_down)\n break\n \"\"\"选则区县\"\"\"\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n try:\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n except:\n time.sleep(1)\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n for i in range(len(enter_area)):\n enter_on_on = web.find_element_by_class_name('el-cascader__dropdown')\n enter_on = enter_on_on.find_element_by_class_name('el-cascader-panel')\n enter_area_on_on = enter_on.find_elements_by_class_name('el-scrollbar')\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\n 'el-cascader-menu__wrap')\n enter_area = enter_area_on.find_elements_by_tag_name('li')\n if enter_area[i].text == area:\n enter_area_down = enter_area[i].find_element_by_class_name(\n 'el-radio__input')\n web.execute_script('arguments[0].click();', enter_area_down)\n break\n return 0\n\n\ndef confirm_time_on(excel_time):\n if type(excel_time) == str:\n return str(excel_time)\n elif type(excel_time) == datetime.datetime:\n excel_time_2 = excel_time.strftime('%Y-%m-%d')\n return str(excel_time_2)\n\n\ndef confirm_tiem(time):\n \"\"\"确定时间\"\"\"\n time = confirm_time_on(time)\n enter_time = web.find_elements_by_class_name('el-range-input')\n for i in enter_time:\n i.send_keys(time)\n return 0\n\n\ndef confirm_cause(cause):\n \"\"\"选则症状\"\"\"\n enter_symptom = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/div[3]/span/div/div[2]/input'\n ).click()\n enter_on = web.find_element_by_class_name('is-multiple')\n enter_on_1 = enter_on.find_element_by_class_name('el-scrollbar')\n enter_on_symptom = enter_on_1.find_elements_by_tag_name('li')\n for i in range(len(enter_on_symptom)):\n enter_on = web.find_element_by_class_name('is-multiple')\n enter_on_symptom = enter_on.find_elements_by_tag_name('li')\n if enter_on_symptom[i].text == cause:\n enter_on_symptom[i].click()\n break\n return 0\n\n\ndef search():\n \"\"\"点击搜索\"\"\"\n enter_search = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[3]/button[1]').click()\n return 0\n\n\ndef reset():\n \"\"\"点击重置\"\"\"\n enter_reset = web.find_element_by_xpath(\n '/html/body/div/section/main/div/div[3]/button[2]').click()\n return 0\n\n\ndef pending():\n \"\"\"待处理\"\"\"\n enter_pending = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[1]'\n ).click()\n return 0\n\n\ndef accomplish():\n \"\"\"已完成\"\"\"\n enter__accomplish = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[3]'\n ).click()\n return 0\n\n\ndef download_cas():\n \"\"\"下载病例\"\"\"\n enter_download_cas = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/ul/li[2]').click()\n enter_download_cas_1 = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/section/main/div[2]/div/div[2]/div/div[1]/div/button[3]'\n ).click()\n return 0\n\n\ndef resetting_excel(cause, clinique, path='D:\\\\林钟\\\\下载'):\n \"\"\"重命名病例\"\"\"\n try:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.rename(src, dst)\n except FileExistsError:\n files = os.listdir(path)\n src = path + '\\\\' + '外呼结果导出表格.xlsx'\n if cause == '发热伴畏寒|寒战':\n cause = \"发热伴畏寒寒战'\"\n if cause == '畏寒|寒战':\n cause = \"畏寒寒战'\"\n dst = path + '\\\\' + clinique + '--' + cause + '.xlsx'\n os.remove(dst)\n os.rename(src, dst)\n return 0\n\n\ndef pagination():\n pagination__total = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/span[1]')\n a = int(pagination__total.text[2:-2])\n return a\n\n\ndef search_data(cause, city, area, clinique, excel_time):\n \"\"\"查找数据\"\"\"\n ls_2 = []\n trlist_table_on = web.find_element_by_class_name('is-scrolling-none')\n trlist_table = trlist_table_on.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n for row in range(len(trlist_tr)):\n trlist_table = web.find_element_by_class_name('el-table__body')\n trlist_tr = trlist_table.find_elements_by_tag_name('tr')\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n i = 0\n j = 0\n ls = []\n for col in range(len(trlist_td)):\n i += 1\n if i == 2:\n ls.append(trlist_td[col].text)\n elif i == 3:\n ls.append(trlist_td[col].text)\n elif i == 7:\n ls.append(trlist_td[col])\n elif i == 9:\n j = 1\n ls.append(trlist_td[col])\n trlist_td = trlist_tr[row].find_elements_by_tag_name('td')\n if ls[0] == cause:\n if ls[1] == '安徽省/' + city + '/' + area + '/' + clinique:\n if j == 0:\n ls_2.append(ls[2])\n elif j == 1:\n ls_2.append(ls[3])\n return ls_2\n\n\ndef search_data_down(cause, clinique, path):\n \"\"\"找到病例后的对病例进行一系列的处理\"\"\"\n \"\"\"下载病例\"\"\"\n download_cas()\n \"\"\"返回上一界面\"\"\"\n web.back()\n \"\"\"点击重置\"\"\"\n reset()\n \"\"\"点击待完成\"\"\"\n pending()\n \"\"\"给病例重命名\"\"\"\n time.sleep(2)\n try:\n resetting_excel(cause, clinique, path)\n except FileNotFoundError:\n time.sleep(2)\n resetting_excel(cause, clinique, path)\n print(clinique + '--' + cause + '已下载完成!')\n\n\ndef tourne_page():\n enter_tourne_page = web.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/div[5]/button[2]/i').click()\n return ''\n\n\ndef search_data_on(cause, city, area, clinique, excel_time, path):\n \"\"\"核心处理流程\"\"\"\n time.sleep(2)\n number = pagination()\n \"\"\"判断待处理下标是否为0\"\"\"\n if number == 0:\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause, city, area,\n clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n reset()\n else:\n \"\"\"判断待处理里是否小于20条数据\"\"\"\n if 0 < number <= 20:\n \"\"\"如果小于进行查找\"\"\"\n pending__search_data = search_data(cause, city, area, clinique,\n excel_time)\n \"\"\"判断有没有找到\"\"\"\n if len(pending__search_data) == 0:\n \"\"\"没找到\"\"\"\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + '--' + cause + ' 下载失败!')\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city,\n area, clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause,\n city, area, clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + '--' +\n cause + ' 下载失败!')\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + '--' + cause +\n ' 下载失败!')\n reset()\n else:\n \"\"\"找到了\"\"\"\n pending__search_data[0].click()\n search_data_down(cause, clinique, path)\n\n\nif __name__ == '__main__':\n download_revers = []\n \"\"\"初始化\"\"\"\n url = input('请输入文件的绝对路径:')\n path = 'D:\\\\林钟\\\\下载'\n Chrome = 'D:\\\\PYthon\\\\webdrivers\\\\chromedriver.exe'\n time1 = time.time()\n \"\"\"登录页面\"\"\"\n deconnexion(Chrome)\n print('已登陆')\n menu_lien()\n print('已跳转')\n \"\"\"读取表格\"\"\"\n excel = vb.load_workbook(url)\n sheet = excel['1-每日监控告警明细']\n subscript = 1\n for i in sheet.iter_rows(min_row=2, max_row=101, max_col=1):\n for cell in i:\n if cell.value in ['3', 3, '高']:\n \"\"\"初始化数值\"\"\"\n cause = sheet['I' + str(cell.row)].value\n city = sheet['E' + str(cell.row)].value\n area = sheet['F' + str(cell.row)].value\n clinique = sheet['G' + str(cell.row)].value\n excel_time = sheet['D' + str(cell.row)].value\n \"\"\"搜索\"\"\"\n try:\n confirm_area(city, area)\n confirm_tiem(excel_time)\n confirm_cause(cause)\n search()\n except:\n try:\n web.refresh()\n print('刷新成功')\n confirm_area(city, area)\n confirm_tiem(excel_time)\n confirm_cause(cause)\n search()\n except Exception as e:\n print('刷新失败!', format(e))\n \"\"\"查找数据\"\"\"\n search_data_on(cause, city, area, clinique, excel_time, path)\n \"\"\"打印最终结果\"\"\"\n print('')\n print('<-----------下面是下载失败的----------->')\n for i in download_revers:\n print(i)\n print('已全部下载完毕')\n time2 = time.time()\n print('用时:{:.2f} 秒'.format(time2 - time1))\n", "step-5": "from selenium import webdriver\nimport time\nimport datetime\nimport os\nimport openpyxl as vb\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome) #公司电脑\n # web = webdriver.Chrome(r'D:\\python\\webdrivers\\chromedriver.exe') #自己的电脑\n web.maximize_window()\n web.implicitly_wait(10) # 最大运行时间不超过10秒\n web.get('http://www.wjw-cdc.com:8003/user-center-portal/login?redirect=%2Fmain')\n actions = ActionChains(web)\n\n \"\"\"登录网页\"\"\"\n username = web.find_element_by_xpath('/html/body/div/div/div[1]/div/div[2]/form/div[1]/div/div[1]/input') # 获得账号和密码\n password = web.find_element_by_xpath('/html/body/div/div/div[1]/div/div[2]/form/div[2]/div/div[2]/input')\n username.send_keys('15375429564')\n password.send_keys(\"cdc1234cdc\")\n enter = web.find_element_by_xpath(\"/html/body/div/div/div[1]/div/div[2]/form/div[3]/div/button\")\n enter.click()\n return 0\ndef menu_lien():\n \"\"\"跳转页面\"\"\"\n enter_into = web.find_element_by_xpath(\n \"/html/body/div[1]/div/div[2]/section/div/div[1]/ul/li[1]/ul/li[2]/span/div[2]/section/article\")\n enter_into.click()\n return 0\ndef confirm_area(city, area):\n \"\"\"确定区域\"\"\"\n \"\"\"点击区域\"\"\"\n enter_area = web.find_element_by_xpath(\"/html/body/div[1]/section/main/div/div[3]/div[1]/span/div/div[1]/input\").click()\n \"\"\"点击安徽省\"\"\"\n enter_on_on = web.find_element_by_class_name(\"el-cascader__dropdown\")\n enter_on = enter_on_on.find_element_by_class_name(\"el-cascader-panel\")\n try:\n enter_AnHui_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_AnHui_on =enter_AnHui_on_on[0].find_element_by_class_name(\"el-scrollbar__view\")\n except:\n time.sleep(1)\n enter_AnHui_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_AnHui_on = enter_AnHui_on_on[0].find_element_by_class_name(\"el-scrollbar__view\")\n enter_AnHui = enter_AnHui_on.find_element_by_tag_name(\"li\")\n enter_AnHui_down =enter_AnHui.find_element_by_class_name(\"el-radio__input\")\n web.execute_script(\"arguments[0].click();\", enter_AnHui_down)\n \"\"\"选择城市\"\"\"\n enter_on_on = web.find_element_by_class_name(\"el-cascader__dropdown\")\n enter_on = enter_on_on.find_element_by_class_name(\"el-cascader-panel\")\n try:\n enter_city_on_on =enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\"el-cascader-menu__wrap\")\n except:\n time.sleep(1)\n enter_city_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\"el-cascader-menu__wrap\")\n enter_city = enter_city_on.find_elements_by_tag_name(\"li\")\n for i in range(len(enter_city)):\n enter_on_on = web.find_element_by_class_name(\"el-cascader__dropdown\")\n enter_on = enter_on_on.find_element_by_class_name(\"el-cascader-panel\")\n enter_city_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_city_on = enter_city_on_on[1].find_element_by_class_name(\"el-cascader-menu__wrap\")\n enter_city = enter_city_on.find_elements_by_tag_name(\"li\")\n if enter_city[i].text ==city:\n enter_city_down = enter_city[i].find_element_by_class_name(\"el-radio__input\")\n web.execute_script(\"arguments[0].click();\", enter_city_down)\n break\n \"\"\"选则区县\"\"\"\n enter_on_on = web.find_element_by_class_name(\"el-cascader__dropdown\")\n enter_on = enter_on_on.find_element_by_class_name(\"el-cascader-panel\")\n try:\n enter_area_on_on =enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\"el-cascader-menu__wrap\")\n except:\n time.sleep(1)\n enter_area_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\"el-cascader-menu__wrap\")\n enter_area = enter_area_on.find_elements_by_tag_name(\"li\")\n for i in range(len(enter_area)):\n enter_on_on = web.find_element_by_class_name(\"el-cascader__dropdown\")\n enter_on = enter_on_on.find_element_by_class_name(\"el-cascader-panel\")\n enter_area_on_on = enter_on.find_elements_by_class_name(\"el-scrollbar\")\n enter_area_on = enter_area_on_on[2].find_element_by_class_name(\"el-cascader-menu__wrap\")\n enter_area = enter_area_on.find_elements_by_tag_name(\"li\")\n if enter_area[i].text ==area:\n enter_area_down = enter_area[i].find_element_by_class_name(\"el-radio__input\")\n web.execute_script(\"arguments[0].click();\", enter_area_down)\n break\n\n return 0\ndef confirm_time_on(excel_time):\n if type(excel_time) == str:\n return str(excel_time)\n elif type(excel_time) == datetime.datetime:\n excel_time_2 = excel_time.strftime('%Y-%m-%d')\n return str(excel_time_2)\ndef confirm_tiem(time):\n \"\"\"确定时间\"\"\"\n time =confirm_time_on(time)\n enter_time = web.find_elements_by_class_name(\"el-range-input\")\n for i in enter_time:\n i.send_keys(time)\n return 0\ndef confirm_cause(cause):\n \"\"\"选则症状\"\"\"\n enter_symptom = web.find_element_by_xpath(\"/html/body/div[1]/section/main/div/div[3]/div[3]/span/div/div[2]/input\").click()\n enter_on = web.find_element_by_class_name(\"is-multiple\")\n enter_on_1 =enter_on.find_element_by_class_name(\"el-scrollbar\")\n enter_on_symptom = enter_on_1.find_elements_by_tag_name(\"li\")\n for i in range(len(enter_on_symptom)):\n enter_on = web.find_element_by_class_name(\"is-multiple\")\n enter_on_symptom = enter_on.find_elements_by_tag_name(\"li\")\n if enter_on_symptom[i].text == cause:\n enter_on_symptom[i].click()\n break\n return 0\ndef search():\n \"\"\"点击搜索\"\"\"\n enter_search = web.find_element_by_xpath(\"/html/body/div[1]/section/main/div/div[3]/button[1]\").click()\n return 0\ndef reset():\n \"\"\"点击重置\"\"\"\n enter_reset = web.find_element_by_xpath(\"/html/body/div/section/main/div/div[3]/button[2]\").click()\n return 0\ndef pending():\n \"\"\"待处理\"\"\"\n enter_pending = web.find_element_by_xpath(\n \"/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[1]\").click()\n return 0\ndef accomplish():\n \"\"\"已完成\"\"\"\n enter__accomplish = web.find_element_by_xpath(\n \"/html/body/div[1]/section/main/div/div[4]/div/div[1]/div/div/div/div[3]\").click()\n return 0\ndef download_cas():\n \"\"\"下载病例\"\"\"\n enter_download_cas = web.find_element_by_xpath(\n \"/html/body/div[1]/section/main/section/main/div[2]/ul/li[2]\").click()\n enter_download_cas_1 = web.find_element_by_xpath(\n \"/html/body/div[1]/section/main/section/main/div[2]/div/div[2]/div/div[1]/div/button[3]\").click()\n return 0\ndef resetting_excel(cause, clinique, path=\"D:\\林钟\\下载\"):\n \"\"\"重命名病例\"\"\"\n try:\n files = os.listdir(path)\n src = path + \"\\\\\" + \"外呼结果导出表格.xlsx\"\n if cause ==\"发热伴畏寒|寒战\":\n cause =\"发热伴畏寒寒战'\"\n if cause == \"畏寒|寒战\":\n cause = \"畏寒寒战'\"\n dst = path + \"\\\\\" + clinique + \"--\" + cause + \".xlsx\"\n os.rename(src, dst)\n except (FileExistsError):\n files = os.listdir(path)\n src = path + \"\\\\\" + \"外呼结果导出表格.xlsx\"\n if cause ==\"发热伴畏寒|寒战\":\n cause =\"发热伴畏寒寒战'\"\n if cause == \"畏寒|寒战\":\n cause = \"畏寒寒战'\"\n dst = path + \"\\\\\" + clinique + \"--\" + cause + \".xlsx\"\n os.remove(dst)\n os.rename(src, dst)\n\n return 0\ndef pagination(): #获取当前界面一共有多少条数据\n pagination__total = web.find_element_by_xpath(\"/html/body/div[1]/section/main/div/div[5]/span[1]\")\n a = int(pagination__total.text[2:-2])\n return a\ndef search_data(cause, city, area, clinique, excel_time):\n \"\"\"查找数据\"\"\"\n ls_2 =[] #存储最终点击的元素,如果为空则说明没找到。\n trlist_table_on = web.find_element_by_class_name(\"is-scrolling-none\")\n trlist_table = trlist_table_on.find_element_by_class_name(\"el-table__body\")\n trlist_tr = trlist_table.find_elements_by_tag_name(\"tr\")\n for row in range(len(trlist_tr)):\n trlist_table = web.find_element_by_class_name(\"el-table__body\")\n trlist_tr = trlist_table.find_elements_by_tag_name(\"tr\")\n trlist_td = trlist_tr[row].find_elements_by_tag_name(\"td\")\n i = 0\n j = 0\n ls = []\n for col in range(len(trlist_td)):\n i += 1\n if i == 2:\n ls.append(trlist_td[col].text)\n elif i == 3:\n ls.append(trlist_td[col].text)\n elif i == 7:\n ls.append(trlist_td[col])\n elif i == 9:\n j = 1\n ls.append((trlist_td[col]))\n trlist_td = trlist_tr[row].find_elements_by_tag_name(\"td\")\n if ls[0] == cause:\n if ls[1] == (\"安徽省/\" + city + \"/\" + area + \"/\" + clinique):\n if j == 0:\n # ls[2].click()\n ls_2.append(ls[2])\n elif j == 1:\n # ls[3].click()\n ls_2.append(ls[3])\n return ls_2\ndef search_data_down(cause,clinique,path):\n \"\"\"找到病例后的对病例进行一系列的处理\"\"\"\n \"\"\"下载病例\"\"\"\n download_cas()\n \"\"\"返回上一界面\"\"\"\n web.back()\n \"\"\"点击重置\"\"\"\n reset()\n \"\"\"点击待完成\"\"\"\n pending()\n \"\"\"给病例重命名\"\"\"\n time.sleep(2)\n try:\n resetting_excel(cause, clinique,path)\n except FileNotFoundError:\n time.sleep(2)\n resetting_excel(cause, clinique,path)\n print(clinique + \"--\" + cause + \"已下载完成!\")\ndef tourne_page():\n enter_tourne_page =web.find_element_by_xpath(\"/html/body/div[1]/section/main/div/div[5]/button[2]/i\").click()\n return \"\"\ndef search_data_on(cause, city, area, clinique, excel_time,path):\n \"\"\"核心处理流程\"\"\"\n time.sleep(2)\n number = pagination()\n \"\"\"判断待处理下标是否为0\"\"\"\n if number == 0 :\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause,clinique,path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause,clinique,path)\n else:\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"判断待处理里是否小于20条数据\"\"\"\n if 0 < number <= 20:\n \"\"\"如果小于进行查找\"\"\"\n pending__search_data = search_data(cause, city, area, clinique, excel_time)\n \"\"\"判断有没有找到\"\"\"\n if len(pending__search_data) == 0:\n \"\"\"没找到\"\"\"\n \"\"\"点击已完成\"\"\"\n accomplish()\n time.sleep(2)\n number_accmplish_1 = pagination()\n \"\"\"判断已完成的下标是否为0\"\"\"\n if number_accmplish_1 == 0:\n \"\"\"如果为0下载失败\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n else:\n \"\"\"不为0判断当前界面是否只有20条数据\"\"\"\n if 0 < number_accmplish_1 <= 20:\n \"\"\"只有20条数据查找数据\"\"\"\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到结束\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"如果找到则点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n elif 20 < number_accmplish_1 <= 40:\n \"\"\"多于20条数据\"\"\"\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n \"\"\"判断第一页有没有查到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到翻页\"\"\"\n tourne_page()\n accomplish_search_data = search_data(cause, city, area, clinique, excel_time)\n \"\"\"判断翻页后有没有找到\"\"\"\n if len(accomplish_search_data) == 0:\n \"\"\"如果没找到存入列表\"\"\"\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"找到后点击\"\"\"\n accomplish_search_data[0].click()\n search_data_down(cause, clinique, path)\n else:\n download_revers.append(clinique + \"--\" + cause + \" 下载失败!\")\n reset()\n else:\n \"\"\"找到了\"\"\"\n pending__search_data[0].click()\n search_data_down(cause,clinique,path)\n\n # elif 20< number <= 40:\n # pending__search_data = search_data(cause, city, area, clinique, excel_time)\n # \"\"\"判断有没有找到\"\"\"\n # if len(pending__search_data) == 0:\n\n\nif __name__ == \"__main__\":\n\n download_revers = []\n \"\"\"初始化\"\"\"\n url = input(\"请输入文件的绝对路径:\") #文件路径\n path = \"D:\\林钟\\下载\" # 下载路径\n Chrome = r'D:\\PYthon\\webdrivers\\chromedriver.exe' #驱动路径\n time1 = time.time()\n \"\"\"登录页面\"\"\"\n deconnexion(Chrome)\n print(\"已登陆\")\n menu_lien()\n print(\"已跳转\")\n\n \"\"\"读取表格\"\"\"\n excel = vb.load_workbook(url)\n sheet = excel[\"1-每日监控告警明细\"]\n subscript = 1\n for i in sheet.iter_rows(min_row=2, max_row=101, max_col=1):\n for cell in i:\n if cell.value in [\"3\", 3, \"高\"]:\n\n \"\"\"初始化数值\"\"\"\n cause = sheet[\"I\" + str(cell.row)].value\n city = sheet[\"E\" + str(cell.row)].value\n area = sheet[\"F\" + str(cell.row)].value\n clinique = sheet[\"G\" + str(cell.row)].value\n excel_time = sheet[\"D\" + str(cell.row)].value\n\n \"\"\"搜索\"\"\"\n try:\n confirm_area(city, area)\n confirm_tiem(excel_time)\n confirm_cause(cause)\n search()\n except:\n try:\n web.refresh() # 刷新方法 refresh\n print('刷新成功')\n confirm_area(city, area)\n confirm_tiem(excel_time)\n confirm_cause(cause)\n search()\n except Exception as e:\n print(\"刷新失败!\", format(e))\n\n\n \"\"\"查找数据\"\"\"\n search_data_on(cause, city, area, clinique, excel_time, path)\n\n\n \"\"\"打印最终结果\"\"\"\n print(\"\")\n print(\"<-----------下面是下载失败的----------->\")\n for i in download_revers:\n print(i)\n print(\"已全部下载完毕\")\n time2 = time.time()\n print(\"用时:{:.2f} 秒\".format(time2-time1))", "step-ids": [ 10, 14, 16, 18, 20 ] }
[ 10, 14, 16, 18, 20 ]
# 내 풀이 with open("sequence.protein.2.fasta", "w") as fw: with open("sequence.protein.fasta", "r") as fr: for line in fr: fw.write(line) # 강사님 풀이 # fr = open('sequence.protein.fasta','r'): # lines=fr.readlines() # seq_list=list() # for line in lines:
normal
{ "blob_id": "84fb0e364ee3cd846148abfc9326f404f008c510", "index": 7908, "step-1": "<mask token>\n", "step-2": "with open('sequence.protein.2.fasta', 'w') as fw:\n with open('sequence.protein.fasta', 'r') as fr:\n for line in fr:\n fw.write(line)\n", "step-3": "# 내 풀이\nwith open(\"sequence.protein.2.fasta\", \"w\") as fw:\n with open(\"sequence.protein.fasta\", \"r\") as fr:\n for line in fr:\n fw.write(line)\n\n# 강사님 풀이\n# fr = open('sequence.protein.fasta','r'):\n# lines=fr.readlines()\n# seq_list=list()\n# for line in lines:\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
my_dict = {'one': '1', 'two': '2'} for key in my_dict: print('{} - {}'.format(key, my_dict[key]))
normal
{ "blob_id": "1d524312cbd3b735850046131f31c03fdfa90bbc", "index": 483, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor key in my_dict:\n print('{} - {}'.format(key, my_dict[key]))\n", "step-3": "my_dict = {'one': '1', 'two': '2'}\nfor key in my_dict:\n print('{} - {}'.format(key, my_dict[key]))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from PIL import Image from random import randrange class PileMosaic: def __init__(self): self.width, self.height = 2380, 2800 self.filename = "pile_mosaic.png" self.crema = (240, 233, 227) self.choco = (89, 62, 53) self.luna = (43, 97, 123) self.latte = (195, 175, 148) self.piscina = (170, 200, 211) self.lavanda = (189, 192, 209) self.viola = (133, 108, 140) self.morado = (121, 69, 92) self.rosa = (222, 179, 172) self.flamingo = (238, 157, 140) self.color_tuple = (self.crema, self.choco, self.luna, self.latte, self.piscina) # self.color_tuple = (self.lavanda, self.viola, self.rosa, self.morado, self.flamingo) self.tile_width = 300 self.tile_height = 100 def create_new_image(self): self.image = Image.new("RGB", (self.width, self.height), "white") self.data = [(255, 255, 255)]*(self.width*self.height) def write_image(self): self.image.save(self.filename, "PNG") def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) def rgb_to_hex(rgb): return '#%02x%02x%02x' % rgb def place_pile(self, color, x=0, y=0): for i in range(self.tile_width): for j in range(self.tile_height): self.image.im.putpixel((x + i, y + j), color) def fill_random(self): for x in range(self.width / self.tile_width): for y in range(self.height / self.tile_height): current_color = randrange(5) self.place_pile(self.color_tuple[current_color], x=x*self.tile_width, y=y*self.tile_height) def create_random_pattern(self): initial_pattern = [] for x in range(self.width / self.tile_width): initial_pattern.append([]) for y in range(self.height / self.tile_height): temp_list = list(self.color_tuple) if x - 1 >= 0: try: temp_list.remove(initial_pattern[x - 1][y]) except ValueError: pass if y - 1 >= 0: try: temp_list.remove(initial_pattern[x][y - 1]) except ValueError: pass initial_pattern[x].append(temp_list[randrange(len(temp_list))]) return initial_pattern def fill(self, pattern): for x in range(self.width / (self.tile_width + 4)): for y in range(self.height / (self.tile_height + 4)): self.place_pile(pattern[x][y], x=x*(self.tile_width+4), y=y*(self.tile_height+4)) pile = PileMosaic() pile.create_new_image() pile.fill(pile.create_random_pattern()) pile.write_image()
normal
{ "blob_id": "a484272ace089008e27f4e00d2e641118432665e", "index": 4592, "step-1": "<mask token>\n\n\nclass PileMosaic:\n\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = 'pile_mosaic.png'\n self.crema = 240, 233, 227\n self.choco = 89, 62, 53\n self.luna = 43, 97, 123\n self.latte = 195, 175, 148\n self.piscina = 170, 200, 211\n self.lavanda = 189, 192, 209\n self.viola = 133, 108, 140\n self.morado = 121, 69, 92\n self.rosa = 222, 179, 172\n self.flamingo = 238, 157, 140\n self.color_tuple = (self.crema, self.choco, self.luna, self.latte,\n self.piscina)\n self.tile_width = 300\n self.tile_height = 100\n\n def create_new_image(self):\n self.image = Image.new('RGB', (self.width, self.height), 'white')\n self.data = [(255, 255, 255)] * (self.width * self.height)\n <mask token>\n\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv //\n 3))\n\n def rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n def place_pile(self, color, x=0, y=0):\n for i in range(self.tile_width):\n for j in range(self.tile_height):\n self.image.im.putpixel((x + i, y + j), color)\n\n def fill_random(self):\n for x in range(self.width / self.tile_width):\n for y in range(self.height / self.tile_height):\n current_color = randrange(5)\n self.place_pile(self.color_tuple[current_color], x=x * self\n .tile_width, y=y * self.tile_height)\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass PileMosaic:\n\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = 'pile_mosaic.png'\n self.crema = 240, 233, 227\n self.choco = 89, 62, 53\n self.luna = 43, 97, 123\n self.latte = 195, 175, 148\n self.piscina = 170, 200, 211\n self.lavanda = 189, 192, 209\n self.viola = 133, 108, 140\n self.morado = 121, 69, 92\n self.rosa = 222, 179, 172\n self.flamingo = 238, 157, 140\n self.color_tuple = (self.crema, self.choco, self.luna, self.latte,\n self.piscina)\n self.tile_width = 300\n self.tile_height = 100\n\n def create_new_image(self):\n self.image = Image.new('RGB', (self.width, self.height), 'white')\n self.data = [(255, 255, 255)] * (self.width * self.height)\n <mask token>\n\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv //\n 3))\n\n def rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n def place_pile(self, color, x=0, y=0):\n for i in range(self.tile_width):\n for j in range(self.tile_height):\n self.image.im.putpixel((x + i, y + j), color)\n\n def fill_random(self):\n for x in range(self.width / self.tile_width):\n for y in range(self.height / self.tile_height):\n current_color = randrange(5)\n self.place_pile(self.color_tuple[current_color], x=x * self\n .tile_width, y=y * self.tile_height)\n\n def create_random_pattern(self):\n initial_pattern = []\n for x in range(self.width / self.tile_width):\n initial_pattern.append([])\n for y in range(self.height / self.tile_height):\n temp_list = list(self.color_tuple)\n if x - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x - 1][y])\n except ValueError:\n pass\n if y - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x][y - 1])\n except ValueError:\n pass\n initial_pattern[x].append(temp_list[randrange(len(temp_list))])\n return initial_pattern\n <mask token>\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass PileMosaic:\n\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = 'pile_mosaic.png'\n self.crema = 240, 233, 227\n self.choco = 89, 62, 53\n self.luna = 43, 97, 123\n self.latte = 195, 175, 148\n self.piscina = 170, 200, 211\n self.lavanda = 189, 192, 209\n self.viola = 133, 108, 140\n self.morado = 121, 69, 92\n self.rosa = 222, 179, 172\n self.flamingo = 238, 157, 140\n self.color_tuple = (self.crema, self.choco, self.luna, self.latte,\n self.piscina)\n self.tile_width = 300\n self.tile_height = 100\n\n def create_new_image(self):\n self.image = Image.new('RGB', (self.width, self.height), 'white')\n self.data = [(255, 255, 255)] * (self.width * self.height)\n\n def write_image(self):\n self.image.save(self.filename, 'PNG')\n\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv //\n 3))\n\n def rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n def place_pile(self, color, x=0, y=0):\n for i in range(self.tile_width):\n for j in range(self.tile_height):\n self.image.im.putpixel((x + i, y + j), color)\n\n def fill_random(self):\n for x in range(self.width / self.tile_width):\n for y in range(self.height / self.tile_height):\n current_color = randrange(5)\n self.place_pile(self.color_tuple[current_color], x=x * self\n .tile_width, y=y * self.tile_height)\n\n def create_random_pattern(self):\n initial_pattern = []\n for x in range(self.width / self.tile_width):\n initial_pattern.append([])\n for y in range(self.height / self.tile_height):\n temp_list = list(self.color_tuple)\n if x - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x - 1][y])\n except ValueError:\n pass\n if y - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x][y - 1])\n except ValueError:\n pass\n initial_pattern[x].append(temp_list[randrange(len(temp_list))])\n return initial_pattern\n\n def fill(self, pattern):\n for x in range(self.width / (self.tile_width + 4)):\n for y in range(self.height / (self.tile_height + 4)):\n self.place_pile(pattern[x][y], x=x * (self.tile_width + 4),\n y=y * (self.tile_height + 4))\n\n\npile = PileMosaic()\npile.create_new_image()\npile.fill(pile.create_random_pattern())\npile.write_image()\n", "step-4": "from PIL import Image\nfrom random import randrange\n\n\nclass PileMosaic:\n\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = 'pile_mosaic.png'\n self.crema = 240, 233, 227\n self.choco = 89, 62, 53\n self.luna = 43, 97, 123\n self.latte = 195, 175, 148\n self.piscina = 170, 200, 211\n self.lavanda = 189, 192, 209\n self.viola = 133, 108, 140\n self.morado = 121, 69, 92\n self.rosa = 222, 179, 172\n self.flamingo = 238, 157, 140\n self.color_tuple = (self.crema, self.choco, self.luna, self.latte,\n self.piscina)\n self.tile_width = 300\n self.tile_height = 100\n\n def create_new_image(self):\n self.image = Image.new('RGB', (self.width, self.height), 'white')\n self.data = [(255, 255, 255)] * (self.width * self.height)\n\n def write_image(self):\n self.image.save(self.filename, 'PNG')\n\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv //\n 3))\n\n def rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n def place_pile(self, color, x=0, y=0):\n for i in range(self.tile_width):\n for j in range(self.tile_height):\n self.image.im.putpixel((x + i, y + j), color)\n\n def fill_random(self):\n for x in range(self.width / self.tile_width):\n for y in range(self.height / self.tile_height):\n current_color = randrange(5)\n self.place_pile(self.color_tuple[current_color], x=x * self\n .tile_width, y=y * self.tile_height)\n\n def create_random_pattern(self):\n initial_pattern = []\n for x in range(self.width / self.tile_width):\n initial_pattern.append([])\n for y in range(self.height / self.tile_height):\n temp_list = list(self.color_tuple)\n if x - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x - 1][y])\n except ValueError:\n pass\n if y - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x][y - 1])\n except ValueError:\n pass\n initial_pattern[x].append(temp_list[randrange(len(temp_list))])\n return initial_pattern\n\n def fill(self, pattern):\n for x in range(self.width / (self.tile_width + 4)):\n for y in range(self.height / (self.tile_height + 4)):\n self.place_pile(pattern[x][y], x=x * (self.tile_width + 4),\n y=y * (self.tile_height + 4))\n\n\npile = PileMosaic()\npile.create_new_image()\npile.fill(pile.create_random_pattern())\npile.write_image()\n", "step-5": "from PIL import Image\nfrom random import randrange\n\nclass PileMosaic:\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = \"pile_mosaic.png\"\n self.crema = (240, 233, 227)\n self.choco = (89, 62, 53)\n self.luna = (43, 97, 123)\n self.latte = (195, 175, 148)\n self.piscina = (170, 200, 211)\n self.lavanda = (189, 192, 209)\n self.viola = (133, 108, 140)\n self.morado = (121, 69, 92)\n self.rosa = (222, 179, 172)\n self.flamingo = (238, 157, 140)\n self.color_tuple = (self.crema, self.choco, self.luna, self.latte, self.piscina)\n # self.color_tuple = (self.lavanda, self.viola, self.rosa, self.morado, self.flamingo)\n self.tile_width = 300\n self.tile_height = 100\n\n def create_new_image(self):\n self.image = Image.new(\"RGB\", (self.width, self.height), \"white\")\n self.data = [(255, 255, 255)]*(self.width*self.height)\n\n def write_image(self):\n self.image.save(self.filename, \"PNG\")\n\n def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))\n\n def rgb_to_hex(rgb):\n return '#%02x%02x%02x' % rgb\n\n def place_pile(self, color, x=0, y=0):\n for i in range(self.tile_width):\n for j in range(self.tile_height):\n self.image.im.putpixel((x + i, y + j), color)\n\n def fill_random(self):\n for x in range(self.width / self.tile_width):\n for y in range(self.height / self.tile_height):\n current_color = randrange(5)\n self.place_pile(self.color_tuple[current_color], x=x*self.tile_width, y=y*self.tile_height)\n\n def create_random_pattern(self):\n initial_pattern = []\n for x in range(self.width / self.tile_width):\n initial_pattern.append([])\n for y in range(self.height / self.tile_height):\n temp_list = list(self.color_tuple)\n if x - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x - 1][y])\n except ValueError:\n pass\n if y - 1 >= 0:\n try:\n temp_list.remove(initial_pattern[x][y - 1])\n except ValueError:\n pass\n initial_pattern[x].append(temp_list[randrange(len(temp_list))])\n return initial_pattern\n \n def fill(self, pattern):\n for x in range(self.width / (self.tile_width + 4)):\n for y in range(self.height / (self.tile_height + 4)):\n self.place_pile(pattern[x][y], x=x*(self.tile_width+4), y=y*(self.tile_height+4))\n \n\npile = PileMosaic()\npile.create_new_image()\npile.fill(pile.create_random_pattern())\npile.write_image()\n", "step-ids": [ 7, 8, 12, 13, 14 ] }
[ 7, 8, 12, 13, 14 ]
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon # are the lat/lon values of the lower left and upper right corners # of the map. # resolution = 'c' means use crude resolution coastlines. m = Basemap(projection='cea',llcrnrlat=-90,urcrnrlat=90,\ llcrnrlon=-180,urcrnrlon=180,resolution='c') m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-90.,91.,30.)) m.drawmeridians(np.arange(-180.,181.,60.)) m.drawmapboundary(fill_color='aqua') plt.title("Cylindrical Equal-Area Projection") plt.show()
normal
{ "blob_id": "f5f9a1c7dcb7345e24f50db54649a1970fc37185", "index": 1262, "step-1": "<mask token>\n", "step-2": "<mask token>\nm.drawcoastlines()\nm.fillcontinents(color='coral', lake_color='aqua')\nm.drawparallels(np.arange(-90.0, 91.0, 30.0))\nm.drawmeridians(np.arange(-180.0, 181.0, 60.0))\nm.drawmapboundary(fill_color='aqua')\nplt.title('Cylindrical Equal-Area Projection')\nplt.show()\n", "step-3": "<mask token>\nm = Basemap(projection='cea', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180,\n urcrnrlon=180, resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='coral', lake_color='aqua')\nm.drawparallels(np.arange(-90.0, 91.0, 30.0))\nm.drawmeridians(np.arange(-180.0, 181.0, 60.0))\nm.drawmapboundary(fill_color='aqua')\nplt.title('Cylindrical Equal-Area Projection')\nplt.show()\n", "step-4": "from mpl_toolkits.basemap import Basemap\nimport numpy as np\nimport matplotlib.pyplot as plt\nm = Basemap(projection='cea', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180,\n urcrnrlon=180, resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='coral', lake_color='aqua')\nm.drawparallels(np.arange(-90.0, 91.0, 30.0))\nm.drawmeridians(np.arange(-180.0, 181.0, 60.0))\nm.drawmapboundary(fill_color='aqua')\nplt.title('Cylindrical Equal-Area Projection')\nplt.show()\n", "step-5": "from mpl_toolkits.basemap import Basemap\nimport numpy as np\nimport matplotlib.pyplot as plt\n# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon\n# are the lat/lon values of the lower left and upper right corners\n# of the map.\n# resolution = 'c' means use crude resolution coastlines.\nm = Basemap(projection='cea',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=-180,urcrnrlon=180,resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='coral',lake_color='aqua')\n# draw parallels and meridians.\nm.drawparallels(np.arange(-90.,91.,30.))\nm.drawmeridians(np.arange(-180.,181.,60.))\nm.drawmapboundary(fill_color='aqua')\nplt.title(\"Cylindrical Equal-Area Projection\")\nplt.show()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import functools import requests import time import argparse class TracePoint: classes = [] funcs = [] flow = [] @staticmethod def clear(): TracePoint.classes = [] TracePoint.funcs = [] TracePoint.flow = [] def __init__(self, cls, func, t): if cls not in TracePoint.classes: TracePoint.classes.append(cls) if cls not in TracePoint.funcs: TracePoint.funcs.append(func) TracePoint.flow.append(",".join([cls,t, func])) def render_flow(self): first = TracePoint.flow[0] recods = set() for no,i in enumerate(TracePoint.flow[1:]): cls,t, func = i.split(',',2) fcls,ft, ffunc = first.split(',', 2) fn = func.split("(")[0] ffn = ffunc.split("(")[0] label = "{l} -> {c}".format(l=ffn, c=fn) if label in recods: continue recods.add(label) lc,_ = self.get_color(cls, func) yield """{l} -> {c} [label="<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];""".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc) first = i def render_var(self, one): cls,t, func = one.strip().split(",", 2) color, color_f = self.get_color(cls, func) fn = func.split("(")[0] tmp = """{func_name} [labelType="html" label="<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>"];""".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func) return tmp def get_color(self, cls, func): base = 4096 // len(TracePoint.classes) base_f = 4096 // len(TracePoint.funcs) c = hex(base * TracePoint.classes.index(cls)).replace("0x", "#") c_f = hex(base_f * TracePoint.funcs.index(func)).replace("0x", "#") if len(c) < 4: c = c + '0'* (4- len(c)) if len(c_f) < 4: c_f = c_f + '0'* (4- len(c_f)) return c,c_f def __repr__(self): TEMP = """ digraph { /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */ node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"] edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"] %s } """ fcon = "\n\t".join([self.render_var(i) for i in TracePoint.flow]) lcon = "\n\t".join(self.render_flow()) return TEMP % (fcon + lcon) def trace(cls): def _func(func): @functools.wraps(func) def __run(*args, **kargs): print(func.__name__, args,"|" ,kargs) return func(*args, **kargs) return __run return _func def trace_cls(method): def _trace_cls(cls): # Get the original implementation orig_getattribute = cls.__getattribute__ # Make a new definition def new_getattribute(self, name): if name in cls.__dict__: f = getattr(cls, name) args = "(%s)" % ', '.join(f.__code__.co_varnames) t = str(time.time()) if "http://" in method: requests.post("http://localhost:12222/", data={ 'class':cls.__name__, 'fun':name + args, 'time':t, }) else: with open(method, "a+") as fp: s = ",".join([cls.__name__,t,name + args]) fp.write(s + "\n") return orig_getattribute(self, name) # Attach to the class and return cls.__getattribute__ = new_getattribute return cls return _trace_cls def main(): parser = argparse.ArgumentParser() parser.add_argument("-l","--load",default=None,help="loadfile") parser.add_argument("--url", default='http://localhost:12222',help="debug server") args = parser.parse_args() with open(args.load) as fp: for l in fp: cls, t, func = l.strip().split(',', 2) requests.post(args.url, data={ 'class':cls, 'fun':func, 'time':t, }) if __name__ == '__main__': main()
normal
{ "blob_id": "80bf208f1d658b639d650af8208a744ed2dd258f", "index": 9355, "step-1": "<mask token>\n\n\nclass TracePoint:\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import functools\nimport requests\nimport time\nimport argparse\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = [] \n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(\",\".join([cls,t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no,i in enumerate(TracePoint.flow[1:]):\n cls,t, func = i.split(',',2)\n fcls,ft, ffunc = first.split(',', 2)\n fn = func.split(\"(\")[0]\n ffn = ffunc.split(\"(\")[0]\n label = \"{l} -> {c}\".format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc,_ = self.get_color(cls, func)\n yield \"\"\"{l} -> {c} [label=\"<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];\"\"\".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n\n def render_var(self, one):\n cls,t, func = one.strip().split(\",\", 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split(\"(\")[0]\n tmp = \"\"\"{func_name} [labelType=\"html\" label=\"<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>\"];\"\"\".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func)\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace(\"0x\", \"#\")\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace(\"0x\", \"#\")\n if len(c) < 4:\n c = c + '0'* (4- len(c))\n if len(c_f) < 4:\n c_f = c_f + '0'* (4- len(c_f))\n return c,c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = \"\\n\\t\".join([self.render_var(i) for i in TracePoint.flow])\n lcon = \"\\n\\t\".join(self.render_flow())\n return TEMP % (fcon + lcon)\n\ndef trace(cls):\n\n def _func(func):\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args,\"|\" ,kargs)\n return func(*args, **kargs)\n\n return __run\n return _func\n\n\ndef trace_cls(method):\n def _trace_cls(cls):\n # Get the original implementation\n orig_getattribute = cls.__getattribute__\n\n # Make a new definition\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = \"(%s)\" % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n\n if \"http://\" in method:\n requests.post(\"http://localhost:12222/\", data={\n 'class':cls.__name__,\n 'fun':name + args,\n 'time':t,\n })\n else:\n with open(method, \"a+\") as fp:\n s = \",\".join([cls.__name__,t,name + args])\n fp.write(s + \"\\n\")\n return orig_getattribute(self, name)\n\n # Attach to the class and return\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\",\"--load\",default=None,help=\"loadfile\")\n parser.add_argument(\"--url\", default='http://localhost:12222',help=\"debug server\")\n\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={\n 'class':cls,\n 'fun':func,\n 'time':t,\n })\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 6, 9, 11, 12, 14 ] }
[ 6, 9, 11, 12, 14 ]
from apps.mastermind.core.domain.domain import Color, Game from apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork from composite_root.container import provide class GameMother: async def a_game( self, num_slots: int, num_colors: int, max_guesses: int, secret_code: list[Color], reference: str | None = None, ) -> Game: async with provide(MongoUnitOfWork) as uow: game = Game.new( id=uow.games.next_id(), num_slots=num_slots, num_colors=num_colors, max_guesses=max_guesses, ) game.secret_code = secret_code if reference: game.reference = reference await uow.games.asave(game) await uow.commit() return game
normal
{ "blob_id": "8457cdde8f8ad069505c7729b8217e5d272be41e", "index": 957, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass GameMother:\n\n async def a_game(self, num_slots: int, num_colors: int, max_guesses:\n int, secret_code: list[Color], reference: (str | None)=None) ->Game:\n async with provide(MongoUnitOfWork) as uow:\n game = Game.new(id=uow.games.next_id(), num_slots=num_slots,\n num_colors=num_colors, max_guesses=max_guesses)\n game.secret_code = secret_code\n if reference:\n game.reference = reference\n await uow.games.asave(game)\n await uow.commit()\n return game\n", "step-3": "from apps.mastermind.core.domain.domain import Color, Game\nfrom apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork\nfrom composite_root.container import provide\n\n\nclass GameMother:\n\n async def a_game(self, num_slots: int, num_colors: int, max_guesses:\n int, secret_code: list[Color], reference: (str | None)=None) ->Game:\n async with provide(MongoUnitOfWork) as uow:\n game = Game.new(id=uow.games.next_id(), num_slots=num_slots,\n num_colors=num_colors, max_guesses=max_guesses)\n game.secret_code = secret_code\n if reference:\n game.reference = reference\n await uow.games.asave(game)\n await uow.commit()\n return game\n", "step-4": "from apps.mastermind.core.domain.domain import Color, Game\nfrom apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork\nfrom composite_root.container import provide\n\n\nclass GameMother:\n async def a_game(\n self,\n num_slots: int,\n num_colors: int,\n max_guesses: int,\n secret_code: list[Color],\n reference: str | None = None,\n ) -> Game:\n async with provide(MongoUnitOfWork) as uow:\n game = Game.new(\n id=uow.games.next_id(),\n num_slots=num_slots,\n num_colors=num_colors,\n max_guesses=max_guesses,\n )\n game.secret_code = secret_code\n\n if reference:\n game.reference = reference\n\n await uow.games.asave(game)\n await uow.commit()\n return game\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pymysql def get_list(sql, args): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd ='chen0918', db='web') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql, args) result = cursor.fetchall() cursor.close() conn.close() return result def get_one(sql, args): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd ='chen0918', db='web') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql, args) result = cursor.fetchone() cursor.close() conn.close() return result def modify(sql, args): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd ='chen0918', db='web') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql, args) conn.commit() cursor.close() conn.close()
normal
{ "blob_id": "80819ec83572737c89044936fc269154b190751a", "index": 2372, "step-1": "<mask token>\n\n\ndef modify(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n conn.commit()\n cursor.close()\n conn.close()\n", "step-2": "<mask token>\n\n\ndef get_list(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n result = cursor.fetchall()\n cursor.close()\n conn.close()\n return result\n\n\n<mask token>\n\n\ndef modify(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n conn.commit()\n cursor.close()\n conn.close()\n", "step-3": "<mask token>\n\n\ndef get_list(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n result = cursor.fetchall()\n cursor.close()\n conn.close()\n return result\n\n\ndef get_one(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n result = cursor.fetchone()\n cursor.close()\n conn.close()\n return result\n\n\ndef modify(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n conn.commit()\n cursor.close()\n conn.close()\n", "step-4": "import pymysql\n\n\ndef get_list(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n result = cursor.fetchall()\n cursor.close()\n conn.close()\n return result\n\n\ndef get_one(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n result = cursor.fetchone()\n cursor.close()\n conn.close()\n return result\n\n\ndef modify(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(sql, args)\n conn.commit()\n cursor.close()\n conn.close()\n", "step-5": null, "step-ids": [ 1, 2, 3, 4 ] }
[ 1, 2, 3, 4 ]
from random import randint from Ball import Ball from Util import Vector, Rectangle class Player: RADIUS = 10 COLOR1 = "#80d6ff" COLOR2 = "#ff867c" OUTLINE = "#000000" @property def right(self): return self.pos.sub(Vector(Player.RADIUS, 0)) @property def left(self): return self.pos.add(Vector(Player.RADIUS, 0)) @property def color(self): if self.team == 1: return Player.COLOR1 elif self.team == 2: return Player.COLOR2 def __init__(self, canvas, team): self.canvas = canvas self.team = team self.pos = Vector(0, 0) self.old_pos = Vector(0, 0) self.shape = None def set(self, v): self.old_pos = self.pos self.pos = v self.paint() def move(self, v: Vector): self.set(self.pos.add(v)) def move_to_point(self, point: Vector): v = randint(1, 10) / 10 self.move(point.sub(self.pos).norm().mul(Vector(v, v))) def get_ball(self, ball): if self.team == 1: ball.set(self.right) elif self.team == 2: ball.set(self.left) def paint(self): if self.shape is None: self.shape = self.canvas.create_rectangle(-Player.RADIUS, -Player.RADIUS, Player.RADIUS, Player.RADIUS, outline=Player.OUTLINE, fill=self.color) delta = self.pos.sub(self.old_pos) self.canvas.move(self.shape, delta.x, delta.y) def rectangle(self) -> Rectangle: return self.pos.rect(Player.RADIUS) def ball_hit_test(self, ball: Ball) -> bool: return self.rectangle().hit(ball.pos)
normal
{ "blob_id": "04b02931b749ad06a512b78ca5661ae1f5cb8a9c", "index": 5534, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Player:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n @property\n def left(self):\n return self.pos.add(Vector(Player.RADIUS, 0))\n <mask token>\n <mask token>\n\n def set(self, v):\n self.old_pos = self.pos\n self.pos = v\n self.paint()\n\n def move(self, v: Vector):\n self.set(self.pos.add(v))\n <mask token>\n\n def get_ball(self, ball):\n if self.team == 1:\n ball.set(self.right)\n elif self.team == 2:\n ball.set(self.left)\n\n def paint(self):\n if self.shape is None:\n self.shape = self.canvas.create_rectangle(-Player.RADIUS, -\n Player.RADIUS, Player.RADIUS, Player.RADIUS, outline=Player\n .OUTLINE, fill=self.color)\n delta = self.pos.sub(self.old_pos)\n self.canvas.move(self.shape, delta.x, delta.y)\n <mask token>\n\n def ball_hit_test(self, ball: Ball) ->bool:\n return self.rectangle().hit(ball.pos)\n", "step-3": "<mask token>\n\n\nclass Player:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n @property\n def left(self):\n return self.pos.add(Vector(Player.RADIUS, 0))\n <mask token>\n <mask token>\n\n def set(self, v):\n self.old_pos = self.pos\n self.pos = v\n self.paint()\n\n def move(self, v: Vector):\n self.set(self.pos.add(v))\n\n def move_to_point(self, point: Vector):\n v = randint(1, 10) / 10\n self.move(point.sub(self.pos).norm().mul(Vector(v, v)))\n\n def get_ball(self, ball):\n if self.team == 1:\n ball.set(self.right)\n elif self.team == 2:\n ball.set(self.left)\n\n def paint(self):\n if self.shape is None:\n self.shape = self.canvas.create_rectangle(-Player.RADIUS, -\n Player.RADIUS, Player.RADIUS, Player.RADIUS, outline=Player\n .OUTLINE, fill=self.color)\n delta = self.pos.sub(self.old_pos)\n self.canvas.move(self.shape, delta.x, delta.y)\n <mask token>\n\n def ball_hit_test(self, ball: Ball) ->bool:\n return self.rectangle().hit(ball.pos)\n", "step-4": "from random import randint\nfrom Ball import Ball\nfrom Util import Vector, Rectangle\n\n\nclass Player:\n RADIUS = 10\n COLOR1 = '#80d6ff'\n COLOR2 = '#ff867c'\n OUTLINE = '#000000'\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n @property\n def left(self):\n return self.pos.add(Vector(Player.RADIUS, 0))\n\n @property\n def color(self):\n if self.team == 1:\n return Player.COLOR1\n elif self.team == 2:\n return Player.COLOR2\n\n def __init__(self, canvas, team):\n self.canvas = canvas\n self.team = team\n self.pos = Vector(0, 0)\n self.old_pos = Vector(0, 0)\n self.shape = None\n\n def set(self, v):\n self.old_pos = self.pos\n self.pos = v\n self.paint()\n\n def move(self, v: Vector):\n self.set(self.pos.add(v))\n\n def move_to_point(self, point: Vector):\n v = randint(1, 10) / 10\n self.move(point.sub(self.pos).norm().mul(Vector(v, v)))\n\n def get_ball(self, ball):\n if self.team == 1:\n ball.set(self.right)\n elif self.team == 2:\n ball.set(self.left)\n\n def paint(self):\n if self.shape is None:\n self.shape = self.canvas.create_rectangle(-Player.RADIUS, -\n Player.RADIUS, Player.RADIUS, Player.RADIUS, outline=Player\n .OUTLINE, fill=self.color)\n delta = self.pos.sub(self.old_pos)\n self.canvas.move(self.shape, delta.x, delta.y)\n\n def rectangle(self) ->Rectangle:\n return self.pos.rect(Player.RADIUS)\n\n def ball_hit_test(self, ball: Ball) ->bool:\n return self.rectangle().hit(ball.pos)\n", "step-5": "from random import randint\n\nfrom Ball import Ball\nfrom Util import Vector, Rectangle\n\n\nclass Player:\n RADIUS = 10\n\n COLOR1 = \"#80d6ff\"\n COLOR2 = \"#ff867c\"\n OUTLINE = \"#000000\"\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n @property\n def left(self):\n return self.pos.add(Vector(Player.RADIUS, 0))\n\n @property\n def color(self):\n if self.team == 1:\n return Player.COLOR1\n elif self.team == 2:\n return Player.COLOR2\n\n def __init__(self, canvas, team):\n self.canvas = canvas\n self.team = team\n self.pos = Vector(0, 0)\n self.old_pos = Vector(0, 0)\n self.shape = None\n\n def set(self, v):\n self.old_pos = self.pos\n self.pos = v\n self.paint()\n\n def move(self, v: Vector):\n self.set(self.pos.add(v))\n\n def move_to_point(self, point: Vector):\n v = randint(1, 10) / 10\n self.move(point.sub(self.pos).norm().mul(Vector(v, v)))\n\n def get_ball(self, ball):\n if self.team == 1:\n ball.set(self.right)\n elif self.team == 2:\n ball.set(self.left)\n\n def paint(self):\n if self.shape is None:\n self.shape = self.canvas.create_rectangle(-Player.RADIUS, -Player.RADIUS, Player.RADIUS, Player.RADIUS,\n outline=Player.OUTLINE, fill=self.color)\n delta = self.pos.sub(self.old_pos)\n self.canvas.move(self.shape, delta.x, delta.y)\n\n def rectangle(self) -> Rectangle:\n return self.pos.rect(Player.RADIUS)\n\n def ball_hit_test(self, ball: Ball) -> bool:\n return self.rectangle().hit(ball.pos)\n", "step-ids": [ 0, 8, 9, 14, 15 ] }
[ 0, 8, 9, 14, 15 ]
from collections import namedtuple from weakref import ref l = list() _l = list() # Point = namedtuple('Point', ['x', 'y']) class Point: def __init__(self,x,y): self.x = x self.y = y def callback(ref): print ('__del__', ref) for x in range(10): p = Point(x,x**2) t = ref(p,callback) print(t) l.append(t) _l.append(p) print(len(l),l) print(len(_l),_l) t = _l[6] del t,_l[6] print(len(_l),_l) # print(len(l),l)
normal
{ "blob_id": "2542998c3a7decd6329856a31d8e9de56f82bae1", "index": 3922, "step-1": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\ndef callback(ref):\n print('__del__', ref)\n\n\n<mask token>\n", "step-3": "<mask token>\nl = list()\n_l = list()\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\ndef callback(ref):\n print('__del__', ref)\n\n\nfor x in range(10):\n p = Point(x, x ** 2)\n t = ref(p, callback)\n print(t)\n l.append(t)\n _l.append(p)\nprint(len(l), l)\nprint(len(_l), _l)\nt = _l[6]\ndel t, _l[6]\nprint(len(_l), _l)\n", "step-4": "from collections import namedtuple\nfrom weakref import ref\nl = list()\n_l = list()\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\ndef callback(ref):\n print('__del__', ref)\n\n\nfor x in range(10):\n p = Point(x, x ** 2)\n t = ref(p, callback)\n print(t)\n l.append(t)\n _l.append(p)\nprint(len(l), l)\nprint(len(_l), _l)\nt = _l[6]\ndel t, _l[6]\nprint(len(_l), _l)\n", "step-5": "from collections import namedtuple\nfrom weakref import ref\n\nl = list()\n_l = list()\n\n# Point = namedtuple('Point', ['x', 'y'])\nclass Point:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\n\ndef callback(ref):\n print ('__del__', ref)\n\n\nfor x in range(10):\n p = Point(x,x**2)\n t = ref(p,callback)\n print(t)\n l.append(t)\n _l.append(p)\n\nprint(len(l),l)\nprint(len(_l),_l)\n\nt = _l[6]\ndel t,_l[6]\n\nprint(len(_l),_l)\n\n\n# print(len(l),l)", "step-ids": [ 2, 3, 5, 6, 7 ] }
[ 2, 3, 5, 6, 7 ]
try: import RPi.GPIO as GPIO import time import numpy as np import matplotlib.pyplot as plt from os.path import dirname, join as pjoin from scipy.io import wavfile import scipy.io except ImportError: print ("Import error!") raise SystemExit try: chan_list = (26, 19, 13, 6, 5, 11, 9, 10) GPIO.setmode (GPIO.BCM) GPIO.setup (chan_list, GPIO.OUT) except: print ("GPIO Initialization error!") raise SystemExit def decToBinList (decNumber): if decNumber < 0 or decNumber > 255: raise ValueError return [(int(decNumber) & (1 << i)) >> i for i in range (7, -1, -1)] def num2dac (value): x = decToBinList (value) GPIO.output (chan_list, tuple (x)) wav_fname = pjoin('SOUND.WAV') samplerate, data = wavfile.read(wav_fname) length = data.shape[0] / samplerate print ("length: ", int(length), "s, number of channels: ", data.shape[1], ", Sample Rate: ", samplerate, ", data type: ", type (data[1, 0])) try: for i in data[:, 0]: num2dac ((int(i) + 32768) / 256) except ValueError: print ("Ошибка в в размере входных данных. Выходим из программы") except: print ("Неизвестная ошибка. Выходим из программы") finally: GPIO.output (chan_list, 0) GPIO.cleanup (chan_list)
normal
{ "blob_id": "675d564ad60870f49b88dece480d5a50a30491df", "index": 4907, "step-1": "<mask token>\n\n\ndef decToBinList(decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [((int(decNumber) & 1 << i) >> i) for i in range(7, -1, -1)]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef decToBinList(decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [((int(decNumber) & 1 << i) >> i) for i in range(7, -1, -1)]\n\n\ndef num2dac(value):\n x = decToBinList(value)\n GPIO.output(chan_list, tuple(x))\n\n\n<mask token>\n", "step-3": "try:\n import RPi.GPIO as GPIO\n import time\n import numpy as np\n import matplotlib.pyplot as plt\n from os.path import dirname, join as pjoin\n from scipy.io import wavfile\n import scipy.io\nexcept ImportError:\n print('Import error!')\n raise SystemExit\ntry:\n chan_list = 26, 19, 13, 6, 5, 11, 9, 10\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(chan_list, GPIO.OUT)\nexcept:\n print('GPIO Initialization error!')\n raise SystemExit\n\n\ndef decToBinList(decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [((int(decNumber) & 1 << i) >> i) for i in range(7, -1, -1)]\n\n\ndef num2dac(value):\n x = decToBinList(value)\n GPIO.output(chan_list, tuple(x))\n\n\n<mask token>\nprint('length: ', int(length), 's, number of channels: ', data.shape[1],\n ', Sample Rate: ', samplerate, ', data type: ', type(data[1, 0]))\ntry:\n for i in data[:, 0]:\n num2dac((int(i) + 32768) / 256)\nexcept ValueError:\n print('Ошибка в в размере входных данных. Выходим из программы')\nexcept:\n print('Неизвестная ошибка. Выходим из программы')\nfinally:\n GPIO.output(chan_list, 0)\n GPIO.cleanup(chan_list)\n", "step-4": "try:\n import RPi.GPIO as GPIO\n import time\n import numpy as np\n import matplotlib.pyplot as plt\n from os.path import dirname, join as pjoin\n from scipy.io import wavfile\n import scipy.io\nexcept ImportError:\n print('Import error!')\n raise SystemExit\ntry:\n chan_list = 26, 19, 13, 6, 5, 11, 9, 10\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(chan_list, GPIO.OUT)\nexcept:\n print('GPIO Initialization error!')\n raise SystemExit\n\n\ndef decToBinList(decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [((int(decNumber) & 1 << i) >> i) for i in range(7, -1, -1)]\n\n\ndef num2dac(value):\n x = decToBinList(value)\n GPIO.output(chan_list, tuple(x))\n\n\nwav_fname = pjoin('SOUND.WAV')\nsamplerate, data = wavfile.read(wav_fname)\nlength = data.shape[0] / samplerate\nprint('length: ', int(length), 's, number of channels: ', data.shape[1],\n ', Sample Rate: ', samplerate, ', data type: ', type(data[1, 0]))\ntry:\n for i in data[:, 0]:\n num2dac((int(i) + 32768) / 256)\nexcept ValueError:\n print('Ошибка в в размере входных данных. Выходим из программы')\nexcept:\n print('Неизвестная ошибка. Выходим из программы')\nfinally:\n GPIO.output(chan_list, 0)\n GPIO.cleanup(chan_list)\n", "step-5": "try:\n import RPi.GPIO as GPIO\n import time\n import numpy as np\n import matplotlib.pyplot as plt\n from os.path import dirname, join as pjoin\n from scipy.io import wavfile\n import scipy.io\nexcept ImportError:\n print (\"Import error!\")\n raise SystemExit\n \ntry:\n chan_list = (26, 19, 13, 6, 5, 11, 9, 10)\n GPIO.setmode (GPIO.BCM)\n GPIO.setup (chan_list, GPIO.OUT)\nexcept:\n print (\"GPIO Initialization error!\")\n raise SystemExit\n \n \ndef decToBinList (decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [(int(decNumber) & (1 << i)) >> i for i in range (7, -1, -1)]\n \ndef num2dac (value):\n x = decToBinList (value)\n GPIO.output (chan_list, tuple (x))\n\nwav_fname = pjoin('SOUND.WAV')\nsamplerate, data = wavfile.read(wav_fname)\nlength = data.shape[0] / samplerate\n\nprint (\"length: \", int(length), \"s, number of channels: \", data.shape[1], \", Sample Rate: \", samplerate, \", data type: \", type (data[1, 0]))\n\ntry:\n for i in data[:, 0]:\n num2dac ((int(i) + 32768) / 256)\nexcept ValueError:\n print (\"Ошибка в в размере входных данных. Выходим из программы\")\nexcept:\n print (\"Неизвестная ошибка. Выходим из программы\")\nfinally:\n GPIO.output (chan_list, 0)\n GPIO.cleanup (chan_list)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
/Users/medrine/anaconda/lib/python2.7/UserDict.py
normal
{ "blob_id": "8db90b0bfde61de1c4c1462bc3bcf05ef9056362", "index": 9236, "step-1": "/Users/medrine/anaconda/lib/python2.7/UserDict.py", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from boxsdk import Client, OAuth2 import os import sys def ConfigObject(config_path): "read a configuration file to retrieve access token" configDict = {} with open(config_path,'r') as config: for line in config.readlines(): try: configDict[line.split("=")[0]] = line.split("=")[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder = None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded def accessUploadFolder(year=2020): # Define client ID, client secret, and developer token.path = os.path.join(*[os.path.dirname(os.path.abspath(__file__)),"instance"]) # Read app info from text file config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(__file__)),"instance", 'Boxapp.cfg'])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] # Create OAuth2 object. auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=ACCESS_TOKEN) # Create the authenticated client client = Client(auth) # make sure we connected try: my = client.user(user_id='me').get() print(my.name) # developer name tied to the token except: sys.exit("ERROR: Invalid access token; try re-generating an " "access token from the app console on the web.") tfolder = client.folder(CLIENT_FOLDER) # 2020 scada data folder return tfolder def listZipFiles(directory_folder): ''' Lists teh zip folders in teh directory folder, including subdirectortories ''' zipFiles = [] for root, dirs, files in os.walk(directory_folder): for name in files: if name[-3:] == 'zip': zipFiles.append(os.path.join(root, name)) return zipFiles def uploadAllZippedToBox(zipFolder): '''uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed''' #files to upload zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() #tfolder.file(file_id=item.id).delete() except Exception as e: print(e) #If we coudn't delete the existing zip file don't try to upload a new one. zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped,True)) except Exception as e: print(e) badUploads.append((zipped,False)) pass return uploadedFiles, badUploads
normal
{ "blob_id": "e76ebbe8dab2e5169ef40b559f783c49ba4de825", "index": 1750, "step-1": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\n<mask token>\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-2": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\n<mask token>\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-3": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\ndef listZipFiles(directory_folder):\n \"\"\"\n Lists teh zip folders in teh directory folder, including subdirectortories\n \"\"\"\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-4": "from boxsdk import Client, OAuth2\nimport os\nimport sys\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\ndef listZipFiles(directory_folder):\n \"\"\"\n Lists teh zip folders in teh directory folder, including subdirectortories\n \"\"\"\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-5": "from boxsdk import Client, OAuth2\n\nimport os\nimport sys\n\ndef ConfigObject(config_path):\n \"read a configuration file to retrieve access token\"\n configDict = {}\n with open(config_path,'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split(\"=\")[0]] = line.split(\"=\")[1].rstrip()\n except:\n pass\n return configDict\ndef uploadZippedToBox(zippedFolder, boxfolder = None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\ndef accessUploadFolder(year=2020):\n # Define client ID, client secret, and developer token.path = os.path.join(*[os.path.dirname(os.path.abspath(__file__)),\"instance\"])\n\n # Read app info from text file\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(__file__)),\"instance\", 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n\n # Create OAuth2 object.\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=ACCESS_TOKEN)\n # Create the authenticated client\n client = Client(auth)\n\n # make sure we connected\n try:\n my = client.user(user_id='me').get()\n print(my.name) # developer name tied to the token\n except:\n sys.exit(\"ERROR: Invalid access token; try re-generating an \"\n \"access token from the app console on the web.\")\n\n tfolder = client.folder(CLIENT_FOLDER) # 2020 scada data folder\n return tfolder\ndef listZipFiles(directory_folder):\n '''\n Lists teh zip folders in teh directory folder, including subdirectortories\n '''\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\ndef uploadAllZippedToBox(zipFolder):\n '''uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed'''\n #files to upload\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n #tfolder.file(file_id=item.id).delete()\n except Exception as e:\n print(e)\n #If we coudn't delete the existing zip file don't try to upload a new one.\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped,True))\n except Exception as e:\n print(e)\n badUploads.append((zipped,False))\n pass\n\n return uploadedFiles, badUploads\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import sys from melody_types import * import dataclasses """ Marks notes for grace notes """ # Mark grace notes on the peak note of every segment def _peaks(song): for phrase in song.phrases: for pe in phrase.phrase_elements: if type(pe) == Segment: if pe.direction != SegmentDirection.UPDOWN: continue # Get peak note for i in range(1, len(pe.notes)): if pe.notes[i].pitch < pe.notes[i - 1].pitch: pe.notes[i - 1].grace = True print('sup', file=sys.stderr) break # Adds a grace note to consonant notes in every segment def _consonant(song): pass def _insert_grace_notes(song): for phrase in song.phrases: for pe in phrase.phrase_elements: if type(pe) != Segment: continue segment = pe initial_len = len(segment.notes) new_notes = [] flag = False for i in range(len(pe.notes)): if segment.notes[i].grace and not flag: new_note = Note(pitch=phrase.scale.skip_up(segment.notes[i].pitch, 1), new=True, duration=1/4) new_notes += [new_note] segment.notes[i].duration -= 1/4 flag = True new_notes += [dataclasses.replace(segment.notes[i])] assert(len(new_notes) - initial_len <= 1) pe.notes = list(new_notes) def add_grace_notes(song): _peaks(song) _insert_grace_notes(song)
normal
{ "blob_id": "ac83d7d39319c08c35302abfb312ebee463b75b2", "index": 5130, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef _insert_grace_notes(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) != Segment:\n continue\n segment = pe\n initial_len = len(segment.notes)\n new_notes = []\n flag = False\n for i in range(len(pe.notes)):\n if segment.notes[i].grace and not flag:\n new_note = Note(pitch=phrase.scale.skip_up(segment.\n notes[i].pitch, 1), new=True, duration=1 / 4)\n new_notes += [new_note]\n segment.notes[i].duration -= 1 / 4\n flag = True\n new_notes += [dataclasses.replace(segment.notes[i])]\n assert len(new_notes) - initial_len <= 1\n pe.notes = list(new_notes)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef _peaks(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) == Segment:\n if pe.direction != SegmentDirection.UPDOWN:\n continue\n for i in range(1, len(pe.notes)):\n if pe.notes[i].pitch < pe.notes[i - 1].pitch:\n pe.notes[i - 1].grace = True\n print('sup', file=sys.stderr)\n break\n\n\ndef _consonant(song):\n pass\n\n\ndef _insert_grace_notes(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) != Segment:\n continue\n segment = pe\n initial_len = len(segment.notes)\n new_notes = []\n flag = False\n for i in range(len(pe.notes)):\n if segment.notes[i].grace and not flag:\n new_note = Note(pitch=phrase.scale.skip_up(segment.\n notes[i].pitch, 1), new=True, duration=1 / 4)\n new_notes += [new_note]\n segment.notes[i].duration -= 1 / 4\n flag = True\n new_notes += [dataclasses.replace(segment.notes[i])]\n assert len(new_notes) - initial_len <= 1\n pe.notes = list(new_notes)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef _peaks(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) == Segment:\n if pe.direction != SegmentDirection.UPDOWN:\n continue\n for i in range(1, len(pe.notes)):\n if pe.notes[i].pitch < pe.notes[i - 1].pitch:\n pe.notes[i - 1].grace = True\n print('sup', file=sys.stderr)\n break\n\n\ndef _consonant(song):\n pass\n\n\ndef _insert_grace_notes(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) != Segment:\n continue\n segment = pe\n initial_len = len(segment.notes)\n new_notes = []\n flag = False\n for i in range(len(pe.notes)):\n if segment.notes[i].grace and not flag:\n new_note = Note(pitch=phrase.scale.skip_up(segment.\n notes[i].pitch, 1), new=True, duration=1 / 4)\n new_notes += [new_note]\n segment.notes[i].duration -= 1 / 4\n flag = True\n new_notes += [dataclasses.replace(segment.notes[i])]\n assert len(new_notes) - initial_len <= 1\n pe.notes = list(new_notes)\n\n\ndef add_grace_notes(song):\n _peaks(song)\n _insert_grace_notes(song)\n", "step-5": "import sys\nfrom melody_types import *\nimport dataclasses\n\"\"\"\nMarks notes for grace notes\n\"\"\"\n\n# Mark grace notes on the peak note of every segment\ndef _peaks(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) == Segment:\n if pe.direction != SegmentDirection.UPDOWN:\n continue\n\n # Get peak note\n for i in range(1, len(pe.notes)):\n if pe.notes[i].pitch < pe.notes[i - 1].pitch:\n pe.notes[i - 1].grace = True\n print('sup', file=sys.stderr)\n break\n\n# Adds a grace note to consonant notes in every segment\ndef _consonant(song):\n pass\n\ndef _insert_grace_notes(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) != Segment:\n continue\n\n segment = pe\n initial_len = len(segment.notes)\n\n new_notes = []\n flag = False\n for i in range(len(pe.notes)):\n if segment.notes[i].grace and not flag:\n new_note = Note(pitch=phrase.scale.skip_up(segment.notes[i].pitch, 1), new=True, duration=1/4)\n new_notes += [new_note]\n segment.notes[i].duration -= 1/4\n flag = True\n new_notes += [dataclasses.replace(segment.notes[i])]\n\n assert(len(new_notes) - initial_len <= 1)\n pe.notes = list(new_notes)\n\ndef add_grace_notes(song):\n _peaks(song)\n _insert_grace_notes(song)\n", "step-ids": [ 0, 1, 3, 4, 6 ] }
[ 0, 1, 3, 4, 6 ]
import requests import re from bs4 import BeautifulSoup r = requests.get("https://terraria.fandom.com/wiki/Banners_(enemy)") soup = BeautifulSoup(r.text, 'html.parser') list_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')}) x_count = 1 y_count = 1 for banner_span in list_of_banners: print(f"{banner_span['id']}, {x_count}, {y_count}") x_count += 1 if x_count == 51: x_count = 1 y_count += 1 print("\n\n-----------------")
normal
{ "blob_id": "e60d57e8884cba8ce50a571e3bd0affcd4dcaf68", "index": 4056, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-3": "<mask token>\nr = requests.get('https://terraria.fandom.com/wiki/Banners_(enemy)')\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile('_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-4": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nr = requests.get('https://terraria.fandom.com/wiki/Banners_(enemy)')\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile('_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print('\\n\\n-----------------')\n", "step-5": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nr = requests.get(\"https://terraria.fandom.com/wiki/Banners_(enemy)\")\nsoup = BeautifulSoup(r.text, 'html.parser')\nlist_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')})\nx_count = 1\ny_count = 1\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n print(\"\\n\\n-----------------\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- # project: fshell # author: s0nnet # time: 2017-01-08 # desc: data_fuzzhash import sys sys.path.append("./dao") from fss_data_fuzzhash_dao import * class FssFuzzHash: @staticmethod def insert_node(agent_id, data): return FssFuzzHashDao.insert_node(agent_id, data)
normal
{ "blob_id": "398f9f52b83ffddfb452abbeaad2e83610580fee", "index": 9763, "step-1": "<mask token>\n\n\nclass FssFuzzHash:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass FssFuzzHash:\n\n @staticmethod\n def insert_node(agent_id, data):\n return FssFuzzHashDao.insert_node(agent_id, data)\n", "step-3": "<mask token>\nsys.path.append('./dao')\n<mask token>\n\n\nclass FssFuzzHash:\n\n @staticmethod\n def insert_node(agent_id, data):\n return FssFuzzHashDao.insert_node(agent_id, data)\n", "step-4": "import sys\nsys.path.append('./dao')\nfrom fss_data_fuzzhash_dao import *\n\n\nclass FssFuzzHash:\n\n @staticmethod\n def insert_node(agent_id, data):\n return FssFuzzHashDao.insert_node(agent_id, data)\n", "step-5": "# -*- coding: utf-8 -*-\n\n# project: fshell\n# author: s0nnet\n# time: 2017-01-08\n# desc: data_fuzzhash\n\n\nimport sys\nsys.path.append(\"./dao\")\nfrom fss_data_fuzzhash_dao import *\n\n\nclass FssFuzzHash:\n \n @staticmethod\n def insert_node(agent_id, data):\n\n return FssFuzzHashDao.insert_node(agent_id, data)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from enum import Enum from app.utilities.data import Prefab class Tags(Enum): FLOW_CONTROL = 'Flow Control' MUSIC_SOUND = 'Music/Sound' PORTRAIT = 'Portrait' BG_FG = 'Background/Foreground' DIALOGUE_TEXT = 'Dialogue/Text' CURSOR_CAMERA = 'Cursor/Camera' LEVEL_VARS = 'Level-wide Unlocks and Variables' GAME_VARS = 'Game-wide Unlocks and Variables' TILEMAP = 'Tilemap' REGION = 'Region' ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units' MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties' UNIT_GROUPS = 'Unit Groups' MISCELLANEOUS = 'Miscellaneous' HIDDEN = 'Hidden' class EventCommand(Prefab): nid: str = None nickname: str = None tag: Tags = Tags.HIDDEN desc: str = '' keywords: list = [] optional_keywords: list = [] flags: list = [] values: list = [] display_values: list = [] def __init__(self, values=None, disp_values=None): self.values = values or [] self.display_values = disp_values or values or [] def save(self): # Don't bother saving display values if they are identical if self.display_values == self.values: return self.nid, self.values else: return self.nid, self.values, self.display_values def to_plain_text(self): if self.display_values: return ';'.join([self.nid] + self.display_values) else: return ';'.join([self.nid] + self.values) def __repr__(self): return self.to_plain_text() class Comment(EventCommand): nid = "comment" nickname = '#' tag = Tags.FLOW_CONTROL desc = \ """ **Lines** starting with '#' will be ignored. """ def to_plain_text(self): return self.values[0] class If(EventCommand): nid = "if" tag = Tags.FLOW_CONTROL desc = \ """ If the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false. Remember to end your **if** blocks with **end**. The indentation is not required, but is recommended for organization of the conditional blocks. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ keywords = ['Condition'] class Elif(EventCommand): nid = "elif" tag = Tags.FLOW_CONTROL desc = \ """ Works exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false. In the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ keywords = ['Condition'] class Else(EventCommand): nid = "else" tag = Tags.FLOW_CONTROL desc = \ """ Defines a block to be executed only if the previous **if** or **elif** returned false. Example: ``` if;game.check_dead('Eirika') lose_game elif;game.check_dead('Lyon') win_game else u;Eirika s;Eirika;Nice! r;Eirika end ``` """ class End(EventCommand): nid = "end" tag = Tags.FLOW_CONTROL desc = \ """ Ends a conditional block. Refer to the **if** command for more information. """ class Break(EventCommand): nid = "break" tag = Tags.FLOW_CONTROL desc = \ """ Immediately ends the current event. """ class Wait(EventCommand): nid = "wait" tag = Tags.FLOW_CONTROL desc = \ """ Pauses the execution of the script for _Time_ milliseconds. Often used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene. """ keywords = ['Time'] class EndSkip(EventCommand): nid = "end_skip" tag = Tags.FLOW_CONTROL desc = \ """ If the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event. """ class Music(EventCommand): nid = "music" nickname = "m" tag = Tags.MUSIC_SOUND desc = \ """ Fades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds. """ keywords = ['Music'] optional_keywords = ['Time'] # How long to fade in (default 400) class MusicClear(EventCommand): nid = "music_clear" tag = Tags.MUSIC_SOUND desc = \ """ Fades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds. """ optional_keywords = ['Time'] # How long to fade out class Sound(EventCommand): nid = "sound" tag = Tags.MUSIC_SOUND desc = \ """ Plays the _Sound_ once. """ keywords = ['Sound'] class ChangeMusic(EventCommand): nid = 'change_music' tag = Tags.MUSIC_SOUND desc = \ """ Changes the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter. """ keywords = ['PhaseMusic', 'Music'] class AddPortrait(EventCommand): nid = "add_portrait" nickname = "u" tag = Tags.PORTRAIT desc = \ """ Adds a portrait to the screen. Extra flags: 1. _mirror_: Portrait will face opposite expected direction. 2. _low_priority_: Portrait will appear behind all other portraits on the screen. 3. _immediate_: Portrait will not fade in. 4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so. """ keywords = ['Portrait', 'ScreenPosition'] optional_keywords = ['Slide', 'ExpressionList'] flags = ["mirror", "low_priority", "immediate", "no_block"] class MultiAddPortrait(EventCommand): nid = "multi_add_portrait" nickname = "uu" tag = Tags.PORTRAIT desc = \ """ Adds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input. """ keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition'] optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition'] class RemovePortrait(EventCommand): nid = "remove_portrait" nickname = "r" tag = Tags.PORTRAIT keywords = ['Portrait'] flags = ["immediate", "no_block"] class MultiRemovePortrait(EventCommand): nid = "multi_remove_portrait" nickname = "rr" tag = Tags.PORTRAIT keywords = ['Portrait', 'Portrait'] optional_keywords = ['Portrait', 'Portrait'] class MovePortrait(EventCommand): nid = "move_portrait" tag = Tags.PORTRAIT keywords = ['Portrait', 'ScreenPosition'] flags = ["immediate", "no_block"] class BopPortrait(EventCommand): nid = "bop_portrait" nickname = "bop" tag = Tags.PORTRAIT keywords = ['Portrait'] flags = ["no_block"] class Expression(EventCommand): nid = "expression" nickname = "e" tag = Tags.PORTRAIT keywords = ['Portrait', 'ExpressionList'] class Speak(EventCommand): nid = "speak" nickname = "s" tag = Tags.DIALOGUE_TEXT keywords = ['Speaker', 'Text'] optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant'] flags = ['low_priority'] class Transition(EventCommand): nid = "transition" nickname = "t" tag = Tags.BG_FG optional_keywords = ['Direction', 'Speed', 'Color3'] class Background(EventCommand): # Also does remove background nid = "change_background" nickname = "b" tag = Tags.BG_FG optional_keywords = ['Panorama'] flags = ["keep_portraits"] class DispCursor(EventCommand): nid = "disp_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Bool"] class MoveCursor(EventCommand): nid = "move_cursor" nickname = "set_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class CenterCursor(EventCommand): nid = "center_cursor" tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class FlickerCursor(EventCommand): nid = 'flicker_cursor' nickname = 'highlight' tag = Tags.CURSOR_CAMERA keywords = ["Position"] flags = ["immediate"] class GameVar(EventCommand): nid = 'game_var' tag = Tags.GAME_VARS keywords = ["Nid", "Condition"] class IncGameVar(EventCommand): nid = 'inc_game_var' tag = Tags.GAME_VARS keywords = ["Nid"] optional_keywords = ["Condition"] class LevelVar(EventCommand): nid = 'level_var' tag = Tags.LEVEL_VARS keywords = ["Nid", "Condition"] class IncLevelVar(EventCommand): nid = 'inc_level_var' tag = Tags.LEVEL_VARS keywords = ["Nid"] optional_keywords = ["Condition"] class WinGame(EventCommand): nid = 'win_game' tag = Tags.LEVEL_VARS class LoseGame(EventCommand): nid = 'lose_game' tag = Tags.LEVEL_VARS class ActivateTurnwheel(EventCommand): nid = 'activate_turnwheel' tag = Tags.MISCELLANEOUS # Whether to force the player to move the turnwheel back # defaults to true optional_keywords = ['Bool'] class BattleSave(EventCommand): nid = 'battle_save' tag = Tags.MISCELLANEOUS class ChangeTilemap(EventCommand): nid = 'change_tilemap' tag = Tags.TILEMAP keywords = ["Tilemap"] # How much to offset placed units by # Which tilemap to load the unit positions from optional_keywords = ["PositionOffset", "Tilemap"] flags = ["reload"] # Should place units in previously recorded positions class LoadUnit(EventCommand): nid = 'load_unit' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["UniqueUnit"] optional_keywords = ["Team", "AI"] class MakeGeneric(EventCommand): nid = 'make_generic' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS # Nid, class, level, team, ai, faction, anim variant keywords = ["String", "Klass", "String", "Team"] optional_keywords = ["AI", "Faction", "String", "ItemList"] class CreateUnit(EventCommand): nid = 'create_unit' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS # Unit template and new unit nid (can be '') keywords = ["Unit", "String"] # Unit level, position, entrytype, placement optional_keywords = ["String", "Position", "EntryType", "Placement"] class AddUnit(EventCommand): nid = 'add_unit' nickname = 'add' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["Position", "EntryType", "Placement"] class MoveUnit(EventCommand): nid = 'move_unit' nickname = 'move' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["Position", "MovementType", "Placement"] flags = ['no_block', 'no_follow'] class RemoveUnit(EventCommand): nid = 'remove_unit' nickname = 'remove' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] optional_keywords = ["RemoveType"] class KillUnit(EventCommand): nid = 'kill_unit' nickname = 'kill' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit"] flags = ['immediate'] class RemoveAllUnits(EventCommand): nid = 'remove_all_units' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS class RemoveAllEnemies(EventCommand): nid = 'remove_all_enemies' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS class InteractUnit(EventCommand): nid = 'interact_unit' nickname = 'interact' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["Unit", "Unit"] optional_keywords = ["CombatScript", "Ability"] class SetCurrentHP(EventCommand): nid = 'set_current_hp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit", "PositiveInteger"] class SetCurrentMana(EventCommand): nid = 'set_current_mana' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit", "PositiveInteger"] class Resurrect(EventCommand): nid = 'resurrect' tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS keywords = ["GlobalUnit"] class Reset(EventCommand): nid = 'reset' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit"] class HasAttacked(EventCommand): nid = 'has_attacked' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["Unit"] class HasTraded(EventCommand): nid = 'has_traded' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ['Unit'] class AddGroup(EventCommand): nid = 'add_group' tag = Tags.UNIT_GROUPS keywords = ["Group"] optional_keywords = ["StartingGroup", "EntryType", "Placement"] flags = ["create"] class SpawnGroup(EventCommand): nid = 'spawn_group' tag = Tags.UNIT_GROUPS keywords = ["Group", "CardinalDirection", "StartingGroup"] optional_keywords = ["EntryType", "Placement"] flags = ["create", "no_block", 'no_follow'] class MoveGroup(EventCommand): nid = 'move_group' nickname = 'morph_group' tag = Tags.UNIT_GROUPS keywords = ["Group", "StartingGroup"] optional_keywords = ["MovementType", "Placement"] flags = ['no_block', 'no_follow'] class RemoveGroup(EventCommand): nid = 'remove_group' tag = Tags.UNIT_GROUPS keywords = ["Group"] optional_keywords = ["RemoveType"] class GiveItem(EventCommand): nid = 'give_item' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Item"] flags = ['no_banner', 'no_choice', 'droppable'] class RemoveItem(EventCommand): nid = 'remove_item' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Item"] flags = ['no_banner'] class GiveMoney(EventCommand): nid = 'give_money' tag = Tags.GAME_VARS keywords = ["Integer"] optional_keywords = ["Party"] flags = ['no_banner'] class GiveBexp(EventCommand): nid = 'give_bexp' tag = Tags.GAME_VARS keywords = ["Condition"] optional_keywords = ["Party", "String"] flags = ['no_banner'] class GiveExp(EventCommand): nid = 'give_exp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PositiveInteger"] class SetExp(EventCommand): nid = 'set_exp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PositiveInteger"] class GiveWexp(EventCommand): nid = 'give_wexp' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "WeaponType", "Integer"] flags = ['no_banner'] class GiveSkill(EventCommand): nid = 'give_skill' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Skill"] flags = ['no_banner'] class RemoveSkill(EventCommand): nid = 'remove_skill' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Skill"] flags = ['no_banner'] class ChangeAI(EventCommand): nid = 'change_ai' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "AI"] class ChangeTeam(EventCommand): nid = 'change_team' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Team"] class ChangePortrait(EventCommand): nid = 'change_portrait' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "PortraitNid"] class ChangeStats(EventCommand): nid = 'change_stats' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "StatList"] flags = ['immediate'] class SetStats(EventCommand): nid = 'set_stats' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "StatList"] flags = ['immediate'] class AutolevelTo(EventCommand): nid = 'autolevel_to' tag = Tags.MODIFY_UNIT_PROPERTIES # Second argument is level that is eval'd keywords = ["GlobalUnit", "String"] # Whether to actually change the unit's level flags = ["hidden"] class SetModeAutolevels(EventCommand): nid = 'set_mode_autolevels' tag = Tags.GAME_VARS keywords = ["String"] # Whether to actually change the unit's level flags = ["hidden"] class Promote(EventCommand): nid = 'promote' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit"] optional_keywords = ["Klass"] class ChangeClass(EventCommand): nid = 'change_class' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit"] optional_keywords = ["Klass"] class AddTag(EventCommand): nid = 'add_tag' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Tag"] class RemoveTag(EventCommand): nid = 'remove_tag' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ["GlobalUnit", "Tag"] class AddTalk(EventCommand): nid = 'add_talk' tag = Tags.LEVEL_VARS keywords = ["Unit", "Unit"] class RemoveTalk(EventCommand): nid = 'remove_talk' tag = Tags.LEVEL_VARS keywords = ["Unit", "Unit"] class AddLore(EventCommand): nid = 'add_lore' nickname = 'unlock_lore' tag = Tags.GAME_VARS keywords = ["Lore"] class RemoveLore(EventCommand): nid = 'remove_lore' tag = Tags.GAME_VARS keywords = ["Lore"] class AddBaseConvo(EventCommand): nid = 'add_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class IgnoreBaseConvo(EventCommand): nid = 'ignore_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class RemoveBaseConvo(EventCommand): nid = 'remove_base_convo' tag = Tags.LEVEL_VARS keywords = ["String"] class IncrementSupportPoints(EventCommand): nid = 'increment_support_points' tag = Tags.MODIFY_UNIT_PROPERTIES keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger'] class AddMarketItem(EventCommand): nid = 'add_market_item' tag = Tags.GAME_VARS keywords = ["Item"] class RemoveMarketItem(EventCommand): nid = 'remove_market_item' tag = Tags.GAME_VARS keywords = ["Item"] class AddRegion(EventCommand): nid = 'add_region' tag = Tags.REGION keywords = ["Nid", "Position", "Size", "RegionType"] optional_keywords = ["String"] flags = ["only_once"] class RegionCondition(EventCommand): nid = 'region_condition' tag = Tags.REGION keywords = ["Nid", "Condition"] class RemoveRegion(EventCommand): nid = 'remove_region' tag = Tags.REGION keywords = ["Nid"] class ShowLayer(EventCommand): nid = 'show_layer' tag = Tags.TILEMAP keywords = ["Layer"] optional_keywords = ["LayerTransition"] class HideLayer(EventCommand): nid = 'hide_layer' tag = Tags.TILEMAP keywords = ["Layer"] optional_keywords = ["LayerTransition"] class AddWeather(EventCommand): nid = 'add_weather' tag = Tags.TILEMAP keywords = ["Weather"] class RemoveWeather(EventCommand): nid = 'remove_weather' tag = Tags.TILEMAP keywords = ["Weather"] class ChangeObjectiveSimple(EventCommand): nid = 'change_objective_simple' tag = Tags.LEVEL_VARS keywords = ["String"] class ChangeObjectiveWin(EventCommand): nid = 'change_objective_win' tag = Tags.LEVEL_VARS keywords = ["String"] class ChangeObjectiveLoss(EventCommand): nid = 'change_objective_loss' tag = Tags.LEVEL_VARS keywords = ["String"] class SetPosition(EventCommand): nid = 'set_position' tag = Tags.MISCELLANEOUS keywords = ["String"] class MapAnim(EventCommand): nid = 'map_anim' tag = Tags.TILEMAP keywords = ["MapAnim", "Position"] flags = ["no_block"] class ArrangeFormation(EventCommand): nid = 'arrange_formation' tag = Tags.MISCELLANEOUS # Puts units on formation tiles automatically class Prep(EventCommand): nid = 'prep' tag = Tags.MISCELLANEOUS optional_keywords = ["Bool", "Music"] # Pick units class Base(EventCommand): nid = 'base' tag = Tags.MISCELLANEOUS keywords = ["Panorama"] optional_keywords = ["Music"] class Shop(EventCommand): nid = 'shop' tag = Tags.MISCELLANEOUS keywords = ["Unit", "ItemList"] optional_keywords = ["ShopFlavor"] class Choice(EventCommand): nid = 'choice' tag = Tags.MISCELLANEOUS keywords = ['Nid', 'String', 'StringList'] optional_keywords = ['Orientation'] class ChapterTitle(EventCommand): nid = 'chapter_title' tag = Tags.MISCELLANEOUS optional_keywords = ["Music", "String"] class Alert(EventCommand): nid = 'alert' tag = Tags.DIALOGUE_TEXT keywords = ["String"] class VictoryScreen(EventCommand): nid = 'victory_screen' tag = Tags.MISCELLANEOUS class RecordsScreen(EventCommand): nid = 'records_screen' tag = Tags.MISCELLANEOUS class LocationCard(EventCommand): nid = 'location_card' tag = Tags.DIALOGUE_TEXT keywords = ["String"] class Credits(EventCommand): nid = 'credits' tag = Tags.DIALOGUE_TEXT keywords = ["String", "String"] flags = ['wait', 'center', 'no_split'] class Ending(EventCommand): nid = 'ending' tag = Tags.DIALOGUE_TEXT keywords = ["Portrait", "String", "String"] class PopDialog(EventCommand): nid = 'pop_dialog' tag = Tags.DIALOGUE_TEXT desc = \ """ Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition. Example: ``` ending;Coyote;Coyote, Man of Mystery;Too mysterious for words. transition;Close pop_dialog transition;Open ``` """ class Unlock(EventCommand): nid = 'unlock' tag = Tags.REGION keywords = ["Unit"] class FindUnlock(EventCommand): nid = 'find_unlock' tag = Tags.HIDDEN keywords = ["Unit"] class SpendUnlock(EventCommand): nid = 'spend_unlock' tag = Tags.HIDDEN keywords = ["Unit"] class TriggerScript(EventCommand): nid = 'trigger_script' tag = Tags.MISCELLANEOUS keywords = ["Event"] optional_keywords = ["GlobalUnit", "GlobalUnit"] class ChangeRoaming(EventCommand): nid = 'change_roaming' tag = Tags.MISCELLANEOUS desc = "Turn free roam mode on or off" keywords = ["Bool"] class ChangeRoamingUnit(EventCommand): nid = 'change_roaming_unit' tag = Tags.MISCELLANEOUS desc = "Changes the level's current roaming unit." keywords = ["Unit"] class CleanUpRoaming(EventCommand): nid = 'clean_up_roaming' tag = Tags.MISCELLANEOUS desc = "Removes all units other than the roaming unit" keywords = [] class AddToInitiative(EventCommand): nid = 'add_to_initiative' tag = Tags.MISCELLANEOUS desc = "Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position." keywords = ["Unit", "Integer"] class MoveInInitiative(EventCommand): nid = 'move_in_initiative' tag = Tags.MISCELLANEOUS desc = "Moves the initiative of the specified unit." keywords = ["Unit", "Integer"] def get_commands(): return EventCommand.__subclasses__() def restore_command(dat): if len(dat) == 2: nid, values = dat display_values = None elif len(dat) == 3: nid, values, display_values = dat subclasses = EventCommand.__subclasses__() for command in subclasses: if command.nid == nid: copy = command(values, display_values) return copy print("Couldn't restore event command!") print(nid, values, display_values) return None def parse_text(text): if text.startswith('#'): return Comment([text]) arguments = text.split(';') command_nid = arguments[0] subclasses = EventCommand.__subclasses__() for command in subclasses: if command.nid == command_nid or command.nickname == command_nid: cmd_args = arguments[1:] true_cmd_args = [] command_info = command() for idx, arg in enumerate(cmd_args): if idx < len(command_info.keywords): cmd_keyword = command_info.keywords[idx] elif idx - len(command_info.keywords) < len(command_info.optional_keywords): cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)] else: cmd_keyword = "N/A" # if parentheses exists, then they contain the "true" arg, with everything outside parens essentially as comments if '(' in arg and ')' in arg and not cmd_keyword == 'Condition': true_arg = arg[arg.find("(")+1:arg.find(")")] true_cmd_args.append(true_arg) else: true_cmd_args.append(arg) copy = command(true_cmd_args, cmd_args) return copy return None def parse(command): values = command.values num_keywords = len(command.keywords) true_values = values[:num_keywords] flags = {v for v in values[num_keywords:] if v in command.flags} optional_keywords = [v for v in values[num_keywords:] if v not in flags] true_values += optional_keywords return true_values, flags
normal
{ "blob_id": "c2dba981b0d628aebdf8cebfb890aad74a629b08", "index": 7365, "step-1": "<mask token>\n\n\nclass GiveExp(EventCommand):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Sound(EventCommand):\n nid = 'sound'\n tag = Tags.MUSIC_SOUND\n desc = '\\nPlays the _Sound_ once.\\n '\n keywords = ['Sound']\n\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n desc = \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n keywords = ['PhaseMusic', 'Music']\n\n\nclass AddPortrait(EventCommand):\n nid = 'add_portrait'\n nickname = 'u'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = ['mirror', 'low_priority', 'immediate', 'no_block']\n\n\nclass MultiAddPortrait(EventCommand):\n nid = 'multi_add_portrait'\n nickname = 'uu'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait',\n 'ScreenPosition']\n\n\nclass RemovePortrait(EventCommand):\n nid = 'remove_portrait'\n nickname = 'r'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['immediate', 'no_block']\n\n\nclass MultiRemovePortrait(EventCommand):\n nid = 'multi_remove_portrait'\n nickname = 'rr'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\n\nclass MovePortrait(EventCommand):\n nid = 'move_portrait'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ScreenPosition']\n flags = ['immediate', 'no_block']\n\n\nclass BopPortrait(EventCommand):\n nid = 'bop_portrait'\n nickname = 'bop'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['no_block']\n\n\nclass Expression(EventCommand):\n nid = 'expression'\n nickname = 'e'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ExpressionList']\n\n\nclass Speak(EventCommand):\n nid = 'speak'\n nickname = 's'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\n\nclass Transition(EventCommand):\n nid = 'transition'\n nickname = 't'\n tag = Tags.BG_FG\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\n\nclass Background(EventCommand):\n nid = 'change_background'\n nickname = 'b'\n tag = Tags.BG_FG\n optional_keywords = ['Panorama']\n flags = ['keep_portraits']\n\n\nclass DispCursor(EventCommand):\n nid = 'disp_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Bool']\n\n\nclass MoveCursor(EventCommand):\n nid = 'move_cursor'\n nickname = 'set_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass CenterCursor(EventCommand):\n nid = 'center_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n", "step-5": "from enum import Enum\nfrom app.utilities.data import Prefab\n\nclass Tags(Enum):\n FLOW_CONTROL = 'Flow Control'\n MUSIC_SOUND = 'Music/Sound'\n PORTRAIT = 'Portrait'\n BG_FG = 'Background/Foreground'\n DIALOGUE_TEXT = 'Dialogue/Text'\n CURSOR_CAMERA = 'Cursor/Camera'\n LEVEL_VARS = 'Level-wide Unlocks and Variables'\n GAME_VARS = 'Game-wide Unlocks and Variables'\n TILEMAP = 'Tilemap'\n REGION = 'Region'\n ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units'\n MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties'\n UNIT_GROUPS = 'Unit Groups'\n MISCELLANEOUS = 'Miscellaneous'\n HIDDEN = 'Hidden'\n\nclass EventCommand(Prefab):\n nid: str = None\n nickname: str = None\n tag: Tags = Tags.HIDDEN\n desc: str = ''\n\n keywords: list = []\n optional_keywords: list = []\n flags: list = []\n\n values: list = []\n display_values: list = []\n\n def __init__(self, values=None, disp_values=None):\n self.values = values or []\n self.display_values = disp_values or values or []\n\n def save(self):\n # Don't bother saving display values if they are identical\n if self.display_values == self.values:\n return self.nid, self.values\n else:\n return self.nid, self.values, self.display_values\n\n def to_plain_text(self):\n if self.display_values:\n return ';'.join([self.nid] + self.display_values)\n else:\n return ';'.join([self.nid] + self.values)\n\n def __repr__(self):\n return self.to_plain_text()\n\nclass Comment(EventCommand):\n nid = \"comment\"\n nickname = '#'\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\n**Lines** starting with '#' will be ignored.\n \"\"\"\n\n def to_plain_text(self):\n return self.values[0]\n\nclass If(EventCommand):\n nid = \"if\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false.\n\nRemember to end your **if** blocks with **end**.\n\nThe indentation is not required, but is recommended for organization of the conditional blocks.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Elif(EventCommand):\n nid = \"elif\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nWorks exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false.\n\nIn the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Else(EventCommand):\n nid = \"else\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nDefines a block to be executed only if the previous **if** or **elif** returned false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\nclass End(EventCommand):\n nid = \"end\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nEnds a conditional block. Refer to the **if** command for more information.\n \"\"\"\n\nclass Break(EventCommand):\n nid = \"break\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nImmediately ends the current event.\n \"\"\"\n\n\nclass Wait(EventCommand):\n nid = \"wait\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nPauses the execution of the script for _Time_ milliseconds.\n\nOften used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene.\n \"\"\"\n\n keywords = ['Time']\n\nclass EndSkip(EventCommand):\n nid = \"end_skip\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event.\n \"\"\"\n\nclass Music(EventCommand):\n nid = \"music\"\n nickname = \"m\"\n tag = Tags.MUSIC_SOUND\n desc = \\\n \"\"\"\nFades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds.\n \"\"\"\n\n keywords = ['Music']\n optional_keywords = ['Time'] # How long to fade in (default 400)\n\nclass MusicClear(EventCommand):\n nid = \"music_clear\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nFades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds.\n \"\"\"\n\n optional_keywords = ['Time'] # How long to fade out\n\nclass Sound(EventCommand):\n nid = \"sound\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nPlays the _Sound_ once.\n \"\"\"\n\n keywords = ['Sound']\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n\n keywords = ['PhaseMusic', 'Music']\n\nclass AddPortrait(EventCommand):\n nid = \"add_portrait\"\n nickname = \"u\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = [\"mirror\", \"low_priority\", \"immediate\", \"no_block\"]\n\nclass MultiAddPortrait(EventCommand):\n nid = \"multi_add_portrait\"\n nickname = \"uu\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n\nclass RemovePortrait(EventCommand):\n nid = \"remove_portrait\"\n nickname = \"r\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"immediate\", \"no_block\"]\n\nclass MultiRemovePortrait(EventCommand):\n nid = \"multi_remove_portrait\"\n nickname = \"rr\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\nclass MovePortrait(EventCommand):\n nid = \"move_portrait\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ScreenPosition']\n flags = [\"immediate\", \"no_block\"]\n\nclass BopPortrait(EventCommand):\n nid = \"bop_portrait\"\n nickname = \"bop\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"no_block\"]\n\nclass Expression(EventCommand):\n nid = \"expression\"\n nickname = \"e\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ExpressionList']\n\nclass Speak(EventCommand):\n nid = \"speak\"\n nickname = \"s\"\n tag = Tags.DIALOGUE_TEXT\n\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\nclass Transition(EventCommand):\n nid = \"transition\"\n nickname = \"t\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\nclass Background(EventCommand):\n # Also does remove background\n nid = \"change_background\"\n nickname = \"b\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Panorama']\n flags = [\"keep_portraits\"]\n\nclass DispCursor(EventCommand):\n nid = \"disp_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Bool\"]\n\nclass MoveCursor(EventCommand):\n nid = \"move_cursor\"\n nickname = \"set_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass CenterCursor(EventCommand):\n nid = \"center_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n\n # Whether to force the player to move the turnwheel back\n # defaults to true\n optional_keywords = ['Bool']\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n\n keywords = [\"Tilemap\"]\n # How much to offset placed units by\n # Which tilemap to load the unit positions from\n optional_keywords = [\"PositionOffset\", \"Tilemap\"]\n flags = [\"reload\"] # Should place units in previously recorded positions\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"UniqueUnit\"]\n optional_keywords = [\"Team\", \"AI\"]\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n # Nid, class, level, team, ai, faction, anim variant\n keywords = [\"String\", \"Klass\", \"String\", \"Team\"]\n optional_keywords = [\"AI\", \"Faction\", \"String\", \"ItemList\"]\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n # Unit template and new unit nid (can be '')\n keywords = [\"Unit\", \"String\"]\n # Unit level, position, entrytype, placement\n optional_keywords = [\"String\", \"Position\", \"EntryType\", \"Placement\"]\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"EntryType\", \"Placement\"]\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"RemoveType\"]\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n flags = ['immediate']\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\", \"Unit\"]\n optional_keywords = [\"CombatScript\", \"Ability\"]\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = [\"GlobalUnit\"]\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"StartingGroup\", \"EntryType\", \"Placement\"]\n flags = [\"create\"]\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"CardinalDirection\", \"StartingGroup\"]\n optional_keywords = [\"EntryType\", \"Placement\"]\n flags = [\"create\", \"no_block\", 'no_follow']\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"StartingGroup\"]\n optional_keywords = [\"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"RemoveType\"]\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner', 'no_choice', 'droppable']\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner']\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n\n keywords = [\"Integer\"]\n optional_keywords = [\"Party\"]\n flags = ['no_banner']\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n\n keywords = [\"Condition\"]\n optional_keywords = [\"Party\", \"String\"]\n flags = ['no_banner']\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"WeaponType\", \"Integer\"]\n flags = ['no_banner']\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"AI\"]\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"Team\"]\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"PortraitNid\"]\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n # Second argument is level that is eval'd\n keywords = [\"GlobalUnit\", \"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = [\"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Position\", \"Size\", \"RegionType\"]\n optional_keywords = [\"String\"]\n flags = [\"only_once\"]\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\"]\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"String\"]\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n\n keywords = [\"MapAnim\", \"Position\"]\n flags = [\"no_block\"]\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n # Puts units on formation tiles automatically\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Bool\", \"Music\"] # Pick units\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Panorama\"]\n optional_keywords = [\"Music\"]\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Unit\", \"ItemList\"]\n optional_keywords = [\"ShopFlavor\"]\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Music\", \"String\"]\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\", \"String\"]\n flags = ['wait', 'center', 'no_split']\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"Portrait\", \"String\", \"String\"]\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \\\n \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n\n keywords = [\"Unit\"]\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Event\"]\n optional_keywords = [\"GlobalUnit\", \"GlobalUnit\"]\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Turn free roam mode on or off\"\n\n keywords = [\"Bool\"]\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n\n keywords = [\"Unit\"]\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Removes all units other than the roaming unit\"\n\n keywords = []\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Moves the initiative of the specified unit.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\ndef get_commands():\n return EventCommand.__subclasses__()\n\ndef restore_command(dat):\n if len(dat) == 2:\n nid, values = dat\n display_values = None\n elif len(dat) == 3:\n nid, values, display_values = dat\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == nid:\n copy = command(values, display_values)\n return copy\n print(\"Couldn't restore event command!\")\n print(nid, values, display_values)\n return None\n\ndef parse_text(text):\n if text.startswith('#'):\n return Comment([text])\n arguments = text.split(';')\n command_nid = arguments[0]\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == command_nid or command.nickname == command_nid:\n cmd_args = arguments[1:]\n true_cmd_args = []\n command_info = command()\n for idx, arg in enumerate(cmd_args):\n if idx < len(command_info.keywords):\n cmd_keyword = command_info.keywords[idx]\n elif idx - len(command_info.keywords) < len(command_info.optional_keywords):\n cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)]\n else:\n cmd_keyword = \"N/A\"\n # if parentheses exists, then they contain the \"true\" arg, with everything outside parens essentially as comments\n if '(' in arg and ')' in arg and not cmd_keyword == 'Condition':\n true_arg = arg[arg.find(\"(\")+1:arg.find(\")\")]\n true_cmd_args.append(true_arg)\n else:\n true_cmd_args.append(arg)\n copy = command(true_cmd_args, cmd_args)\n return copy\n return None\n\ndef parse(command):\n values = command.values\n num_keywords = len(command.keywords)\n true_values = values[:num_keywords]\n flags = {v for v in values[num_keywords:] if v in command.flags}\n optional_keywords = [v for v in values[num_keywords:] if v not in flags]\n true_values += optional_keywords\n return true_values, flags\n", "step-ids": [ 119, 154, 180, 218, 252 ] }
[ 119, 154, 180, 218, 252 ]
from five import grok from zope.formlib import form from zope import schema from zope.interface import implements from zope.component import getMultiAdapter from plone.app.portlets.portlets import base from plone.memoize.instance import memoize from plone.portlets.interfaces import IPortletDataProvider from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Products.CMFCore.utils import getToolByName #grok.templatedir('templates') class IContentNavigation(IPortletDataProvider): portlet_header = schema.TextLine( title = u"Portlet Header", default = u"TWITTER FEED", required = False ) twitter_username = schema.TextLine( title = u"Twitter Username", default = u"isclimatechange" ) twitter_widgetId = schema.TextLine( title = u"Twitter Widget ID", default = u"565570873433006080" ) class Assignment(base.Assignment): implements(IContentNavigation) def __init__(self,portlet_header=None, twitter_username= None, twitter_widgetId=None): self.portlet_header = portlet_header self.twitter_username = twitter_username self.twitter_widgetId = twitter_widgetId @property def title(self): return self.portlet_header class Renderer(base.Renderer): render = ViewPageTemplateFile('twitterportlet.pt') def __init__(self, context, request, view, manager, data): self.context = context self.request = request self.view = view self.manager = manager self.data = data def contents(self): return self.data class AddForm(base.AddForm): form_fields = form.Fields(IContentNavigation) label = u"Add Twitter Portlet" description = '' def create(self, data): assignment = Assignment() form.applyChanges(assignment, self.form_fields, data) return assignment class EditForm(base.EditForm): form_fields = form.Fields(IContentNavigation) label = u"Edit Twitter Portlet" description = ''
normal
{ "blob_id": "214585956e44ce006db0702fd23692b11459f9e1", "index": 7664, "step-1": "<mask token>\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n\n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = request\n self.view = view\n self.manager = manager\n self.data = data\n\n def contents(self):\n return self.data\n\n\nclass AddForm(base.AddForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Add Twitter Portlet'\n description = ''\n\n def create(self, data):\n assignment = Assignment()\n form.applyChanges(assignment, self.form_fields, data)\n return assignment\n\n\nclass EditForm(base.EditForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Edit Twitter Portlet'\n description = ''\n", "step-2": "<mask token>\n\n\nclass Assignment(base.Assignment):\n implements(IContentNavigation)\n <mask token>\n <mask token>\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n\n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = request\n self.view = view\n self.manager = manager\n self.data = data\n\n def contents(self):\n return self.data\n\n\nclass AddForm(base.AddForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Add Twitter Portlet'\n description = ''\n\n def create(self, data):\n assignment = Assignment()\n form.applyChanges(assignment, self.form_fields, data)\n return assignment\n\n\nclass EditForm(base.EditForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Edit Twitter Portlet'\n description = ''\n", "step-3": "<mask token>\n\n\nclass IContentNavigation(IPortletDataProvider):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Assignment(base.Assignment):\n implements(IContentNavigation)\n\n def __init__(self, portlet_header=None, twitter_username=None,\n twitter_widgetId=None):\n self.portlet_header = portlet_header\n self.twitter_username = twitter_username\n self.twitter_widgetId = twitter_widgetId\n\n @property\n def title(self):\n return self.portlet_header\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n\n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = request\n self.view = view\n self.manager = manager\n self.data = data\n\n def contents(self):\n return self.data\n\n\nclass AddForm(base.AddForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Add Twitter Portlet'\n description = ''\n\n def create(self, data):\n assignment = Assignment()\n form.applyChanges(assignment, self.form_fields, data)\n return assignment\n\n\nclass EditForm(base.EditForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Edit Twitter Portlet'\n description = ''\n", "step-4": "from five import grok\nfrom zope.formlib import form\nfrom zope import schema\nfrom zope.interface import implements\nfrom zope.component import getMultiAdapter\nfrom plone.app.portlets.portlets import base\nfrom plone.memoize.instance import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom Products.CMFCore.utils import getToolByName\n\n\nclass IContentNavigation(IPortletDataProvider):\n portlet_header = schema.TextLine(title=u'Portlet Header', default=\n u'TWITTER FEED', required=False)\n twitter_username = schema.TextLine(title=u'Twitter Username', default=\n u'isclimatechange')\n twitter_widgetId = schema.TextLine(title=u'Twitter Widget ID', default=\n u'565570873433006080')\n\n\nclass Assignment(base.Assignment):\n implements(IContentNavigation)\n\n def __init__(self, portlet_header=None, twitter_username=None,\n twitter_widgetId=None):\n self.portlet_header = portlet_header\n self.twitter_username = twitter_username\n self.twitter_widgetId = twitter_widgetId\n\n @property\n def title(self):\n return self.portlet_header\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n\n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = request\n self.view = view\n self.manager = manager\n self.data = data\n\n def contents(self):\n return self.data\n\n\nclass AddForm(base.AddForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Add Twitter Portlet'\n description = ''\n\n def create(self, data):\n assignment = Assignment()\n form.applyChanges(assignment, self.form_fields, data)\n return assignment\n\n\nclass EditForm(base.EditForm):\n form_fields = form.Fields(IContentNavigation)\n label = u'Edit Twitter Portlet'\n description = ''\n", "step-5": "from five import grok\nfrom zope.formlib import form\nfrom zope import schema\nfrom zope.interface import implements\nfrom zope.component import getMultiAdapter\nfrom plone.app.portlets.portlets import base\nfrom plone.memoize.instance import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom Products.CMFCore.utils import getToolByName\n\n\n#grok.templatedir('templates')\n\nclass IContentNavigation(IPortletDataProvider):\n \n portlet_header = schema.TextLine(\n title = u\"Portlet Header\",\n default = u\"TWITTER FEED\",\n required = False\n )\n\n twitter_username = schema.TextLine(\n title = u\"Twitter Username\",\n default = u\"isclimatechange\"\n )\n\n twitter_widgetId = schema.TextLine(\n title = u\"Twitter Widget ID\",\n default = u\"565570873433006080\"\n )\n\nclass Assignment(base.Assignment):\n implements(IContentNavigation)\n \n \n def __init__(self,portlet_header=None, twitter_username= None, twitter_widgetId=None):\n self.portlet_header = portlet_header\n self.twitter_username = twitter_username\n self.twitter_widgetId = twitter_widgetId\n \n @property\n def title(self):\n return self.portlet_header\n \n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n \n \n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = request\n self.view = view\n self.manager = manager\n self.data = data\n \n \n def contents(self):\n return self.data\n\n \n \n\nclass AddForm(base.AddForm):\n form_fields = form.Fields(IContentNavigation)\n label = u\"Add Twitter Portlet\"\n description = ''\n \n def create(self, data):\n assignment = Assignment()\n form.applyChanges(assignment, self.form_fields, data)\n return assignment\n \n\nclass EditForm(base.EditForm):\n form_fields = form.Fields(IContentNavigation)\n label = u\"Edit Twitter Portlet\"\n description = ''\n", "step-ids": [ 9, 10, 13, 15, 16 ] }
[ 9, 10, 13, 15, 16 ]
from django.conf.urls import url from tree import views urlpatterns = [ url('/home', views.home), url('/about', views.about), ]
normal
{ "blob_id": "3313f01ed98433f4b150c4d8e877ac09eb8403b4", "index": 5652, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [url('/home', views.home), url('/about', views.about)]\n", "step-3": "from django.conf.urls import url\nfrom tree import views\nurlpatterns = [url('/home', views.home), url('/about', views.about)]\n", "step-4": "\nfrom django.conf.urls import url\nfrom tree import views\n\nurlpatterns = [\n url('/home', views.home),\n url('/about', views.about),\n]", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
"""Test cases for the __main__ module.""" import pytest from click.testing import CliRunner from skimpy import __main__ from skimpy import generate_test_data from skimpy import skim @pytest.fixture def runner() -> CliRunner: """Fixture for invoking command-line interfaces.""" return CliRunner() def test_main_succeeds(runner: CliRunner) -> None: """It exits with a status code of zero.""" with runner.isolated_filesystem(): df = generate_test_data() df.to_csv("test_file.csv", index=False) result = runner.invoke(__main__.main, ["test_file.csv"]) assert result.exit_code == 0 def test_000_basic_functionality() -> None: """Tests that a skim of the test data works.""" df = generate_test_data() skim(df) def test_001_colour_kwargs() -> None: """Tests that colour keyword arguments work.""" df = generate_test_data() skim(df, datetime="chartreuse1") def test_002_header_style() -> None: """Tests that the header style optional argument works.""" df = generate_test_data() skim(df, header_style="italic green") def test_003_not_enough_datetimes() -> None: """Tests logic branch with too few datetimes for freq inference.""" df = generate_test_data() df = df.head(2) skim(df) def test_004_when_df_is_named() -> None: """Tests what happens when df has a name.""" df = generate_test_data() df.name = "Named dataframe" skim(df)
normal
{ "blob_id": "97a51d959ad642467c508cedc8786f636e4050bb", "index": 1333, "step-1": "<mask token>\n\n\n@pytest.fixture\ndef runner() ->CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) ->None:\n \"\"\"It exits with a status code of zero.\"\"\"\n with runner.isolated_filesystem():\n df = generate_test_data()\n df.to_csv('test_file.csv', index=False)\n result = runner.invoke(__main__.main, ['test_file.csv'])\n assert result.exit_code == 0\n\n\n<mask token>\n\n\ndef test_002_header_style() ->None:\n \"\"\"Tests that the header style optional argument works.\"\"\"\n df = generate_test_data()\n skim(df, header_style='italic green')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@pytest.fixture\ndef runner() ->CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) ->None:\n \"\"\"It exits with a status code of zero.\"\"\"\n with runner.isolated_filesystem():\n df = generate_test_data()\n df.to_csv('test_file.csv', index=False)\n result = runner.invoke(__main__.main, ['test_file.csv'])\n assert result.exit_code == 0\n\n\ndef test_000_basic_functionality() ->None:\n \"\"\"Tests that a skim of the test data works.\"\"\"\n df = generate_test_data()\n skim(df)\n\n\ndef test_001_colour_kwargs() ->None:\n \"\"\"Tests that colour keyword arguments work.\"\"\"\n df = generate_test_data()\n skim(df, datetime='chartreuse1')\n\n\ndef test_002_header_style() ->None:\n \"\"\"Tests that the header style optional argument works.\"\"\"\n df = generate_test_data()\n skim(df, header_style='italic green')\n\n\n<mask token>\n\n\ndef test_004_when_df_is_named() ->None:\n \"\"\"Tests what happens when df has a name.\"\"\"\n df = generate_test_data()\n df.name = 'Named dataframe'\n skim(df)\n", "step-3": "<mask token>\n\n\n@pytest.fixture\ndef runner() ->CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) ->None:\n \"\"\"It exits with a status code of zero.\"\"\"\n with runner.isolated_filesystem():\n df = generate_test_data()\n df.to_csv('test_file.csv', index=False)\n result = runner.invoke(__main__.main, ['test_file.csv'])\n assert result.exit_code == 0\n\n\ndef test_000_basic_functionality() ->None:\n \"\"\"Tests that a skim of the test data works.\"\"\"\n df = generate_test_data()\n skim(df)\n\n\ndef test_001_colour_kwargs() ->None:\n \"\"\"Tests that colour keyword arguments work.\"\"\"\n df = generate_test_data()\n skim(df, datetime='chartreuse1')\n\n\ndef test_002_header_style() ->None:\n \"\"\"Tests that the header style optional argument works.\"\"\"\n df = generate_test_data()\n skim(df, header_style='italic green')\n\n\ndef test_003_not_enough_datetimes() ->None:\n \"\"\"Tests logic branch with too few datetimes for freq inference.\"\"\"\n df = generate_test_data()\n df = df.head(2)\n skim(df)\n\n\ndef test_004_when_df_is_named() ->None:\n \"\"\"Tests what happens when df has a name.\"\"\"\n df = generate_test_data()\n df.name = 'Named dataframe'\n skim(df)\n", "step-4": "<mask token>\nimport pytest\nfrom click.testing import CliRunner\nfrom skimpy import __main__\nfrom skimpy import generate_test_data\nfrom skimpy import skim\n\n\n@pytest.fixture\ndef runner() ->CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) ->None:\n \"\"\"It exits with a status code of zero.\"\"\"\n with runner.isolated_filesystem():\n df = generate_test_data()\n df.to_csv('test_file.csv', index=False)\n result = runner.invoke(__main__.main, ['test_file.csv'])\n assert result.exit_code == 0\n\n\ndef test_000_basic_functionality() ->None:\n \"\"\"Tests that a skim of the test data works.\"\"\"\n df = generate_test_data()\n skim(df)\n\n\ndef test_001_colour_kwargs() ->None:\n \"\"\"Tests that colour keyword arguments work.\"\"\"\n df = generate_test_data()\n skim(df, datetime='chartreuse1')\n\n\ndef test_002_header_style() ->None:\n \"\"\"Tests that the header style optional argument works.\"\"\"\n df = generate_test_data()\n skim(df, header_style='italic green')\n\n\ndef test_003_not_enough_datetimes() ->None:\n \"\"\"Tests logic branch with too few datetimes for freq inference.\"\"\"\n df = generate_test_data()\n df = df.head(2)\n skim(df)\n\n\ndef test_004_when_df_is_named() ->None:\n \"\"\"Tests what happens when df has a name.\"\"\"\n df = generate_test_data()\n df.name = 'Named dataframe'\n skim(df)\n", "step-5": "\"\"\"Test cases for the __main__ module.\"\"\"\nimport pytest\nfrom click.testing import CliRunner\n\nfrom skimpy import __main__\nfrom skimpy import generate_test_data\nfrom skimpy import skim\n\n\n@pytest.fixture\ndef runner() -> CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) -> None:\n \"\"\"It exits with a status code of zero.\"\"\"\n with runner.isolated_filesystem():\n df = generate_test_data()\n df.to_csv(\"test_file.csv\", index=False)\n result = runner.invoke(__main__.main, [\"test_file.csv\"])\n assert result.exit_code == 0\n\n\ndef test_000_basic_functionality() -> None:\n \"\"\"Tests that a skim of the test data works.\"\"\"\n df = generate_test_data()\n skim(df)\n\n\ndef test_001_colour_kwargs() -> None:\n \"\"\"Tests that colour keyword arguments work.\"\"\"\n df = generate_test_data()\n skim(df, datetime=\"chartreuse1\")\n\n\ndef test_002_header_style() -> None:\n \"\"\"Tests that the header style optional argument works.\"\"\"\n df = generate_test_data()\n skim(df, header_style=\"italic green\")\n\n\ndef test_003_not_enough_datetimes() -> None:\n \"\"\"Tests logic branch with too few datetimes for freq inference.\"\"\"\n df = generate_test_data()\n df = df.head(2)\n skim(df)\n\n\ndef test_004_when_df_is_named() -> None:\n \"\"\"Tests what happens when df has a name.\"\"\"\n df = generate_test_data()\n df.name = \"Named dataframe\"\n skim(df)\n", "step-ids": [ 3, 6, 7, 8, 9 ] }
[ 3, 6, 7, 8, 9 ]
# Generated by Django 3.2.6 on 2021-08-19 22:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chat', '0005_user_image'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', field=models.CharField(max_length=255, verbose_name='Имя'), ), migrations.AlterField( model_name='user', name='last_name', field=models.CharField(max_length=255, verbose_name='Фамилия'), ), ]
normal
{ "blob_id": "fac60a8967354e4f306b95fdb5c75d02dc2c1455", "index": 2247, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('chat', '0005_user_image')]\n operations = [migrations.AlterField(model_name='user', name=\n 'first_name', field=models.CharField(max_length=255, verbose_name=\n 'Имя')), migrations.AlterField(model_name='user', name='last_name',\n field=models.CharField(max_length=255, verbose_name='Фамилия'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('chat', '0005_user_image')]\n operations = [migrations.AlterField(model_name='user', name=\n 'first_name', field=models.CharField(max_length=255, verbose_name=\n 'Имя')), migrations.AlterField(model_name='user', name='last_name',\n field=models.CharField(max_length=255, verbose_name='Фамилия'))]\n", "step-5": "# Generated by Django 3.2.6 on 2021-08-19 22:01\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('chat', '0005_user_image'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='first_name',\n field=models.CharField(max_length=255, verbose_name='Имя'),\n ),\n migrations.AlterField(\n model_name='user',\n name='last_name',\n field=models.CharField(max_length=255, verbose_name='Фамилия'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from pymouse import PyMouse m = PyMouse() w,h = m.screen_size() class base_controller: def __init__(self): pass def move(self,xy:list): ''' 移动 ''' m.move(xy[0]*w,xy[1]*h) def click(self, xy:list): ''' 点击 ''' m.click(xy[0]*w,xy[1]*h) def scroll(self, marks:list): ''' 滚动 ''' d = marks[0][1] - marks[-1][1] R = 0.2 print(d) if d > R: m.scroll(-1) elif d < -R: m.scroll(1) def press(self, xy:list, ones = True): ''' 长按 ''' if ones: m.press(xy[0]*w,xy[1]*h) else: m.drag(xy[0]*w,xy[1]*h) def release(self, xy:list): ''' 松开 ''' m.release(xy[0]*w,xy[1]*h) class mac_controller(base_controller): def __init__(self): super(mac_controller, self).__init__()
normal
{ "blob_id": "b2f2f1e4b7070ac867b71e538f759e527eb1ffb9", "index": 416, "step-1": "<mask token>\n\n\nclass base_controller:\n <mask token>\n\n def move(self, xy: list):\n \"\"\"\n 移动\n \"\"\"\n m.move(xy[0] * w, xy[1] * h)\n\n def click(self, xy: list):\n \"\"\"\n 点击\n \"\"\"\n m.click(xy[0] * w, xy[1] * h)\n <mask token>\n <mask token>\n\n def release(self, xy: list):\n \"\"\"\n 松开\n \"\"\"\n m.release(xy[0] * w, xy[1] * h)\n\n\nclass mac_controller(base_controller):\n\n def __init__(self):\n super(mac_controller, self).__init__()\n", "step-2": "<mask token>\n\n\nclass base_controller:\n <mask token>\n\n def move(self, xy: list):\n \"\"\"\n 移动\n \"\"\"\n m.move(xy[0] * w, xy[1] * h)\n\n def click(self, xy: list):\n \"\"\"\n 点击\n \"\"\"\n m.click(xy[0] * w, xy[1] * h)\n\n def scroll(self, marks: list):\n \"\"\"\n 滚动\n \"\"\"\n d = marks[0][1] - marks[-1][1]\n R = 0.2\n print(d)\n if d > R:\n m.scroll(-1)\n elif d < -R:\n m.scroll(1)\n\n def press(self, xy: list, ones=True):\n \"\"\"\n 长按\n \"\"\"\n if ones:\n m.press(xy[0] * w, xy[1] * h)\n else:\n m.drag(xy[0] * w, xy[1] * h)\n\n def release(self, xy: list):\n \"\"\"\n 松开\n \"\"\"\n m.release(xy[0] * w, xy[1] * h)\n\n\nclass mac_controller(base_controller):\n\n def __init__(self):\n super(mac_controller, self).__init__()\n", "step-3": "<mask token>\nm = PyMouse()\nw, h = m.screen_size()\n\n\nclass base_controller:\n\n def __init__(self):\n pass\n\n def move(self, xy: list):\n \"\"\"\n 移动\n \"\"\"\n m.move(xy[0] * w, xy[1] * h)\n\n def click(self, xy: list):\n \"\"\"\n 点击\n \"\"\"\n m.click(xy[0] * w, xy[1] * h)\n\n def scroll(self, marks: list):\n \"\"\"\n 滚动\n \"\"\"\n d = marks[0][1] - marks[-1][1]\n R = 0.2\n print(d)\n if d > R:\n m.scroll(-1)\n elif d < -R:\n m.scroll(1)\n\n def press(self, xy: list, ones=True):\n \"\"\"\n 长按\n \"\"\"\n if ones:\n m.press(xy[0] * w, xy[1] * h)\n else:\n m.drag(xy[0] * w, xy[1] * h)\n\n def release(self, xy: list):\n \"\"\"\n 松开\n \"\"\"\n m.release(xy[0] * w, xy[1] * h)\n\n\nclass mac_controller(base_controller):\n\n def __init__(self):\n super(mac_controller, self).__init__()\n", "step-4": "from pymouse import PyMouse\nm = PyMouse()\nw, h = m.screen_size()\n\n\nclass base_controller:\n\n def __init__(self):\n pass\n\n def move(self, xy: list):\n \"\"\"\n 移动\n \"\"\"\n m.move(xy[0] * w, xy[1] * h)\n\n def click(self, xy: list):\n \"\"\"\n 点击\n \"\"\"\n m.click(xy[0] * w, xy[1] * h)\n\n def scroll(self, marks: list):\n \"\"\"\n 滚动\n \"\"\"\n d = marks[0][1] - marks[-1][1]\n R = 0.2\n print(d)\n if d > R:\n m.scroll(-1)\n elif d < -R:\n m.scroll(1)\n\n def press(self, xy: list, ones=True):\n \"\"\"\n 长按\n \"\"\"\n if ones:\n m.press(xy[0] * w, xy[1] * h)\n else:\n m.drag(xy[0] * w, xy[1] * h)\n\n def release(self, xy: list):\n \"\"\"\n 松开\n \"\"\"\n m.release(xy[0] * w, xy[1] * h)\n\n\nclass mac_controller(base_controller):\n\n def __init__(self):\n super(mac_controller, self).__init__()\n", "step-5": "from pymouse import PyMouse\nm = PyMouse()\nw,h = m.screen_size()\n\nclass base_controller:\n def __init__(self):\n pass\n\n def move(self,xy:list):\n '''\n 移动\n '''\n m.move(xy[0]*w,xy[1]*h)\n \n def click(self, xy:list):\n '''\n 点击\n '''\n m.click(xy[0]*w,xy[1]*h)\n \n def scroll(self, marks:list):\n '''\n 滚动\n '''\n d = marks[0][1] - marks[-1][1]\n R = 0.2\n print(d)\n if d > R:\n m.scroll(-1)\n elif d < -R:\n m.scroll(1)\n\n def press(self, xy:list, ones = True):\n '''\n 长按\n '''\n if ones:\n m.press(xy[0]*w,xy[1]*h)\n else:\n m.drag(xy[0]*w,xy[1]*h)\n\n def release(self, xy:list):\n '''\n 松开\n '''\n m.release(xy[0]*w,xy[1]*h)\n\n\nclass mac_controller(base_controller):\n def __init__(self):\n super(mac_controller, self).__init__()\n", "step-ids": [ 6, 8, 10, 11, 12 ] }
[ 6, 8, 10, 11, 12 ]
def count_words(word): count = 0 count = len(word.split()) return count if __name__ == '__main__': print count_words("Boj is dope")
normal
{ "blob_id": "9f3b7d6dbf57157b5ebd6ad72f46befc94798a5f", "index": 3845, "step-1": "def count_words(word):\n\tcount = 0\n\tcount = len(word.split())\n\treturn count\n\n\nif __name__ == '__main__':\n\tprint count_words(\"Boj is dope\")\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from superwires import games, color import random SCORE = 0 ## pizza_image= games.load_image("images/pizza.png") ## pizza = games.Sprite(image = pizza_image, x=SW/2, y=SH/2, ## dx =1, dy = 1) ## games.screen.add(pizza) games.init(screen_width = 640, screen_height = 480, fps = 50) class Pan(games.Sprite): """ A pan controlled by the mouse. """ def update(self): """ Move to mouse coordinates """ self.x = games.mouse.x #self.y = games.mouse.y self.check_collide() def check_collide(self): """ Check for collision with pizza. """ for pizza in self.overlapping_sprites: pizza.handle_collide() class Pizza(games.Sprite): def update(self): global SCORE #bouncing if self.right > games.screen.width or self.left < 0: self.dx = -self.dx #SCORE += 1 #if self.bottom > games.screen.height or if self.top < 0: self.dy = -self.dy #SCORE += 1 ## if self.left > games.screen.width: ## self.right = 0 ## SCORE +=1 ## if self.right<0: ## self.left = games.screen.width ## SCORE +=1 ## ## if self.top > games.screen.height: ## self.top = 0 ## SCORE +=1 ## if self.bottom < 0: ## self.bottom = games.screen.height ## SCORE +=1 ## def handle_collide(self): #self.x = random.randrange(games.screen.width) self.dy = -self.dy class ScText(games.Text): def update(self): self.value = SCORE def main(): # loaded img bg_img = games.load_image("images/pizzeria.jpg", transparent = True) pizza_img = games.load_image("images/pizza.png") pan_img = games.load_image("images/mousepoint.png") #added img to bg games.screen.background = bg_img #create pizza obj pizza = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2, dx =random.randint(-10,10), dy = random.randint(-10,10)) pizza2 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2, dx =random.randint(-10,10), dy = random.randint(-10,10)) pizza3 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2, dx =random.randint(-10,10), dy = random.randint(-10,10)) pizza4 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2, dx =random.randint(-10,10), dy = random.randint(-10,10)) #create pan obj pan = Pan(image = pan_img, x=games.mouse.x, y=games.mouse.y) #create txt obj score = ScText(value = SCORE, size = 60, is_collideable = False, color = color.black, x = 550, y = 30) #draw objs to screen games.screen.add(pizza) games.screen.add(pizza2) games.screen.add(pizza3) games.screen.add(pizza4) games.screen.add(score) games.screen.add(pan) #sets visibility of mouse while on screen games.mouse.is_visible = False #locks mouse to screen if True games.screen.event_grab = False #start mainloop games.screen.mainloop() #score = games.Text(value = "welcome", size = 60, color = color.black, x = 550, y = 30) games.screen.add(score) #### won_message = games.Message(value = "You lose!", color = color.blue, size = 100, x = games.screen.width/2, y = games.screen.height/2, lifetime = 250, after_death = games.screen.quit) #### games.screen.add(won_message) ##game_over = games.Message(value = "Game Over", ## size = 100, ## color = color.blue, ## x = games.screen.width/2 ## y = games.screen.height/2 ## lifetime = 250, ## after_death = games.screen.quit) ##games.screen.add(game_over) main() ##angle - Facing in degrees ## ##x - x-coordinate ## ##y - y-coordinate ## ##dx - x velocity ## ##dy - y velocity ## ##left - x-coordinate of left sprite edge ## ##right - x-coordinate of right sprite edge ## ##top - y-coordinate of top sprite edge ## ##bottom - y-coordinate of bottom sprite edge ## ##image - image object of sprite ## ##overlapping_sprites - List of other objects that overlap sprite ## ##is_collideable - Whether or not the sprite is collideable. True means sprite will register in collisions. False means sprite will not show up in collisions. ##Methods ## ##update() - Updates sprite. Automatically called every mainloop() cycle. ## ##destroy() - Removes sprite from the screen
normal
{ "blob_id": "ee16b91ce1c12ce78d23ff655304aebc39cb1639", "index": 9693, "step-1": "<mask token>\n\n\nclass Pan(games.Sprite):\n <mask token>\n\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n self.check_collide()\n <mask token>\n\n\nclass Pizza(games.Sprite):\n\n def update(self):\n global SCORE\n if self.right > games.screen.width or self.left < 0:\n self.dx = -self.dx\n if self.top < 0:\n self.dy = -self.dy\n\n def handle_collide(self):\n self.dy = -self.dy\n\n\nclass ScText(games.Text):\n\n def update(self):\n self.value = SCORE\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Pan(games.Sprite):\n \"\"\" A pan controlled by the mouse. \"\"\"\n\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n self.check_collide()\n\n def check_collide(self):\n \"\"\" Check for collision with pizza. \"\"\"\n for pizza in self.overlapping_sprites:\n pizza.handle_collide()\n\n\nclass Pizza(games.Sprite):\n\n def update(self):\n global SCORE\n if self.right > games.screen.width or self.left < 0:\n self.dx = -self.dx\n if self.top < 0:\n self.dy = -self.dy\n\n def handle_collide(self):\n self.dy = -self.dy\n\n\nclass ScText(games.Text):\n\n def update(self):\n self.value = SCORE\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Pan(games.Sprite):\n \"\"\" A pan controlled by the mouse. \"\"\"\n\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n self.check_collide()\n\n def check_collide(self):\n \"\"\" Check for collision with pizza. \"\"\"\n for pizza in self.overlapping_sprites:\n pizza.handle_collide()\n\n\nclass Pizza(games.Sprite):\n\n def update(self):\n global SCORE\n if self.right > games.screen.width or self.left < 0:\n self.dx = -self.dx\n if self.top < 0:\n self.dy = -self.dy\n\n def handle_collide(self):\n self.dy = -self.dy\n\n\nclass ScText(games.Text):\n\n def update(self):\n self.value = SCORE\n\n\ndef main():\n bg_img = games.load_image('images/pizzeria.jpg', transparent=True)\n pizza_img = games.load_image('images/pizza.png')\n pan_img = games.load_image('images/mousepoint.png')\n games.screen.background = bg_img\n pizza = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.screen\n .height / 2, dx=random.randint(-10, 10), dy=random.randint(-10, 10))\n pizza2 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pizza3 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pizza4 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pan = Pan(image=pan_img, x=games.mouse.x, y=games.mouse.y)\n score = ScText(value=SCORE, size=60, is_collideable=False, color=color.\n black, x=550, y=30)\n games.screen.add(pizza)\n games.screen.add(pizza2)\n games.screen.add(pizza3)\n games.screen.add(pizza4)\n games.screen.add(score)\n games.screen.add(pan)\n games.mouse.is_visible = False\n games.screen.event_grab = False\n games.screen.mainloop()\n games.screen.add(score)\n\n\n<mask token>\n", "step-4": "from superwires import games, color\nimport random\nSCORE = 0\ngames.init(screen_width=640, screen_height=480, fps=50)\n\n\nclass Pan(games.Sprite):\n \"\"\" A pan controlled by the mouse. \"\"\"\n\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n self.check_collide()\n\n def check_collide(self):\n \"\"\" Check for collision with pizza. \"\"\"\n for pizza in self.overlapping_sprites:\n pizza.handle_collide()\n\n\nclass Pizza(games.Sprite):\n\n def update(self):\n global SCORE\n if self.right > games.screen.width or self.left < 0:\n self.dx = -self.dx\n if self.top < 0:\n self.dy = -self.dy\n\n def handle_collide(self):\n self.dy = -self.dy\n\n\nclass ScText(games.Text):\n\n def update(self):\n self.value = SCORE\n\n\ndef main():\n bg_img = games.load_image('images/pizzeria.jpg', transparent=True)\n pizza_img = games.load_image('images/pizza.png')\n pan_img = games.load_image('images/mousepoint.png')\n games.screen.background = bg_img\n pizza = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.screen\n .height / 2, dx=random.randint(-10, 10), dy=random.randint(-10, 10))\n pizza2 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pizza3 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pizza4 = Pizza(image=pizza_img, x=games.screen.width / 2, y=games.\n screen.height / 2, dx=random.randint(-10, 10), dy=random.randint(-\n 10, 10))\n pan = Pan(image=pan_img, x=games.mouse.x, y=games.mouse.y)\n score = ScText(value=SCORE, size=60, is_collideable=False, color=color.\n black, x=550, y=30)\n games.screen.add(pizza)\n games.screen.add(pizza2)\n games.screen.add(pizza3)\n games.screen.add(pizza4)\n games.screen.add(score)\n games.screen.add(pan)\n games.mouse.is_visible = False\n games.screen.event_grab = False\n games.screen.mainloop()\n games.screen.add(score)\n\n\nmain()\n", "step-5": "from superwires import games, color\nimport random\n\nSCORE = 0\n\n\n\n\n \n## pizza_image= games.load_image(\"images/pizza.png\")\n## pizza = games.Sprite(image = pizza_image, x=SW/2, y=SH/2,\n## dx =1, dy = 1)\n## games.screen.add(pizza)\n\ngames.init(screen_width = 640, screen_height = 480, fps = 50)\n\nclass Pan(games.Sprite):\n \"\"\" A pan controlled by the mouse. \"\"\"\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n #self.y = games.mouse.y\n self.check_collide()\n def check_collide(self):\n \"\"\" Check for collision with pizza. \"\"\"\n for pizza in self.overlapping_sprites:\n pizza.handle_collide()\n \n \nclass Pizza(games.Sprite):\n\n def update(self):\n global SCORE\n #bouncing \n if self.right > games.screen.width or self.left < 0:\n self.dx = -self.dx\n #SCORE += 1\n\n #if self.bottom > games.screen.height or\n if self.top < 0:\n self.dy = -self.dy\n #SCORE += 1\n \n## if self.left > games.screen.width:\n## self.right = 0\n## SCORE +=1\n## if self.right<0:\n## self.left = games.screen.width\n## SCORE +=1\n##\n## if self.top > games.screen.height:\n## self.top = 0\n## SCORE +=1\n## if self.bottom < 0:\n## self.bottom = games.screen.height\n## SCORE +=1\n## \n def handle_collide(self):\n #self.x = random.randrange(games.screen.width)\n self.dy = -self.dy\n \n\n\nclass ScText(games.Text):\n def update(self):\n self.value = SCORE\n\ndef main():\n # loaded img\n bg_img = games.load_image(\"images/pizzeria.jpg\", transparent = True)\n pizza_img = games.load_image(\"images/pizza.png\")\n pan_img = games.load_image(\"images/mousepoint.png\")\n\n #added img to bg\n games.screen.background = bg_img\n\n #create pizza obj\n pizza = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2,\n dx =random.randint(-10,10), dy = random.randint(-10,10))\n pizza2 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2,\n dx =random.randint(-10,10), dy = random.randint(-10,10))\n pizza3 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2,\n dx =random.randint(-10,10), dy = random.randint(-10,10))\n pizza4 = Pizza(image = pizza_img, x=games.screen.width/2, y=games.screen.height/2,\n dx =random.randint(-10,10), dy = random.randint(-10,10))\n\n #create pan obj\n pan = Pan(image = pan_img, x=games.mouse.x, y=games.mouse.y)\n \n \n \n \n \n\n #create txt obj\n score = ScText(value = SCORE, size = 60,\n is_collideable = False,\n color = color.black,\n x = 550,\n y = 30)\n\n #draw objs to screen\n games.screen.add(pizza)\n games.screen.add(pizza2)\n games.screen.add(pizza3)\n games.screen.add(pizza4)\n games.screen.add(score)\n games.screen.add(pan)\n \n #sets visibility of mouse while on screen\n games.mouse.is_visible = False\n\n #locks mouse to screen if True\n games.screen.event_grab = False\n\n\n #start mainloop\n games.screen.mainloop()\n\n\n #score = games.Text(value = \"welcome\", size = 60, color = color.black, x = 550, y = 30)\n games.screen.add(score)\n\n#### won_message = games.Message(value = \"You lose!\", color = color.blue, size = 100, x = games.screen.width/2, y = games.screen.height/2, lifetime = 250, after_death = games.screen.quit)\n#### games.screen.add(won_message)\n\n##game_over = games.Message(value = \"Game Over\",\n## size = 100,\n## color = color.blue,\n## x = games.screen.width/2\n## y = games.screen.height/2\n## lifetime = 250,\n## after_death = games.screen.quit)\n##games.screen.add(game_over)\n\nmain()\n\n\n\n\n\n##angle - Facing in degrees\n##\n##x - x-coordinate\n##\n##y - y-coordinate\n##\n##dx - x velocity\n##\n##dy - y velocity\n##\n##left - x-coordinate of left sprite edge\n##\n##right - x-coordinate of right sprite edge\n##\n##top - y-coordinate of top sprite edge\n##\n##bottom - y-coordinate of bottom sprite edge\n##\n##image - image object of sprite\n##\n##overlapping_sprites - List of other objects that overlap sprite\n##\n##is_collideable - Whether or not the sprite is collideable. True means sprite will register in collisions. False means sprite will not show up in collisions.\n\n##Methods\n##\n##update() - Updates sprite. Automatically called every mainloop() cycle.\n##\n##destroy() - Removes sprite from the screen\n", "step-ids": [ 7, 9, 10, 13, 14 ] }
[ 7, 9, 10, 13, 14 ]
from collections import deque ''' Big O เวลาเรียก queue จะมี2operation 1deque 2enqueue เวลาเอาไปใช้ อยู่ที่การimplementation โปรแกรมที่ดี 1.ทำงานถูกต้อง 2.ทันใจ 3.ทรัพยากรที่ใช้รันได้ทุกเครื่อง(specคอมกาก) 4.ทำงานได้ตามต้องการ5.ความเสถียรของระบบ 6.Bugs แพง คือ memory expansive ใช้หน่วยความจำเยอะ runtime expensive ใช้เวลาเยอะ เลยเกิด queue linklist โดยแต่ละอย่าง - linklist มีcost มาเกี่ยว - dequeue ใช้ O(1) มันขึ้นกับว่าจำหน่วยตัวข้างในมี10ตัวใช้ 1ms 1ล้านตัวก็ใช้ 1ms เรียกความเร็วคงที่ อีกชื่อ O(1) โอวัน โอหนึ่ง แต่มันในอุดมคติ เวลาใใช้ linklist เก็บตัวชี้และ ข้อมูล มันเลยใช้ หน่วยความจำเป็น2เท่าของ list Big O คือการวิเคราะห์ runing time complexityเปรียบเทียบสองตัวว่าตัวไหนมีประสิทธิภาพดีกว่า แต่Big O ที่ดีกว่าไม่ได้เร็วกว่า เพราะ ขึ้นอยุกับ ความเร็วspecเครื่อง n T(n) 1 1ms 10 10ms 1M 1000s T(N)ผันตามn เรียก O(n) อีกเคส n T(n) 1 1 10 100 1M 1Ms T(N) ผันตาม n^2,n^3,n! จะใช้เวลาเยอะมาก เช่น ให้ทาย อันไหนเร็วสุด 1. O(1) อันดับ1 2. O(n) อันดับ3 3. O(n^2) อันดับ4 4. O(logn) อันดับ2 เวลาใช้ linklist จะมี3ขั้นตอนในการเชื่อม 1.สร้างnodeใหม่ 2.ลิ้งข้อมูลอันเก่ากะอันใหม่ 3.ลิ้งส่วนfront radix sort ดูค่าในแต่ละหลัก 1.รับ input เก็บไว้ในqueue 2.หยิบตัวแรกออกไป 3.มันจะหาว่าตัวไหนmax และมีกี่หลัก 4.จะมีการเทียบ3รอบ รอบที่1 เอาข้อมูลที่ดึงออกมา เก็บไว้ตามหลักในรอบนั้นๆเช่น 64 เลขหลักหน่วยตรงกับหลัก4 ก้เก่บไว้ที่4 ''' class Queue: def __init__(self): self.items=deque() def enQueue(self,i): self.items.append(i) def deQueue(self): return self.items.popleft() def isEmpty(self): return len(self.items)==0 def size(self): return len(self.items) '''class Queue(): def __init__(self,list=None): if list==None: self.items=[] else: self.items=list def enQueue(self,i): self.items.append(i) def deQueue(self): self.items.pop(0) def isQEmpty(self): return len(self.items)==0 def size(self): return len(self.items) ''' if __name__== '__main__': q=Queue() print(q.items) q.enQueue('A') print(q.items) q.deQueue() print(q.items) print(q.isEmpty())
normal
{ "blob_id": "c96a64573fc6cc207ee09be4f4b183d065736ff6", "index": 5442, "step-1": "<mask token>\n\n\nclass Queue:\n\n def __init__(self):\n self.items = deque()\n\n def enQueue(self, i):\n self.items.append(i)\n\n def deQueue(self):\n return self.items.popleft()\n\n def isEmpty(self):\n return len(self.items) == 0\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Queue:\n\n def __init__(self):\n self.items = deque()\n\n def enQueue(self, i):\n self.items.append(i)\n\n def deQueue(self):\n return self.items.popleft()\n\n def isEmpty(self):\n return len(self.items) == 0\n\n def size(self):\n return len(self.items)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Queue:\n\n def __init__(self):\n self.items = deque()\n\n def enQueue(self, i):\n self.items.append(i)\n\n def deQueue(self):\n return self.items.popleft()\n\n def isEmpty(self):\n return len(self.items) == 0\n\n def size(self):\n return len(self.items)\n\n\n<mask token>\nif __name__ == '__main__':\n q = Queue()\n print(q.items)\n q.enQueue('A')\n print(q.items)\n q.deQueue()\n print(q.items)\n print(q.isEmpty())\n", "step-4": "from collections import deque\n<mask token>\n\n\nclass Queue:\n\n def __init__(self):\n self.items = deque()\n\n def enQueue(self, i):\n self.items.append(i)\n\n def deQueue(self):\n return self.items.popleft()\n\n def isEmpty(self):\n return len(self.items) == 0\n\n def size(self):\n return len(self.items)\n\n\n<mask token>\nif __name__ == '__main__':\n q = Queue()\n print(q.items)\n q.enQueue('A')\n print(q.items)\n q.deQueue()\n print(q.items)\n print(q.isEmpty())\n", "step-5": "from collections import deque\r\n'''\r\nBig O \r\nเวลาเรียก queue จะมี2operation 1deque 2enqueue เวลาเอาไปใช้\r\nอยู่ที่การimplementation\r\nโปรแกรมที่ดี 1.ทำงานถูกต้อง 2.ทันใจ 3.ทรัพยากรที่ใช้รันได้ทุกเครื่อง(specคอมกาก)\r\n4.ทำงานได้ตามต้องการ5.ความเสถียรของระบบ 6.Bugs\r\n\r\nแพง คือ memory expansive ใช้หน่วยความจำเยอะ\r\n\truntime expensive ใช้เวลาเยอะ\r\nเลยเกิด queue linklist\r\nโดยแต่ละอย่าง\r\n- linklist มีcost มาเกี่ยว \r\n- dequeue ใช้ O(1) มันขึ้นกับว่าจำหน่วยตัวข้างในมี10ตัวใช้ 1ms 1ล้านตัวก็ใช้ 1ms\r\nเรียกความเร็วคงที่ อีกชื่อ O(1) โอวัน โอหนึ่ง แต่มันในอุดมคติ\r\nเวลาใใช้ linklist เก็บตัวชี้และ ข้อมูล มันเลยใช้ หน่วยความจำเป็น2เท่าของ list\r\n\r\nBig O คือการวิเคราะห์ runing time complexityเปรียบเทียบสองตัวว่าตัวไหนมีประสิทธิภาพดีกว่า\r\nแต่Big O ที่ดีกว่าไม่ได้เร็วกว่า เพราะ ขึ้นอยุกับ ความเร็วspecเครื่อง\r\nn T(n)\r\n1 1ms\r\n10 10ms\r\n1M 1000s\r\nT(N)ผันตามn เรียก O(n)\r\nอีกเคส\r\nn T(n)\r\n1 1\r\n10 100\r\n1M 1Ms\r\nT(N) ผันตาม n^2,n^3,n! จะใช้เวลาเยอะมาก\r\n\r\nเช่น ให้ทาย อันไหนเร็วสุด\r\n1. O(1)\tอันดับ1\r\n2. O(n)\tอันดับ3\r\n3. O(n^2)\tอันดับ4\r\n4. O(logn)\tอันดับ2\r\n\r\n\r\n\r\nเวลาใช้ linklist จะมี3ขั้นตอนในการเชื่อม 1.สร้างnodeใหม่ 2.ลิ้งข้อมูลอันเก่ากะอันใหม่ 3.ลิ้งส่วนfront\r\n\r\nradix sort ดูค่าในแต่ละหลัก\r\n1.รับ input เก็บไว้ในqueue\r\n2.หยิบตัวแรกออกไป\r\n3.มันจะหาว่าตัวไหนmax และมีกี่หลัก\r\n4.จะมีการเทียบ3รอบ รอบที่1 เอาข้อมูลที่ดึงออกมา เก็บไว้ตามหลักในรอบนั้นๆเช่น 64 เลขหลักหน่วยตรงกับหลัก4 ก้เก่บไว้ที่4\r\n'''\r\nclass Queue:\r\n def __init__(self):\r\n self.items=deque()\r\n def enQueue(self,i):\r\n self.items.append(i)\r\n def deQueue(self):\r\n return self.items.popleft()\r\n def isEmpty(self):\r\n return len(self.items)==0\r\n def size(self):\r\n return len(self.items)\r\n'''class Queue(): \r\n def __init__(self,list=None):\r\n if list==None:\r\n self.items=[]\r\n else:\r\n self.items=list\r\n \r\n def enQueue(self,i):\r\n self.items.append(i)\r\n def deQueue(self):\r\n self.items.pop(0)\r\n def isQEmpty(self):\r\n return len(self.items)==0\r\n def size(self):\r\n return len(self.items)\r\n'''\r\nif __name__== '__main__':\r\n q=Queue()\r\n print(q.items)\r\n q.enQueue('A')\r\n print(q.items)\r\n q.deQueue()\r\n print(q.items)\r\n print(q.isEmpty())\r\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
from flask import Flask, render_template, flash, request import pandas as pd from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField df = pd.read_csv('data1.csv') try: row = df[df['District'] == 'Delhi'].index[0] except: print("now city found") DEBUG = True app = Flask(__name__) app.config.from_object(__name__) class ReusableForm(FlaskForm) name = StringField('name', validators=[validators.required()]) submit = SubmitField('Enter') @app.route("/", methods=['GET', 'POST']) def hello(): form = ReusableForm( ) if form.is_submitted(): city = request.form['name'].capitalize() try: row = df[df['District'] == city].index[0] print(city) cases = df.at[row, 'count(district)'] print(cases) except: cases = -1 print("cases are", cases) flash("cases are " + str(cases)) return render_template('data.html', form=form) if __name__ == "__main__": app.run()
normal
{ "blob_id": "8240e6483f47abbe12e7bef02493bd147ad3fec6", "index": 6998, "step-1": "from flask import Flask, render_template, flash, request\nimport pandas as pd\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\n\ndf = pd.read_csv('data1.csv')\ntry:\n row = df[df['District'] == 'Delhi'].index[0]\nexcept:\n print(\"now city found\")\n\nDEBUG = True\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nclass ReusableForm(FlaskForm)\n name = StringField('name', validators=[validators.required()])\n submit = SubmitField('Enter')\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef hello():\n form = ReusableForm( )\n\n if form.is_submitted():\n city = request.form['name'].capitalize()\n try:\n row = df[df['District'] == city].index[0]\n print(city)\n cases = df.at[row, 'count(district)']\n print(cases)\n except:\n cases = -1\n print(\"cases are\", cases)\n flash(\"cases are \" + str(cases))\n\n\t return render_template('data.html', form=form)\n\nif __name__ == \"__main__\":\n app.run()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]